tui-app.test.ts 417 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527
  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.each([true, false])(
  1962. "hydrates the BYOK model and welcome status with managed token %s",
  1963. async (managedTokenPresent) => {
  1964. const terminal = new FakeTerminal();
  1965. const runtime = createRuntime();
  1966. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  1967. status: "ready",
  1968. defaultModel: "custom_provider:innerTest/MiniMax-M3",
  1969. providerId: "custom_provider:innerTest",
  1970. modelId: "MiniMax-M3",
  1971. authMode: "byok",
  1972. managedTokenPresent,
  1973. modelSource: "byok",
  1974. warnings: [],
  1975. });
  1976. vi.mocked(runtime.listModels).mockResolvedValue([
  1977. {
  1978. providerId: "custom_provider:innerTest",
  1979. modelId: "MiniMax-M3",
  1980. displayName: "m3.05",
  1981. selected: true,
  1982. },
  1983. ]);
  1984. const app = createTuiApp({
  1985. runtime,
  1986. terminal,
  1987. version: "0.1.0",
  1988. workspaceDir: "/workspace",
  1989. });
  1990. app.start();
  1991. await app.ready;
  1992. await vi.waitFor(() => expect(app.tui.render(120).join("\n")).toContain("✦ m3.05"));
  1993. const welcome = stripAnsi(app.tui.render(120).join("\n"));
  1994. expect(welcome).toContain("● Ready");
  1995. expect(welcome).not.toContain("Login required");
  1996. expect(welcome).not.toContain("Sign in with /login");
  1997. await app.stop();
  1998. },
  1999. );
  2000. it("restores a managed-login failure to the Composer", async () => {
  2001. const terminal = new FakeTerminal();
  2002. const runtime = createRuntime();
  2003. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2004. status: "ready",
  2005. defaultModel: "minimax/MiniMax-M2.7",
  2006. authMode: "managed-login",
  2007. modelSource: "token-plan",
  2008. managedTokenPresent: false,
  2009. warnings: [],
  2010. });
  2011. const app = createTuiApp({
  2012. runtime,
  2013. terminal,
  2014. version: "0.1.0",
  2015. workspaceDir: "/workspace",
  2016. });
  2017. app.start();
  2018. await app.ready;
  2019. await vi.waitFor(() =>
  2020. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login"),
  2021. );
  2022. terminal.input?.("Keep this until login");
  2023. terminal.input?.("\r");
  2024. await vi.waitFor(() =>
  2025. expect(app.editor.getText()).toBe("Keep this until login"),
  2026. );
  2027. expect(app.tui.render(80).join("\n")).toContain("Keep this until login");
  2028. expect(app.transcript.snapshot()).toEqual(
  2029. expect.arrayContaining([
  2030. expect.objectContaining({
  2031. kind: "warning",
  2032. content:
  2033. "Sign in to MiniMax to use Agent features. Run /login, then retry.",
  2034. }),
  2035. ]),
  2036. );
  2037. expect(runtime.createSession).not.toHaveBeenCalled();
  2038. expect(runtime.sendMessage).not.toHaveBeenCalled();
  2039. await app.stop();
  2040. });
  2041. it("renders an Enter submission before the asynchronous login preflight settles", async () => {
  2042. const terminal = new FakeTerminal();
  2043. const runtime = createRuntime();
  2044. const app = createTuiApp({
  2045. runtime,
  2046. terminal,
  2047. version: "0.1.0",
  2048. workspaceDir: "/workspace",
  2049. });
  2050. app.start();
  2051. await app.ready;
  2052. let resolveAccount:
  2053. | ((
  2054. account: Awaited<ReturnType<typeof runtime.getAccountStatus>>,
  2055. ) => void)
  2056. | undefined;
  2057. vi.mocked(runtime.getAccountStatus).mockImplementationOnce(
  2058. () =>
  2059. new Promise((resolve) => {
  2060. resolveAccount = resolve;
  2061. }),
  2062. );
  2063. const writesBeforeSubmission = terminal.writes.length;
  2064. terminal.input?.("Show this immediately");
  2065. terminal.input?.("\r");
  2066. expect(app.editor.getText()).toBe("");
  2067. expect(
  2068. app.transcript.snapshot().filter((cell) => cell.kind === "user"),
  2069. ).toEqual([
  2070. expect.objectContaining({
  2071. status: "pending",
  2072. content: "Show this immediately",
  2073. }),
  2074. ]);
  2075. await vi.waitFor(() =>
  2076. expect(terminal.writes.length).toBeGreaterThan(writesBeforeSubmission),
  2077. );
  2078. expect(runtime.createSession).not.toHaveBeenCalled();
  2079. expect(runtime.sendMessage).not.toHaveBeenCalled();
  2080. await vi.waitFor(() => expect(resolveAccount).toBeTypeOf("function"));
  2081. resolveAccount?.({
  2082. status: "ready",
  2083. defaultModel: "minimax/MiniMax-M2.7",
  2084. providerId: "minimax",
  2085. modelId: "MiniMax-M2.7",
  2086. authMode: "managed-login",
  2087. managedTokenPresent: true,
  2088. warnings: [],
  2089. });
  2090. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
  2091. await app.stop();
  2092. });
  2093. it("keeps a login-blocked submission editable after current-region sign-in", async () => {
  2094. const terminal = new FakeTerminal();
  2095. const runtime = createRuntime();
  2096. let authenticated = false;
  2097. vi.mocked(runtime.getAccountStatus).mockImplementation(async () =>
  2098. authenticated
  2099. ? {
  2100. status: "ready",
  2101. defaultModel: "minimax/MiniMax-M2.7",
  2102. providerId: "minimax",
  2103. modelId: "MiniMax-M2.7",
  2104. authMode: "managed-login",
  2105. modelSource: "token-plan",
  2106. managedTokenPresent: true,
  2107. warnings: [],
  2108. }
  2109. : {
  2110. status: "needs-login",
  2111. authMode: "managed-login",
  2112. modelSource: "token-plan",
  2113. managedTokenPresent: false,
  2114. warnings: [],
  2115. },
  2116. );
  2117. const auth = {
  2118. login: vi.fn(async () => {
  2119. authenticated = true;
  2120. return {
  2121. state: "authenticated" as const,
  2122. message: "Signed in with MiniMax.",
  2123. };
  2124. }),
  2125. logout: vi.fn(async () => ({
  2126. state: "signed-out" as const,
  2127. message: "Signed out of MiniMax.",
  2128. })),
  2129. };
  2130. const app = createTuiApp({
  2131. runtime,
  2132. auth,
  2133. terminal,
  2134. version: "0.1.0",
  2135. workspaceDir: "/workspace",
  2136. });
  2137. app.start();
  2138. await app.ready;
  2139. terminal.input?.("Send this after login");
  2140. terminal.input?.("\r");
  2141. await vi.waitFor(() =>
  2142. expect(app.editor.getText()).toBe("Send this after login"),
  2143. );
  2144. await app.submit("/login");
  2145. app.interaction.current()?.handleInput("\r");
  2146. expect(runtime.sendMessage).not.toHaveBeenCalled();
  2147. app.editor.handleInput("\r");
  2148. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
  2149. expect(runtime.sendMessage).toHaveBeenCalledWith(
  2150. expect.objectContaining({
  2151. id: "session-1",
  2152. content: "Send this after login",
  2153. turnId: expect.any(String),
  2154. }),
  2155. expect.any(AbortSignal),
  2156. );
  2157. expect(app.transcript.snapshot()).toEqual(
  2158. expect.arrayContaining([
  2159. expect.objectContaining({
  2160. kind: "user",
  2161. content: "Send this after login",
  2162. }),
  2163. ]),
  2164. );
  2165. await app.stop();
  2166. });
  2167. it("runs /checkin immediately for a signed-in MiniMax account", async () => {
  2168. const runtime = createRuntime();
  2169. const app = createTuiApp({
  2170. runtime,
  2171. terminal: new FakeTerminal(),
  2172. version: "0.1.0",
  2173. workspaceDir: "/workspace",
  2174. });
  2175. app.start();
  2176. await app.ready;
  2177. await app.submit("/checkin");
  2178. expect(runtime.runDailyCheckin).toHaveBeenCalledOnce();
  2179. expect(app.transcript.snapshot()).toEqual(
  2180. expect.arrayContaining([
  2181. expect.objectContaining({
  2182. kind: "final-summary",
  2183. content: expect.stringContaining(
  2184. "Checked in: Cycle day 2, +20 Credits",
  2185. ),
  2186. }),
  2187. ]),
  2188. );
  2189. await app.stop();
  2190. });
  2191. it("shows a generic /checkin failure without backend details", async () => {
  2192. const runtime = createRuntime();
  2193. vi.mocked(runtime.runDailyCheckin).mockRejectedValue(
  2194. new Error("internal signin shard rejected request"),
  2195. );
  2196. const app = createTuiApp({
  2197. runtime,
  2198. terminal: new FakeTerminal(),
  2199. version: "0.1.0",
  2200. workspaceDir: "/workspace",
  2201. });
  2202. app.start();
  2203. await app.ready;
  2204. await app.submit("/checkin");
  2205. const transcript = app.transcript
  2206. .snapshot()
  2207. .map((cell) => cell.content)
  2208. .join("\n");
  2209. expect(transcript).toContain("Couldn't complete daily check-in.");
  2210. expect(transcript).not.toContain("internal signin shard");
  2211. await app.stop();
  2212. });
  2213. it("does not open login when /checkin cannot verify account status", async () => {
  2214. const runtime = createRuntime();
  2215. const auth = {
  2216. login: vi.fn(),
  2217. logout: vi.fn(async () => ({
  2218. state: "signed-out" as const,
  2219. message: "Signed out of MiniMax.",
  2220. })),
  2221. };
  2222. const app = createTuiApp({
  2223. runtime,
  2224. auth,
  2225. terminal: new FakeTerminal(),
  2226. version: "0.1.0",
  2227. workspaceDir: "/workspace",
  2228. });
  2229. app.start();
  2230. await app.ready;
  2231. vi.mocked(runtime.getAccountStatus).mockRejectedValue(
  2232. new Error("status unavailable"),
  2233. );
  2234. await app.submit("/checkin");
  2235. expect(app.interaction.current()).toBeUndefined();
  2236. expect(auth.login).not.toHaveBeenCalled();
  2237. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2238. await app.stop();
  2239. });
  2240. it("starts MiniMax login and resumes /checkin once after authentication", async () => {
  2241. const runtime = createRuntime();
  2242. let authenticated = false;
  2243. vi.mocked(runtime.getAccountStatus).mockImplementation(async () => ({
  2244. status: authenticated ? "ready" : "needs-login",
  2245. authMode: "managed-login",
  2246. modelSource: "byok",
  2247. managedTokenPresent: authenticated,
  2248. warnings: [],
  2249. }));
  2250. const auth = {
  2251. login: vi.fn(async () => {
  2252. authenticated = true;
  2253. return {
  2254. state: "authenticated" as const,
  2255. message: "Signed in with MiniMax.",
  2256. };
  2257. }),
  2258. logout: vi.fn(async () => ({
  2259. state: "signed-out" as const,
  2260. message: "Signed out of MiniMax.",
  2261. })),
  2262. };
  2263. const app = createTuiApp({
  2264. runtime,
  2265. auth,
  2266. terminal: new FakeTerminal(),
  2267. version: "0.1.0",
  2268. workspaceDir: "/workspace",
  2269. });
  2270. app.start();
  2271. await app.ready;
  2272. await app.submit("/checkin");
  2273. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2274. app.interaction.current()?.handleInput("\r");
  2275. await vi.waitFor(() =>
  2276. expect(runtime.runDailyCheckin).toHaveBeenCalledOnce(),
  2277. );
  2278. expect(auth.login).toHaveBeenCalledWith(expect.any(Function), "cn");
  2279. await app.stop();
  2280. });
  2281. it("does not resume /checkin when the login picker is cancelled", async () => {
  2282. const runtime = createRuntime();
  2283. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2284. status: "needs-login",
  2285. authMode: "managed-login",
  2286. modelSource: "byok",
  2287. managedTokenPresent: false,
  2288. warnings: [],
  2289. });
  2290. const auth = {
  2291. login: vi.fn(),
  2292. logout: vi.fn(async () => ({
  2293. state: "signed-out" as const,
  2294. message: "Signed out of MiniMax.",
  2295. })),
  2296. };
  2297. const app = createTuiApp({
  2298. runtime,
  2299. auth,
  2300. terminal: new FakeTerminal(),
  2301. version: "0.1.0",
  2302. workspaceDir: "/workspace",
  2303. });
  2304. app.start();
  2305. await app.ready;
  2306. await app.submit("/checkin");
  2307. app.interaction.current()?.handleInput("\u001b");
  2308. expect(auth.login).not.toHaveBeenCalled();
  2309. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2310. await app.stop();
  2311. });
  2312. it("does not resume /checkin when browser login fails", async () => {
  2313. const runtime = createRuntime();
  2314. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2315. status: "needs-login",
  2316. managedTokenPresent: false,
  2317. warnings: [],
  2318. });
  2319. const auth = {
  2320. login: vi.fn(async () => {
  2321. throw new Error("browser login failed");
  2322. }),
  2323. logout: vi.fn(async () => ({
  2324. state: "signed-out" as const,
  2325. message: "Signed out of MiniMax.",
  2326. })),
  2327. };
  2328. const app = createTuiApp({
  2329. runtime,
  2330. auth,
  2331. terminal: new FakeTerminal(),
  2332. version: "0.1.0",
  2333. workspaceDir: "/workspace",
  2334. });
  2335. app.start();
  2336. await app.ready;
  2337. await app.submit("/checkin");
  2338. app.interaction.current()?.handleInput("\r");
  2339. await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
  2340. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2341. await app.stop();
  2342. });
  2343. it("carries /checkin through a cross-region login restart", async () => {
  2344. const runtime = createRuntime();
  2345. const requestRestart = vi.fn();
  2346. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2347. status: "needs-login",
  2348. managedTokenPresent: false,
  2349. warnings: [],
  2350. });
  2351. const auth = {
  2352. login: vi.fn(async () => ({
  2353. state: "authenticated" as const,
  2354. restartRequired: true,
  2355. message: "Signed in with MiniMax Global.",
  2356. })),
  2357. logout: vi.fn(async () => ({
  2358. state: "signed-out" as const,
  2359. message: "Signed out of MiniMax.",
  2360. })),
  2361. };
  2362. const app = createTuiApp({
  2363. runtime,
  2364. auth,
  2365. terminal: new FakeTerminal(),
  2366. version: "0.1.0",
  2367. workspaceDir: "/workspace",
  2368. requestRestart,
  2369. });
  2370. app.start();
  2371. await app.ready;
  2372. await app.submit("/checkin");
  2373. app.interaction.current()?.handleInput("\u001b[B");
  2374. app.interaction.current()?.handleInput("\r");
  2375. await vi.waitFor(() =>
  2376. expect(requestRestart).toHaveBeenCalledWith("en", "/checkin"),
  2377. );
  2378. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2379. await app.stopped;
  2380. });
  2381. it("restarts after cross-region login while keeping the blocked submission", async () => {
  2382. const terminal = new FakeTerminal();
  2383. const runtime = createRuntime();
  2384. const requestRestart = vi.fn();
  2385. const notifyAuthContextChanged = vi.fn(async () => undefined);
  2386. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2387. status: "needs-login",
  2388. authMode: "managed-login",
  2389. modelSource: "token-plan",
  2390. managedTokenPresent: false,
  2391. warnings: [],
  2392. });
  2393. const auth = {
  2394. login: vi.fn(async () => ({
  2395. state: "authenticated" as const,
  2396. restartRequired: true,
  2397. message: "Signed in with MiniMax Global.",
  2398. })),
  2399. logout: vi.fn(async () => ({
  2400. state: "signed-out" as const,
  2401. message: "Signed out of MiniMax.",
  2402. })),
  2403. };
  2404. const app = createTuiApp({
  2405. runtime,
  2406. auth,
  2407. terminal,
  2408. version: "0.1.0",
  2409. workspaceDir: "/workspace",
  2410. requestRestart,
  2411. notifyAuthContextChanged,
  2412. });
  2413. app.start();
  2414. await app.ready;
  2415. terminal.input?.("Keep this through restart");
  2416. terminal.input?.("\r");
  2417. await vi.waitFor(() =>
  2418. expect(app.editor.getText()).toBe("Keep this through restart"),
  2419. );
  2420. await app.submit("/login");
  2421. app.interaction.current()?.handleInput("\u001b[B");
  2422. app.interaction.current()?.handleInput("\r");
  2423. await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
  2424. expect(auth.login).toHaveBeenCalledWith(expect.any(Function), "en");
  2425. expect(runtime.sendMessage).not.toHaveBeenCalled();
  2426. await vi.waitFor(() => expect(requestRestart).toHaveBeenCalledOnce());
  2427. expect(requestRestart).toHaveBeenCalledWith("en");
  2428. expect(notifyAuthContextChanged).not.toHaveBeenCalled();
  2429. await app.stopped;
  2430. expect(app.editor.getText()).toBe("Keep this through restart");
  2431. });
  2432. it("shows ready and runs an unauthenticated builtin BYOK Turn", async () => {
  2433. const runtime = createRuntime();
  2434. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2435. status: "ready",
  2436. defaultModel: "minimax/MiniMax-M3",
  2437. providerId: "minimax",
  2438. authMode: "managed-login",
  2439. modelSource: "byok",
  2440. managedTokenPresent: false,
  2441. warnings: [],
  2442. });
  2443. const app = createTuiApp({
  2444. runtime,
  2445. terminal: new FakeTerminal(),
  2446. version: "0.1.0",
  2447. workspaceDir: "/workspace",
  2448. statusLineItems: ["build-mode"],
  2449. });
  2450. app.start();
  2451. await app.ready;
  2452. const welcome = stripAnsi(app.tui.render(120).join("\n"));
  2453. expect(welcome).toContain("● Ready");
  2454. expect(welcome).toContain("state=ready");
  2455. expect(welcome).not.toContain("Sign in with /login");
  2456. expect(welcome).not.toContain("Login required");
  2457. await app.submit("BYOK still runs");
  2458. expect(runtime.createSession).toHaveBeenCalledWith({
  2459. workspaceDir: "/workspace",
  2460. });
  2461. expect(app.transcript.snapshot()).toEqual(
  2462. expect.arrayContaining([
  2463. expect.objectContaining({ kind: "user", content: "BYOK still runs" }),
  2464. expect.objectContaining({
  2465. kind: "assistant",
  2466. content: "Hello from the Agent",
  2467. }),
  2468. ]),
  2469. );
  2470. await app.stop();
  2471. });
  2472. it("starts a terminal-native workbench and submits messages through the Agent runtime", async () => {
  2473. const terminal = new FakeTerminal();
  2474. const runtime = createRuntime();
  2475. const app = createTuiApp({
  2476. runtime,
  2477. terminal,
  2478. version: "0.1.0",
  2479. workspaceDir: "/workspace",
  2480. homeDir: "/home/dev",
  2481. });
  2482. app.start();
  2483. await app.ready;
  2484. expect(app.getSurface()).toBe("welcome");
  2485. await app.submit("Say hello");
  2486. expect(app.getSurface()).toBe("conversation");
  2487. const conversation = app.tui.render(80).join("\n");
  2488. expect(conversation).toContain("Tips for getting started");
  2489. expect(conversation).toContain("Say hello");
  2490. expect(conversation).toContain("Hello from the Agent");
  2491. expect(terminal.started).toBe(true);
  2492. expect(terminal.title).toBe("Minimax Code");
  2493. expect(runtime.createSession).toHaveBeenCalledWith({
  2494. workspaceDir: "/workspace",
  2495. });
  2496. expect(app.transcript.snapshot()).toEqual([
  2497. expect.objectContaining({ kind: "user", content: "Say hello" }),
  2498. expect.objectContaining({
  2499. kind: "assistant",
  2500. status: "succeeded",
  2501. content: "Hello from the Agent",
  2502. }),
  2503. expect.objectContaining({ kind: "turn-duration", status: "succeeded" }),
  2504. ]);
  2505. await app.stop();
  2506. expect(terminal.stopped).toBe(true);
  2507. });
  2508. it("syncs the generated Session title to the terminal without duplicate writes", async () => {
  2509. const terminal = new FakeTerminal();
  2510. const runtime = createRuntime();
  2511. let sessionTitle = "New session";
  2512. let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  2513. vi.mocked(runtime.listSessions).mockImplementation(async () => [
  2514. {
  2515. sessionId: "session-1",
  2516. title: sessionTitle,
  2517. workspaceDir: "/workspace",
  2518. },
  2519. ]);
  2520. vi.mocked(runtime.watchEvents).mockImplementation(
  2521. async function* watchEvents(signal) {
  2522. const event = await new Promise<TuiRuntimeEvent | undefined>(
  2523. (resolve) => {
  2524. emitEvent = resolve;
  2525. signal.addEventListener("abort", () => resolve(undefined), {
  2526. once: true,
  2527. });
  2528. },
  2529. );
  2530. if (event) yield event;
  2531. await new Promise<void>((resolve) => {
  2532. signal.addEventListener("abort", resolve, { once: true });
  2533. });
  2534. },
  2535. );
  2536. const app = createTuiApp({
  2537. runtime,
  2538. terminal,
  2539. version: "0.1.0",
  2540. workspaceDir: "/workspace",
  2541. });
  2542. app.start();
  2543. await app.ready;
  2544. await app.submit("Review uncommitted work");
  2545. await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
  2546. sessionTitle = "Review uncommitted work";
  2547. emitEvent?.(
  2548. runtimeEvent({
  2549. type: "session.title_updated",
  2550. timestamp: Date.now(),
  2551. source: "runtime",
  2552. payload: {
  2553. sessionId: "session-1",
  2554. title: sessionTitle,
  2555. },
  2556. }),
  2557. );
  2558. await vi.waitFor(() => expect(terminal.title).toBe(sessionTitle));
  2559. await app.submit("/status");
  2560. expect(terminal.titleUpdates).toEqual(["Minimax Code", sessionTitle]);
  2561. await app.stop();
  2562. });
  2563. it("keeps chat state alive while a regular feature overlay owns the viewport", async () => {
  2564. const terminal = new FakeTerminal();
  2565. terminal.rows = 6;
  2566. const runtime = createRuntime();
  2567. const app = createTuiApp({
  2568. runtime,
  2569. terminal,
  2570. version: "0.1.0",
  2571. workspaceDir: "/workspace",
  2572. });
  2573. const featureInput = vi.fn();
  2574. const featureContent = {
  2575. render: () => ["feature-header", "feature-body"],
  2576. invalidate: () => undefined,
  2577. };
  2578. const feature = {
  2579. id: "sessions",
  2580. layoutRoot: new VStack([{ component: featureContent }]),
  2581. render: featureContent.render,
  2582. invalidate: () => undefined,
  2583. handleInput: featureInput,
  2584. };
  2585. app.start();
  2586. await app.ready;
  2587. const screen = new VirtualTerminalScreen(terminal.columns, terminal.rows);
  2588. let writeIndex = 0;
  2589. const flushWrites = (): void => {
  2590. for (; writeIndex < terminal.writes.length; writeIndex += 1) {
  2591. screen.feed(terminal.writes[writeIndex] ?? "");
  2592. }
  2593. };
  2594. flushWrites();
  2595. app.editor.setText("preserved draft");
  2596. const handle = app.surfaceHost.pushFeature({ screen: feature });
  2597. app.tui.renderNow();
  2598. flushWrites();
  2599. expect(app.surfaceHost.getActiveSurface()).toEqual({
  2600. kind: "feature",
  2601. id: "sessions",
  2602. });
  2603. expect(app.surfaceHost.render(80).join("\n")).toContain("preserved draft");
  2604. expect(screen.viewportText()).toContain("feature-header");
  2605. expect(screen.viewportText()).toContain("feature-body");
  2606. expect(app.tui.mode).toBe("regular");
  2607. expect(terminal.startCount).toBe(1);
  2608. expect(terminal.stopCount).toBe(0);
  2609. terminal.input?.("j");
  2610. expect(featureInput).toHaveBeenCalledWith("j");
  2611. expect(handle.close()).toBe(true);
  2612. app.tui.renderNow();
  2613. flushWrites();
  2614. expect(app.surfaceHost.getActiveSurface()).toEqual({
  2615. kind: "chat",
  2616. id: "chat",
  2617. });
  2618. expect(app.editor.getText()).toBe("preserved draft");
  2619. expect(app.surfaceHost.render(80).join("\n")).toContain("preserved draft");
  2620. expect(screen.viewportText()).toContain("preserved draft");
  2621. expect(screen.viewportText()).not.toContain("feature-header");
  2622. await app.stop();
  2623. screen.dispose();
  2624. });
  2625. it("switches /settings through explicit choices and closes after applying", async () => {
  2626. const terminal = new FakeTerminal();
  2627. const persistTuiMode = vi.fn();
  2628. const app = createTuiApp({
  2629. runtime: createRuntime(),
  2630. terminal,
  2631. version: "0.2.0",
  2632. workspaceDir: "/workspace",
  2633. tuiMode: "regular",
  2634. persistTuiMode,
  2635. });
  2636. app.start();
  2637. await app.ready;
  2638. expect(app.surfaceHost.getChatMode()).toBe("regular");
  2639. expect(app.tui.mode).toBe("regular");
  2640. await app.submit("/settings");
  2641. const fullscreenSettings = app.interaction.current();
  2642. expect(app.tui.getFocusedComponent()).toBe(fullscreenSettings);
  2643. expect(app.surfaceHost.render(80).join("\n")).toContain(
  2644. "TUI mode · Regular",
  2645. );
  2646. terminal.input?.("\u001b[B");
  2647. terminal.input?.("\r");
  2648. expect(app.surfaceHost.getChatMode()).toBe("fullscreen");
  2649. expect(app.tui.mode).toBe("fullscreen");
  2650. expect(app.interaction.isActive()).toBe(false);
  2651. expect(app.tui.getFocusedComponent()).toBe(app.editor);
  2652. expect(persistTuiMode).toHaveBeenLastCalledWith("fullscreen");
  2653. expect(app.editor.focused).toBe(true);
  2654. terminal.input?.("/");
  2655. await vi.waitFor(() =>
  2656. expect(app.editor.render(60).join("\n")).toContain(
  2657. "Show available commands",
  2658. ),
  2659. );
  2660. terminal.input?.("\u001b");
  2661. app.editor.setText("");
  2662. await app.submit("/settings");
  2663. const regularSettings = app.interaction.current();
  2664. expect(app.tui.getFocusedComponent()).toBe(regularSettings);
  2665. expect(app.surfaceHost.render(80).join("\n")).toContain(
  2666. "TUI mode · Fullscreen",
  2667. );
  2668. terminal.input?.("\u001b[A");
  2669. terminal.input?.("\r");
  2670. expect(app.surfaceHost.getChatMode()).toBe("regular");
  2671. expect(app.tui.mode).toBe("regular");
  2672. expect(app.interaction.isActive()).toBe(false);
  2673. expect(app.tui.getFocusedComponent()).toBe(app.editor);
  2674. expect(persistTuiMode).toHaveBeenLastCalledWith("regular");
  2675. await app.stop();
  2676. });
  2677. it("keeps the Pi Editor and Slash Command autocomplete active in fullscreen chat", async () => {
  2678. const terminal = new FakeTerminal();
  2679. terminal.rows = 8;
  2680. const app = createTuiApp({
  2681. runtime: createRuntime(),
  2682. terminal,
  2683. version: "0.2.0",
  2684. workspaceDir: "/workspace",
  2685. tuiMode: "fullscreen",
  2686. });
  2687. app.start();
  2688. await app.ready;
  2689. terminal.input?.("/");
  2690. await vi.waitFor(() =>
  2691. expect(app.editor.render(60).join("\n")).toContain(
  2692. "Show available commands",
  2693. ),
  2694. );
  2695. expect(app.editor.getText()).toBe("/");
  2696. terminal.input?.("\u001B[B");
  2697. expect(app.editor.getText()).toBe("/");
  2698. terminal.input?.("\u001B");
  2699. expect(app.editor.getText()).toBe("/");
  2700. expect(app.editor.focused).toBe(true);
  2701. await app.stop();
  2702. });
  2703. it("renders regular-mode Slash Command autocomplete on the first keypress and every update", async () => {
  2704. const terminal = new FakeTerminal();
  2705. const app = createTuiApp({
  2706. runtime: createRuntime(),
  2707. terminal,
  2708. version: "0.2.0",
  2709. workspaceDir: "/workspace",
  2710. tuiMode: "regular",
  2711. });
  2712. app.start();
  2713. await app.ready;
  2714. const screen = new VirtualTerminalScreen(terminal.columns, terminal.rows);
  2715. let writeIndex = 0;
  2716. const flushWrites = (): void => {
  2717. for (; writeIndex < terminal.writes.length; writeIndex += 1) {
  2718. screen.feed(terminal.writes[writeIndex] ?? "");
  2719. }
  2720. };
  2721. flushWrites();
  2722. terminal.input?.("/");
  2723. await vi.waitFor(() => {
  2724. flushWrites();
  2725. expect(screen.viewportText()).toContain("Show available commands");
  2726. });
  2727. expect(screen.viewportText()).toContain("/");
  2728. terminal.input?.("m");
  2729. await vi.waitFor(() => {
  2730. flushWrites();
  2731. expect(screen.viewportText()).toContain("Choose a model");
  2732. });
  2733. expect(screen.viewportText()).toContain("/m");
  2734. screen.dispose();
  2735. await app.stop();
  2736. });
  2737. it("resumes fullscreen tail following when submitting from scrolled history", async () => {
  2738. const terminal = new FakeTerminal();
  2739. terminal.rows = 6;
  2740. const app = createTuiApp({
  2741. runtime: createRuntime(),
  2742. terminal,
  2743. version: "0.2.0",
  2744. workspaceDir: "/workspace",
  2745. tuiMode: "fullscreen",
  2746. });
  2747. app.start();
  2748. await app.ready;
  2749. for (let index = 1; index <= 4; index += 1) {
  2750. await app.submit(`Prompt ${String(index)}`);
  2751. }
  2752. app.tui.renderNow();
  2753. terminal.input?.("\u001B[5~");
  2754. expect((app.tui as TuiAltScreen).isFollowingOutput).toBe(false);
  2755. await app.submit("Latest prompt");
  2756. expect((app.tui as TuiAltScreen).isFollowingOutput).toBe(true);
  2757. await app.stop();
  2758. });
  2759. it("stops the terminal without waiting for a stalled Desktop event stream", async () => {
  2760. const terminal = new FakeTerminal();
  2761. const runtime = createRuntime();
  2762. vi.mocked(runtime.watchEvents).mockImplementation(
  2763. async function* watchEvents() {
  2764. await new Promise<void>(() => undefined);
  2765. yield runtimeEvent({
  2766. type: "unreachable",
  2767. timestamp: 0,
  2768. source: "test",
  2769. payload: {},
  2770. });
  2771. },
  2772. );
  2773. const app = createTuiApp({
  2774. runtime,
  2775. terminal,
  2776. version: "0.1.0",
  2777. workspaceDir: "/workspace",
  2778. });
  2779. app.start();
  2780. await app.ready;
  2781. const stopping = app.stop();
  2782. await vi.waitFor(() => expect(terminal.stopped).toBe(true));
  2783. await stopping;
  2784. });
  2785. it("restores the terminal before a stalled remote turn abort finishes", async () => {
  2786. const terminal = new FakeTerminal();
  2787. const runtime = createRuntime();
  2788. let finishRemoteAbort: ((value: boolean) => void) | undefined;
  2789. vi.mocked(runtime.sendMessage).mockImplementation(
  2790. async function* sendMessage(_req: SendMessageReq, signal?: AbortSignal) {
  2791. await new Promise<void>((resolve) => {
  2792. signal?.addEventListener("abort", () => resolve(), { once: true });
  2793. });
  2794. yield { type: "done" };
  2795. },
  2796. );
  2797. vi.mocked(runtime.abortSession).mockImplementation(
  2798. async () =>
  2799. await new Promise<boolean>((resolve) => {
  2800. finishRemoteAbort = resolve;
  2801. }),
  2802. );
  2803. const app = createTuiApp({
  2804. runtime,
  2805. terminal,
  2806. version: "0.1.0",
  2807. workspaceDir: "/workspace",
  2808. });
  2809. app.start();
  2810. await app.ready;
  2811. const submitting = app.submit("Keep running");
  2812. await vi.waitFor(() =>
  2813. expect(app.controller.snapshot().status).toBe("running"),
  2814. );
  2815. const stopping = app.stop();
  2816. await vi.waitFor(() => expect(terminal.stopped).toBe(true));
  2817. finishRemoteAbort?.(true);
  2818. await Promise.all([submitting, stopping]);
  2819. });
  2820. it("stops the active turn before leaving the UI", async () => {
  2821. const terminal = new FakeTerminal();
  2822. const runtime = createRuntime();
  2823. let finishTurn: (() => void) | undefined;
  2824. vi.mocked(runtime.sendMessage).mockImplementation(
  2825. async function* sendMessage() {
  2826. yield {
  2827. type: "delta",
  2828. turnId: "turn-detached",
  2829. role: "assistant",
  2830. content: "Still running",
  2831. };
  2832. await new Promise<void>((resolve) => {
  2833. finishTurn = resolve;
  2834. });
  2835. yield { type: "done", turnId: "turn-detached" };
  2836. },
  2837. );
  2838. const app = createTuiApp({
  2839. runtime,
  2840. terminal,
  2841. version: "0.1.0",
  2842. workspaceDir: "/workspace",
  2843. });
  2844. app.start();
  2845. await app.ready;
  2846. const submitting = app.submit("Keep running after the UI leaves");
  2847. await vi.waitFor(() =>
  2848. expect(app.controller.snapshot().status).toBe("running"),
  2849. );
  2850. await app.leaveUi();
  2851. expect(terminal.stopped).toBe(true);
  2852. expect(runtime.abortSession).toHaveBeenCalledWith(
  2853. expect.objectContaining({ id: "session-1" }),
  2854. );
  2855. finishTurn?.();
  2856. await submitting;
  2857. });
  2858. it("resumes a launcher-selected Session and exposes its ID for the exit hint", async () => {
  2859. const terminal = new FakeTerminal();
  2860. const runtime = createRuntime();
  2861. const app = createTuiApp({
  2862. runtime,
  2863. terminal,
  2864. version: "0.1.0",
  2865. workspaceDir: "/workspace",
  2866. });
  2867. app.start();
  2868. await app.ready;
  2869. expect(app.controller.snapshot().session?.sessionId).toBeUndefined();
  2870. await app.openSession("session-existing");
  2871. expect(runtime.getSession).toHaveBeenCalledWith("session-existing");
  2872. expect(runtime.getMessages).toHaveBeenCalledWith("session-existing");
  2873. expect(app.controller.snapshot().session?.sessionId).toBe(
  2874. "session-existing",
  2875. );
  2876. await app.leaveUi();
  2877. });
  2878. it("reports a launcher continue hydration failure in the Transcript", async () => {
  2879. const terminal = new FakeTerminal();
  2880. const runtime = createRuntime();
  2881. vi.mocked(runtime.listSessions).mockResolvedValue([
  2882. {
  2883. sessionId: "session-existing",
  2884. title: "Existing session",
  2885. workspaceDir: "/workspace",
  2886. },
  2887. ]);
  2888. vi.mocked(runtime.getSession).mockRejectedValue(
  2889. new Error("Session hydration failed"),
  2890. );
  2891. const app = createTuiApp({
  2892. runtime,
  2893. terminal,
  2894. version: "0.1.0",
  2895. workspaceDir: "/workspace",
  2896. });
  2897. await app.ready;
  2898. await expect(app.continueLatestSession()).rejects.toThrow(
  2899. "Session hydration failed",
  2900. );
  2901. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  2902. kind: "error",
  2903. content:
  2904. "Couldn't continue the latest conversation: Session hydration failed. Retry after the connection recovers.",
  2905. });
  2906. await app.leaveUi();
  2907. });
  2908. it("can disable queue UI and preserve the next draft while a turn is running", async () => {
  2909. const terminal = new FakeTerminal();
  2910. const runtime = createRuntime();
  2911. let finishTool: (() => void) | undefined;
  2912. vi.mocked(runtime.sendMessage).mockImplementation(
  2913. async function* sendMessage() {
  2914. yield {
  2915. type: "delta",
  2916. turnId: "turn-running-tool",
  2917. toolCalls: [
  2918. {
  2919. id: "read-1",
  2920. name: "read",
  2921. status: "running",
  2922. input: { path: "src/cart/price.ts" },
  2923. },
  2924. ],
  2925. };
  2926. await new Promise<void>((resolve) => {
  2927. finishTool = resolve;
  2928. });
  2929. yield { type: "done", turnId: "turn-running-tool" };
  2930. },
  2931. );
  2932. const app = createTuiApp({
  2933. runtime,
  2934. terminal,
  2935. version: "0.1.0",
  2936. workspaceDir: "/workspace",
  2937. productFeatures: { queue: false },
  2938. });
  2939. await app.ready;
  2940. const submission = app.submit("Inspect the pricing logic");
  2941. await vi.waitFor(() => {
  2942. const rendered = app.tui.render(80).join("\n");
  2943. expect(rendered).toContain("Reading (src/cart/price.ts)");
  2944. expect(rendered).toContain("Running");
  2945. expect(rendered).not.toContain("Running · 0s");
  2946. expect(rendered).not.toContain("Running · Read");
  2947. expect(rendered).not.toContain("MCode · Running");
  2948. expect(rendered).toContain("Ctrl+O details");
  2949. expect(rendered).toContain("Esc stop");
  2950. expect(rendered).not.toContain("Enter run next");
  2951. expect(rendered).not.toContain("Message · Enter send");
  2952. expect(rendered).not.toContain("Follow-up");
  2953. expect(rendered).not.toContain("waiting");
  2954. });
  2955. await app.submit("Review the tests next");
  2956. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  2957. expect(app.editor.getText()).toBe("Review the tests next");
  2958. expect(app.tui.render(80).join("\n")).toContain("Esc to interrupt");
  2959. finishTool?.();
  2960. await submission;
  2961. });
  2962. it("refreshes the running queue hint from the same bindings as the hotkeys panel", async () => {
  2963. const keybindings = createTuiHostKeybindings({
  2964. platform: "linux",
  2965. suspendSupported: true,
  2966. });
  2967. const runtime = createRuntime();
  2968. let finishTurn: (() => void) | undefined;
  2969. vi.mocked(runtime.sendMessage).mockImplementation(
  2970. async function* sendMessage() {
  2971. yield {
  2972. type: "delta",
  2973. turnId: "turn-custom-queue",
  2974. thinking: "Inspecting the repository",
  2975. };
  2976. await new Promise<void>((resolve) => {
  2977. finishTurn = resolve;
  2978. });
  2979. yield { type: "done", turnId: "turn-custom-queue" };
  2980. },
  2981. );
  2982. const app = createTuiApp({
  2983. runtime,
  2984. terminal: new FakeTerminal(),
  2985. version: "0.1.0",
  2986. workspaceDir: "/workspace",
  2987. keybindings: keybindings.registry,
  2988. });
  2989. await app.ready;
  2990. keybindings.manager.setUserBindings({ "run.queue-draft": "ctrl+enter" });
  2991. const submission = app.submit("Inspect the repository");
  2992. try {
  2993. await vi.waitFor(() => {
  2994. const rendered = stripAnsi(app.tui.render(100).join("\n"));
  2995. expect(rendered).toContain("Running");
  2996. expect(rendered).toContain("Ctrl+Enter queue");
  2997. expect(rendered).not.toContain("Alt+Enter queue");
  2998. expect(
  2999. keybindings.registry
  3000. .helpRows()
  3001. .find((row) => row.ids.includes("run.queue-draft"))?.keys,
  3002. ).toBe("Ctrl+Enter");
  3003. });
  3004. } finally {
  3005. finishTurn?.();
  3006. await submission;
  3007. await app.stop();
  3008. }
  3009. });
  3010. it("shows running Thinking in chat and opens the full Transcript with /transcript", async () => {
  3011. const terminal = new FakeTerminal();
  3012. const runtime = createRuntime();
  3013. let finishThinking: (() => void) | undefined;
  3014. vi.mocked(runtime.sendMessage).mockImplementation(
  3015. async function* sendMessage() {
  3016. yield {
  3017. type: "delta",
  3018. turnId: "turn-running-thinking",
  3019. thinking: "Inspecting the repository",
  3020. };
  3021. await new Promise<void>((resolve) => {
  3022. finishThinking = resolve;
  3023. });
  3024. yield { type: "done", turnId: "turn-running-thinking" };
  3025. },
  3026. );
  3027. const app = createTuiApp({
  3028. runtime,
  3029. terminal,
  3030. version: "0.1.0",
  3031. workspaceDir: "/workspace",
  3032. });
  3033. app.start();
  3034. await app.ready;
  3035. const submission = app.submit("Inspect the repository");
  3036. const countThinkingBodyRows = (rendered: string): number =>
  3037. rendered
  3038. .split("\n")
  3039. .filter(
  3040. (line) =>
  3041. line.includes("Inspecting the repository") &&
  3042. !line.includes("MCode"),
  3043. ).length;
  3044. let expandedThinkingRows = 0;
  3045. try {
  3046. await vi.waitFor(() => {
  3047. const thinking = app.transcript
  3048. .snapshot()
  3049. .find((cell) => cell.kind === "thinking");
  3050. expect(thinking?.content).toBe("Inspecting the repository");
  3051. expect(thinking?.expanded).toBeUndefined();
  3052. const rendered = app.tui.render(80).join("\n");
  3053. expect(rendered).toContain("Running");
  3054. expect(rendered).not.toContain("Running · 0s");
  3055. expect(rendered).toContain(`${formatTuiShortcut("alt+enter")} queue`);
  3056. expect(rendered).toContain("Enter steer");
  3057. expect(rendered).not.toContain(`${formatTuiShortcut("ctrl+x")} steer`);
  3058. expect(rendered).toContain("Ctrl+O details");
  3059. expect(rendered).toContain("Esc stop");
  3060. expect(rendered).toContain("Thinking…");
  3061. expect(rendered).not.toContain("MCode ·");
  3062. expect(rendered).not.toContain("Thinking · Inspecting the repository");
  3063. expandedThinkingRows = countThinkingBodyRows(rendered);
  3064. expect(expandedThinkingRows).toBeGreaterThan(0);
  3065. });
  3066. await app.submit("/transcript");
  3067. await vi.waitFor(() => {
  3068. const rendered = renderTerminalViewport(app, terminal);
  3069. expect(app.surfaceHost.getActiveSurface()).toEqual({
  3070. kind: "feature",
  3071. id: "transcript",
  3072. });
  3073. expect(rendered).toContain("Transcript");
  3074. expect(rendered).not.toContain("Inspecting the repository");
  3075. expect(countThinkingBodyRows(rendered)).toBeLessThan(
  3076. expandedThinkingRows,
  3077. );
  3078. });
  3079. terminal.input?.("\x14");
  3080. expect(app.surfaceHost.getActiveSurface()).toEqual({
  3081. kind: "feature",
  3082. id: "transcript",
  3083. });
  3084. finishThinking?.();
  3085. finishThinking = undefined;
  3086. await submission;
  3087. expect(app.surfaceHost.getActiveSurface()).toEqual({
  3088. kind: "feature",
  3089. id: "transcript",
  3090. });
  3091. expect(app.controller.snapshot().activeTurnId).toBeUndefined();
  3092. expect(
  3093. app.transcript.snapshot().find((cell) => cell.kind === "thinking"),
  3094. ).toMatchObject({
  3095. status: "succeeded",
  3096. });
  3097. terminal.input?.("\u001B");
  3098. await vi.waitFor(() => {
  3099. const rendered = app.tui.render(80).join("\n");
  3100. expect(app.surfaceHost.getActiveSurface()).toEqual({
  3101. kind: "chat",
  3102. id: "chat",
  3103. });
  3104. expect(rendered).toContain("Message · Enter send");
  3105. expect(rendered).not.toContain("Running");
  3106. });
  3107. } finally {
  3108. finishThinking?.();
  3109. await submission;
  3110. await app.stop();
  3111. }
  3112. });
  3113. it("toggles hidden and full inline Tool output with Ctrl+O", async () => {
  3114. const terminal = new FakeTerminal();
  3115. const app = createTuiApp({
  3116. runtime: createRuntime(),
  3117. terminal,
  3118. version: "0.1.0",
  3119. workspaceDir: "/workspace",
  3120. });
  3121. app.start();
  3122. await app.ready;
  3123. app.transcript.upsert({
  3124. id: "tool-detail-toggle",
  3125. kind: "tool",
  3126. status: "succeeded",
  3127. title: "bash",
  3128. content: '{"command":"pnpm test"}',
  3129. detail: [
  3130. "result line 1",
  3131. "result line 2",
  3132. "result line 3",
  3133. "result line 4",
  3134. ].join("\n"),
  3135. createdAtMs: 1,
  3136. });
  3137. expect(app.tui.render(80).join("\n")).not.toContain("result line 1");
  3138. expect(app.tui.render(80).join("\n")).not.toContain("result line 4");
  3139. terminal.input?.("\x0f");
  3140. const detailed = app.tui.render(80).join("\n");
  3141. expect(detailed).toContain("result line 1");
  3142. expect(detailed).toContain("result line 3");
  3143. expect(detailed).toContain("result line 4");
  3144. expect(detailed).not.toContain("Details expanded");
  3145. terminal.input?.("\x0f");
  3146. const compact = app.tui.render(80).join("\n");
  3147. expect(compact).not.toContain("result line 1");
  3148. expect(compact).not.toContain("result line 3");
  3149. expect(compact).not.toContain("result line 4");
  3150. expect(compact).not.toContain("Details collapsed");
  3151. await app.stop();
  3152. });
  3153. it("uses Ctrl+T for tasks while Ctrl+O remains scoped to transcript details", async () => {
  3154. const terminal = new FakeTerminal();
  3155. const app = createTuiApp({
  3156. runtime: createRuntime(),
  3157. terminal,
  3158. version: "0.1.0",
  3159. workspaceDir: "/workspace",
  3160. });
  3161. app.start();
  3162. await app.ready;
  3163. app.controller.applyRuntimeTurnEvent("turn-todo", {
  3164. type: "generic",
  3165. eventType: "todo_updated",
  3166. turnId: "turn-todo",
  3167. data: {
  3168. todos: [
  3169. { content: "Inspect Desktop behavior", status: "completed" },
  3170. { content: "Polish the task rail", status: "in_progress" },
  3171. { content: "Run focused tests", status: "pending" },
  3172. { content: "Review narrow layouts", status: "pending" },
  3173. { content: "Update user documentation", status: "pending" },
  3174. { content: "Publish the test package", status: "pending" },
  3175. ],
  3176. },
  3177. });
  3178. const compact = app.tui.render(80).join("\n");
  3179. expect(compact).toContain("✓ Inspect Desktop behavior");
  3180. expect(compact).toContain("● Polish the task rail");
  3181. expect(compact).toContain("Ctrl+T expand");
  3182. expect(compact).not.toContain("Publish the test package");
  3183. expect(compact).not.toContain("todo_updated");
  3184. terminal.input?.("\x0f");
  3185. const transcriptDetailed = app.tui.render(80).join("\n");
  3186. expect(transcriptDetailed).toContain("Ctrl+T expand");
  3187. expect(transcriptDetailed).not.toContain("Publish the test package");
  3188. terminal.input?.("\x14");
  3189. const tasksExpanded = app.tui.render(80).join("\n");
  3190. expect(tasksExpanded).toContain(
  3191. "Todo list 1/6 · 5 remaining · Ctrl+T compact",
  3192. );
  3193. expect(tasksExpanded).toContain("Publish the test package");
  3194. terminal.input?.("\x0f");
  3195. expect(app.tui.render(80).join("\n")).toContain("Publish the test package");
  3196. app.controller.applyRuntimeTurnEvent("turn-todo", {
  3197. type: "generic",
  3198. eventType: "todo_updated",
  3199. turnId: "turn-todo",
  3200. data: {
  3201. todos: [
  3202. { content: "Inspect Desktop behavior", status: "completed" },
  3203. { content: "Polish the task rail", status: "completed" },
  3204. { content: "Run focused tests", status: "completed" },
  3205. { content: "Review narrow layouts", status: "completed" },
  3206. { content: "Update user documentation", status: "completed" },
  3207. { content: "Publish the test package", status: "completed" },
  3208. ],
  3209. },
  3210. });
  3211. expect(app.tui.render(80).join("\n")).toContain(
  3212. "✓ Todo list 6/6 completed",
  3213. );
  3214. await app.stop();
  3215. });
  3216. it("keeps settled Thinking hidden until Ctrl+O requests transcript details", async () => {
  3217. const terminal = new FakeTerminal();
  3218. const app = createTuiApp({
  3219. runtime: createRuntime(),
  3220. terminal,
  3221. version: "0.1.0",
  3222. workspaceDir: "/workspace",
  3223. });
  3224. app.start();
  3225. await app.ready;
  3226. app.transcript.upsert({
  3227. id: "thinking-detail-toggle",
  3228. kind: "thinking",
  3229. status: "succeeded",
  3230. content: "Private settled reasoning",
  3231. durationMs: 3_200,
  3232. createdAtMs: 1,
  3233. updatedAtMs: 3_201,
  3234. });
  3235. const compact = app.tui.render(80).join("\n");
  3236. expect(compact).toContain("Thought for 3.2s");
  3237. expect(compact).not.toContain("Private settled reasoning");
  3238. terminal.input?.("\x0f");
  3239. expect(app.tui.render(80).join("\n")).toContain(
  3240. "Private settled reasoning",
  3241. );
  3242. terminal.input?.("\x0f");
  3243. expect(app.tui.render(80).join("\n")).not.toContain(
  3244. "Private settled reasoning",
  3245. );
  3246. await app.stop();
  3247. });
  3248. it("returns from the conversation surface to Welcome after /new", async () => {
  3249. const terminal = new FakeTerminal();
  3250. const runtime = createRuntime();
  3251. const app = createTuiApp({
  3252. runtime,
  3253. terminal,
  3254. version: "0.1.0",
  3255. workspaceDir: "/workspace",
  3256. });
  3257. await app.ready;
  3258. await app.submit("Start a conversation");
  3259. expect(app.getSurface()).toBe("conversation");
  3260. await app.submit("/new");
  3261. expect(app.getSurface()).toBe("welcome");
  3262. expect(app.transcript.snapshot()).toEqual([]);
  3263. });
  3264. it("clears into a fresh conversation while keeping the previous session resumable", async () => {
  3265. const terminal = new FakeTerminal();
  3266. const runtime = createRuntime();
  3267. const app = createTuiApp({
  3268. runtime,
  3269. terminal,
  3270. version: "0.1.0",
  3271. workspaceDir: "/workspace",
  3272. });
  3273. await app.ready;
  3274. await app.submit("Keep this conversation");
  3275. expect(app.controller.snapshot().session?.sessionId).toBe("session-1");
  3276. await app.submit("/clear");
  3277. expect(app.getSurface()).toBe("welcome");
  3278. expect(app.transcript.snapshot()).toEqual([]);
  3279. expect(app.controller.snapshot()).toMatchObject({
  3280. status: "idle",
  3281. session: undefined,
  3282. sessions: [expect.objectContaining({ sessionId: "session-1" })],
  3283. });
  3284. expect(runtime.archiveSession).not.toHaveBeenCalled();
  3285. });
  3286. it("opens read-only Help above the Composer without using a TUI overlay", async () => {
  3287. const terminal = new FakeTerminal();
  3288. const runtime = createRuntime();
  3289. const app = createTuiApp({
  3290. runtime,
  3291. terminal,
  3292. version: "0.1.0",
  3293. workspaceDir: "/workspace",
  3294. });
  3295. const showOverlay = vi.spyOn(app.tui, "showOverlay");
  3296. app.start();
  3297. await app.ready;
  3298. const modelRequestsBeforeHelp = vi.mocked(runtime.listModels).mock.calls
  3299. .length;
  3300. const activeRunRequestsBeforeHelp = vi.mocked(runtime.getActiveRun).mock
  3301. .calls.length;
  3302. await app.submit("/help");
  3303. expect(runtime.sendMessage).not.toHaveBeenCalled();
  3304. expect(app.transcript.snapshot()).toEqual([]);
  3305. expect(app.tui.hasOverlay()).toBe(false);
  3306. expect(app.interaction.isActive()).toBe(true);
  3307. expect(terminal.mouseTracking).toBe(false);
  3308. terminal.input?.("m");
  3309. terminal.input?.("\r");
  3310. expect(app.tui.hasOverlay()).toBe(false);
  3311. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  3312. expect(app.editor.getText()).toBe("");
  3313. expect(runtime.listModels).toHaveBeenCalledTimes(modelRequestsBeforeHelp);
  3314. expect(runtime.getActiveRun).toHaveBeenCalledTimes(
  3315. activeRunRequestsBeforeHelp,
  3316. );
  3317. expect(showOverlay).not.toHaveBeenCalled();
  3318. await app.stop();
  3319. });
  3320. it("lets Help use the available terminal height instead of capping it at twelve rows", async () => {
  3321. const terminal = new FakeTerminal();
  3322. terminal.rows = 30;
  3323. const app = createTuiApp({
  3324. runtime: createRuntime(),
  3325. terminal,
  3326. version: "0.1.0",
  3327. workspaceDir: "/workspace",
  3328. });
  3329. app.start();
  3330. await app.submit("/help");
  3331. expect(app.interaction.current()?.render?.(terminal.columns)).toHaveLength(
  3332. 24,
  3333. );
  3334. terminal.rows = 18;
  3335. expect(app.interaction.current()?.render?.(terminal.columns)).toHaveLength(
  3336. 12,
  3337. );
  3338. await app.stop();
  3339. });
  3340. it("keeps steer executable and exposes it in slash-command discovery", async () => {
  3341. const terminal = new FakeTerminal();
  3342. const runtime = createRuntime();
  3343. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
  3344. schemaVersion: 1,
  3345. sessionId,
  3346. state: "running",
  3347. turnId: "turn-active",
  3348. actions: { steer: true },
  3349. }));
  3350. vi.mocked(runtime.steer).mockResolvedValue({
  3351. turnId: "turn-active",
  3352. mode: "steered",
  3353. });
  3354. const app = createTuiApp({
  3355. runtime,
  3356. terminal,
  3357. version: "0.1.0",
  3358. workspaceDir: "/workspace",
  3359. });
  3360. app.start();
  3361. await app.submit("Create session");
  3362. await app.submit("/help");
  3363. const helpPanel = app.interaction.current();
  3364. expect(helpPanel).toBeDefined();
  3365. expect(app.tui.hasOverlay()).toBe(false);
  3366. const helpPages: string[] = [];
  3367. for (let page = 0; page < 20; page += 1) {
  3368. const current = helpPanel?.render?.(100).join("\n") ?? "";
  3369. if (current === helpPages.at(-1)) break;
  3370. helpPages.push(current);
  3371. helpPanel?.handleInput?.("\x1b[6~");
  3372. }
  3373. const help = helpPages.join("\n");
  3374. expect(help).toContain("/steer <message>");
  3375. expect(help).not.toContain("/send-now");
  3376. expect(help).not.toContain("/retry");
  3377. helpPanel?.handleInput?.("\x1b");
  3378. await app.submit("/steer focus on the failing test");
  3379. expect(runtime.steer).toHaveBeenCalledWith(
  3380. expect.objectContaining({
  3381. sessionId: "session-1",
  3382. source: "api",
  3383. message: { content: "focus on the failing test" },
  3384. producerId: "mcode",
  3385. idempotencyKey: expect.stringMatching(/^run_action_/u),
  3386. }),
  3387. );
  3388. await app.stop();
  3389. });
  3390. it("refreshes Runtime steer capability before Enter submits the active Draft", async () => {
  3391. const terminal = new FakeTerminal();
  3392. const runtime = createRuntime();
  3393. let finishTurn: (() => void) | undefined;
  3394. let consumeSteer: (() => void) | undefined;
  3395. const steerConsumptionReady = new Promise<void>((resolve) => {
  3396. consumeSteer = resolve;
  3397. });
  3398. let steerAvailable = false;
  3399. vi.mocked(runtime.sendMessage).mockImplementation(
  3400. async function* sendMessage() {
  3401. yield {
  3402. type: "delta",
  3403. turnId: "turn-active",
  3404. content: "Working on it",
  3405. };
  3406. await steerConsumptionReady;
  3407. yield {
  3408. type: "message",
  3409. message: {
  3410. id: "message-steer",
  3411. turnId: "turn-active",
  3412. role: "user",
  3413. content: "focus on the failing test",
  3414. },
  3415. };
  3416. await new Promise<void>((resolve) => {
  3417. finishTurn = resolve;
  3418. });
  3419. yield { type: "done", turnId: "turn-active" };
  3420. },
  3421. );
  3422. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) =>
  3423. steerAvailable
  3424. ? {
  3425. schemaVersion: 1,
  3426. sessionId,
  3427. state: "running",
  3428. turnId: "turn-active",
  3429. actions: { steer: true },
  3430. }
  3431. : {
  3432. schemaVersion: 1,
  3433. sessionId,
  3434. state: "idle",
  3435. actions: { steer: false },
  3436. },
  3437. );
  3438. vi.mocked(runtime.steer).mockResolvedValue({
  3439. turnId: "turn-active",
  3440. mode: "steered",
  3441. });
  3442. const app = createTuiApp({
  3443. runtime,
  3444. terminal,
  3445. version: "0.1.0",
  3446. workspaceDir: "/workspace",
  3447. });
  3448. app.start();
  3449. await app.ready;
  3450. const submission = app.submit("Inspect the failure");
  3451. try {
  3452. await vi.waitFor(() =>
  3453. expect(app.tui.render(80).join("\n")).toContain("Running"),
  3454. );
  3455. steerAvailable = true;
  3456. terminal.input?.("focus on the failing test");
  3457. terminal.input?.("\r");
  3458. expect(app.editor.getText()).toBe("");
  3459. await vi.waitFor(() =>
  3460. expect(runtime.steer).toHaveBeenCalledWith(
  3461. expect.objectContaining({
  3462. sessionId: "session-1",
  3463. source: "api",
  3464. message: { content: "focus on the failing test" },
  3465. producerId: "mcode",
  3466. idempotencyKey: expect.stringMatching(/^run_action_/u),
  3467. requestedTurnId: "turn-active",
  3468. }),
  3469. ),
  3470. );
  3471. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  3472. kind: "user",
  3473. status: "pending",
  3474. content: "focus on the failing test",
  3475. userPresentation: "pending-steer",
  3476. });
  3477. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  3478. "↳ Next · focus on the failing test",
  3479. );
  3480. consumeSteer?.();
  3481. await vi.waitFor(() =>
  3482. expect(
  3483. app.transcript.snapshot().filter((cell) => cell.kind === "user"),
  3484. ).toEqual([
  3485. expect.objectContaining({ content: "Inspect the failure" }),
  3486. expect.objectContaining({
  3487. status: "succeeded",
  3488. content: "focus on the failing test",
  3489. sourceMessageId: "message-steer",
  3490. userPresentation: undefined,
  3491. }),
  3492. ]),
  3493. );
  3494. const rendered = app.tui.render(80).join("\n");
  3495. expect(rendered).toContain("Inspect the failure");
  3496. expect(rendered).toContain("focus on the failing test");
  3497. expect(stripAnsi(rendered)).not.toContain("↳ Next ·");
  3498. expect(app.editor.getText()).toBe("");
  3499. } finally {
  3500. consumeSteer?.();
  3501. await vi.waitFor(() => expect(finishTurn).toEqual(expect.any(Function)));
  3502. finishTurn?.();
  3503. await submission;
  3504. await app.stop();
  3505. }
  3506. });
  3507. it("queues with Alt+Enter, restores with Option+Up, then steers with Enter", async () => {
  3508. const terminal = new FakeTerminal();
  3509. const runtime = createRuntime();
  3510. const queuedItems: TuiQueuedMessage[] = [];
  3511. let finishTurn: (() => void) | undefined;
  3512. vi.mocked(runtime.sendMessage).mockImplementation(
  3513. async function* sendMessage() {
  3514. yield {
  3515. type: "delta",
  3516. turnId: "turn-active",
  3517. content: "Working on it",
  3518. };
  3519. await new Promise<void>((resolve) => {
  3520. finishTurn = resolve;
  3521. });
  3522. yield { type: "done", turnId: "turn-active" };
  3523. },
  3524. );
  3525. vi.mocked(runtime.enqueueMessage).mockImplementation(
  3526. async (sessionId, content) => {
  3527. const item: TuiQueuedMessage = {
  3528. itemId: "queue-guidance",
  3529. sessionId,
  3530. status: "queued",
  3531. source: "api",
  3532. content,
  3533. };
  3534. queuedItems.push(item);
  3535. return {
  3536. itemId: item.itemId,
  3537. status: item.status,
  3538. position: queuedItems.length,
  3539. };
  3540. },
  3541. );
  3542. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  3543. ...queuedItems,
  3544. ]);
  3545. vi.mocked(runtime.deleteQueuedMessage).mockImplementation(
  3546. async (_sessionId, itemId) => {
  3547. const index = queuedItems.findIndex((item) => item.itemId === itemId);
  3548. return index >= 0 ? queuedItems.splice(index, 1)[0] : undefined;
  3549. },
  3550. );
  3551. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
  3552. schemaVersion: 1,
  3553. sessionId,
  3554. state: "running",
  3555. turnId: "turn-active",
  3556. actions: { steer: true },
  3557. }));
  3558. const app = createTuiApp({
  3559. runtime,
  3560. terminal,
  3561. version: "0.1.0",
  3562. workspaceDir: "/workspace",
  3563. });
  3564. app.start();
  3565. await app.ready;
  3566. const submission = app.submit("Inspect the failure");
  3567. try {
  3568. await vi.waitFor(() =>
  3569. expect(app.tui.render(80).join("\n")).toContain("Running"),
  3570. );
  3571. terminal.input?.("Use the preview branch directly");
  3572. terminal.input?.("\x1b\r");
  3573. await vi.waitFor(() =>
  3574. expect(app.tui.render(80).join("\n")).toContain(
  3575. "Use the preview branch directly",
  3576. ),
  3577. );
  3578. await vi.waitFor(() =>
  3579. expect(runtime.listQueuedMessages).toHaveBeenCalledWith("session-1"),
  3580. );
  3581. expect(app.editor.getText()).toBe("");
  3582. terminal.input?.("\x1b[1;3A");
  3583. await vi.waitFor(() =>
  3584. expect(app.editor.getText()).toBe("Use the preview branch directly"),
  3585. );
  3586. expect(runtime.deleteQueuedMessage).toHaveBeenCalledWith(
  3587. "session-1",
  3588. "queue-guidance",
  3589. );
  3590. expect(runtime.steerQueuedMessage).not.toHaveBeenCalled();
  3591. await vi.waitFor(() =>
  3592. expect(app.tui.render(80).join("\n")).not.toContain("Queued ·"),
  3593. );
  3594. terminal.input?.("\r");
  3595. await vi.waitFor(() =>
  3596. expect(runtime.steer).toHaveBeenCalledWith(
  3597. expect.objectContaining({
  3598. sessionId: "session-1",
  3599. message: { content: "Use the preview branch directly" },
  3600. requestedTurnId: "turn-active",
  3601. }),
  3602. ),
  3603. );
  3604. expect(app.editor.getText()).toBe("");
  3605. } finally {
  3606. finishTurn?.();
  3607. await submission;
  3608. await app.stop();
  3609. }
  3610. });
  3611. it("renders /context from the Runtime-owned persisted context usage", async () => {
  3612. const runtime = createRuntime();
  3613. vi.mocked(runtime.getContextSnapshot).mockResolvedValue({
  3614. status: "live",
  3615. model: { provider: "minimax", id: "MiniMax-M3", contextWindow: 10_000 },
  3616. contextUsage: {
  3617. contextWindowTokens: 10_000,
  3618. usedTokens: 3_000,
  3619. totalCountSource: "PROVIDER_USAGE_ANCHORED",
  3620. components: [
  3621. { kind: "SYSTEM_PROMPT", tokens: 1_000 },
  3622. { kind: "MEMORY", tokens: 0 },
  3623. { kind: "TOOLS", tokens: 0 },
  3624. { kind: "SKILLS", tokens: 0 },
  3625. { kind: "MESSAGES", tokens: 2_000 },
  3626. { kind: "OTHER", tokens: 0 },
  3627. ],
  3628. },
  3629. });
  3630. const app = createTuiApp({
  3631. runtime,
  3632. terminal: new FakeTerminal(),
  3633. version: "0.1.0",
  3634. workspaceDir: "/workspace",
  3635. });
  3636. await app.submit("Create session");
  3637. const transcriptBeforeContext = app.transcript.snapshot();
  3638. await app.submit("/context");
  3639. expect(app.transcript.snapshot()).toEqual(transcriptBeforeContext);
  3640. expect(app.interaction.current()).toBeDefined();
  3641. const rendered = app.tui.render(80).join("\n");
  3642. expect(rendered).toContain("Context");
  3643. expect(rendered).toContain("3k/10k tokens (30% used)");
  3644. expect(rendered).toContain("Usage by category");
  3645. expect(rendered).toContain("Messages");
  3646. expect(rendered).toMatch(/[⛁⛀⛶]/u);
  3647. app.interaction.current()?.handleInput?.("\x1b");
  3648. expect(app.interaction.current()).toBeUndefined();
  3649. expect(app.transcript.snapshot()).toEqual(transcriptBeforeContext);
  3650. });
  3651. it("routes /init through the Runtime-owned init Skill and the normal Agent turn", async () => {
  3652. const terminal = new FakeTerminal();
  3653. const runtime = createRuntime();
  3654. vi.mocked(runtime.listSkills).mockResolvedValue({
  3655. skills: [
  3656. {
  3657. name: "init",
  3658. displayName: "Init",
  3659. description: "Analyze the codebase and generate AGENTS.md",
  3660. enabled: true,
  3661. sourceKind: "builtin",
  3662. },
  3663. ],
  3664. hasMore: false,
  3665. });
  3666. const app = createTuiApp({
  3667. runtime,
  3668. terminal,
  3669. version: "0.1.0",
  3670. workspaceDir: "/workspace",
  3671. });
  3672. app.start();
  3673. await app.ready;
  3674. await vi.waitFor(() => expect(runtime.listSkills).toHaveBeenCalled());
  3675. await app.submit("/init");
  3676. expect(runtime.sendMessage).toHaveBeenCalledWith(
  3677. expect.objectContaining({ id: "session-1", content: "/init" }),
  3678. expect.any(AbortSignal),
  3679. );
  3680. });
  3681. it("forwards literal slash-prefixed prompts without invoking local commands", async () => {
  3682. const runtime = createRuntime();
  3683. const app = createTuiApp({
  3684. runtime,
  3685. terminal: new FakeTerminal(),
  3686. version: "0.1.0",
  3687. workspaceDir: "/workspace",
  3688. });
  3689. const prompts = [
  3690. "/commands",
  3691. "/diff",
  3692. "/tool",
  3693. "/tools",
  3694. "/resumex",
  3695. "/renamex Renamed by a typo",
  3696. "/clearx",
  3697. "/tmp/sample-photo.JPG 用 read 工具直接读这个图片,告诉我是什么",
  3698. "/not-a-command explain what this text means",
  3699. "/context 这样还是会显示上下文信息",
  3700. ];
  3701. try {
  3702. app.start();
  3703. await app.ready;
  3704. for (const prompt of prompts) {
  3705. await app.submit(prompt);
  3706. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  3707. expect.objectContaining({ id: "session-1", content: prompt }),
  3708. expect.any(AbortSignal),
  3709. );
  3710. expect(app.interaction.current()).toBeUndefined();
  3711. expect(app.tui.hasOverlay()).toBe(false);
  3712. }
  3713. expect(runtime.sendMessage).toHaveBeenCalledTimes(prompts.length);
  3714. expect(runtime.renameSession).not.toHaveBeenCalled();
  3715. // Context metrics refresh independently; the overlay assertions above verify no local command ran.
  3716. expect(app.transcript.snapshot()).not.toContainEqual(
  3717. expect.objectContaining({ content: "Unknown command. Use /help." }),
  3718. );
  3719. } finally {
  3720. await app.stop();
  3721. }
  3722. });
  3723. it("keeps contextual commands local and submits other legacy names as prompts", async () => {
  3724. const terminal = new FakeTerminal();
  3725. const runtime = createRuntime();
  3726. const app = createTuiApp({
  3727. runtime,
  3728. terminal,
  3729. version: "0.1.0",
  3730. workspaceDir: "/workspace",
  3731. });
  3732. await app.submit("/queue");
  3733. expect(runtime.listQueuedMessages).not.toHaveBeenCalled();
  3734. expect(app.transcript.snapshot()).toEqual([]);
  3735. expect(app.tui.render(80).join("\n")).toContain(
  3736. "No messages are waiting and no response is currently running.",
  3737. );
  3738. await app.submit("/queue-clear");
  3739. expect(runtime.deleteQueuedMessage).not.toHaveBeenCalled();
  3740. await app.submit("/send-now do this first");
  3741. await app.submit("/retry");
  3742. expect(
  3743. vi
  3744. .mocked(runtime.sendMessage)
  3745. .mock.calls.map(([request]) => request.content),
  3746. ).toEqual(["/queue-clear", "/send-now do this first"]);
  3747. expect(app.tui.render(80).join("\n")).toContain(
  3748. "There is no failed response to retry in this Session.",
  3749. );
  3750. });
  3751. it("resends the failed user submission through /retry instead of sending the command as text", async () => {
  3752. const terminal = new FakeTerminal();
  3753. const runtime = createRuntime();
  3754. let attempt = 0;
  3755. vi.mocked(runtime.sendMessage).mockImplementation(
  3756. async function* sendMessage() {
  3757. attempt += 1;
  3758. if (attempt === 1) {
  3759. yield { type: "error", message: "terminated" };
  3760. return;
  3761. }
  3762. yield { type: "delta", content: "Recovered response" };
  3763. yield { type: "done" };
  3764. },
  3765. );
  3766. const app = createTuiApp({
  3767. runtime,
  3768. terminal,
  3769. version: "0.1.0",
  3770. workspaceDir: "/workspace",
  3771. });
  3772. await app.submit("Explain this failure");
  3773. expect(app.tui.render(100).join("\n")).toContain(
  3774. "The model connection ended before the response was completed.",
  3775. );
  3776. expect(app.tui.render(100).join("\n")).toContain(
  3777. "Run /retry to resend your last message.",
  3778. );
  3779. await app.submit("/retry");
  3780. expect(
  3781. vi
  3782. .mocked(runtime.sendMessage)
  3783. .mock.calls.map(([request]) => request.content),
  3784. ).toEqual(["Explain this failure", "Explain this failure"]);
  3785. expect(
  3786. vi
  3787. .mocked(runtime.sendMessage)
  3788. .mock.calls.some(([request]) => request.content === "/retry"),
  3789. ).toBe(false);
  3790. expect(app.transcript.snapshot()).toContainEqual(
  3791. expect.objectContaining({
  3792. kind: "assistant",
  3793. content: "Recovered response",
  3794. }),
  3795. );
  3796. await app.stop();
  3797. });
  3798. it("uses Runtime retry-continuation when a terminal failure has no local submission snapshot", async () => {
  3799. const terminal = new FakeTerminal();
  3800. const runtime = createRuntime();
  3801. const restoredSession = {
  3802. sessionId: "session-1",
  3803. title: "Restored session",
  3804. workspaceDir: "/workspace",
  3805. status: "error",
  3806. errorMessage: "terminated",
  3807. };
  3808. vi.mocked(runtime.listSessions).mockResolvedValue([restoredSession]);
  3809. vi.mocked(runtime.getSession).mockResolvedValue(restoredSession);
  3810. const app = createTuiApp({
  3811. runtime,
  3812. terminal,
  3813. version: "0.1.0",
  3814. workspaceDir: "/workspace",
  3815. });
  3816. app.start();
  3817. await app.ready;
  3818. await app.submit("/resume session-1");
  3819. expect(app.tui.render(100).join("\n")).toContain(
  3820. "The model connection ended before the response was completed.",
  3821. );
  3822. await app.submit("/retry");
  3823. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  3824. expect.objectContaining({
  3825. id: "session-1",
  3826. content: "",
  3827. clientIntent: "retry-continuation",
  3828. }),
  3829. expect.any(AbortSignal),
  3830. );
  3831. await app.stop();
  3832. });
  3833. it("reports service authentication failures without assuming the user needs to sign in", async () => {
  3834. const runtime = createRuntime();
  3835. vi.mocked(runtime.sendMessage).mockImplementation(
  3836. async function* sendMessage() {
  3837. yield { type: "error", message: "authentication failed" };
  3838. },
  3839. );
  3840. const app = createTuiApp({
  3841. runtime,
  3842. terminal: new FakeTerminal(),
  3843. version: "0.1.0",
  3844. workspaceDir: "/workspace",
  3845. });
  3846. await app.submit("Use the protected model");
  3847. expect(app.tui.render(100).join("\n")).toContain(
  3848. "The service rejected request authentication.",
  3849. );
  3850. expect(app.tui.render(100).join("\n")).not.toContain("Run /login");
  3851. expect(app.tui.render(100).join("\n")).not.toContain("Run /retry");
  3852. await app.submit("/retry");
  3853. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  3854. await app.stop();
  3855. });
  3856. it("cycles the shared permission mode with Alt+M without repeating the shortcut", async () => {
  3857. const terminal = new FakeTerminal();
  3858. const runtime = createRuntime();
  3859. const app = createTuiApp({
  3860. runtime,
  3861. terminal,
  3862. version: "0.1.0",
  3863. workspaceDir: "/workspace",
  3864. });
  3865. app.start();
  3866. await app.ready;
  3867. expect(app.tui.render(80).join("\n")).toContain("Auto");
  3868. expect(app.tui.render(80).join("\n")).not.toContain("Shift+Tab");
  3869. expect(app.tui.render(80).join("\n")).not.toContain(
  3870. "Shift+Tab switch mode",
  3871. );
  3872. terminal.input?.("\x1bm");
  3873. await vi.waitFor(() => {
  3874. expect(runtime.setPermissionMode).toHaveBeenCalledWith(
  3875. "bypassPermissions",
  3876. );
  3877. const rendered = app.tui.render(80).join("\n");
  3878. expect(rendered).toContain("Full access");
  3879. expect(rendered).not.toContain("Shift+Tab");
  3880. expect(rendered.match(/Full access/g)).toHaveLength(1);
  3881. expect(rendered).not.toContain("Desktop permissions:");
  3882. });
  3883. await app.stop();
  3884. });
  3885. it("projects Token Plan warnings into the status rail", async () => {
  3886. const terminal = new FakeTerminal();
  3887. const runtime = createRuntime();
  3888. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  3889. status: "ready",
  3890. defaultModel: "minimax/MiniMax-M2.7",
  3891. providerId: "minimax",
  3892. modelId: "MiniMax-M2.7",
  3893. authMode: "managed-login",
  3894. managedTokenPresent: true,
  3895. modelSource: "token-plan",
  3896. tokenPlanQuotaState: "available",
  3897. tokenPlanQuota: {
  3898. fiveHour: { remainingPercent: 30, unlimited: false },
  3899. weekly: { remainingPercent: 64, unlimited: false },
  3900. },
  3901. warnings: [],
  3902. });
  3903. const app = createTuiApp({
  3904. runtime,
  3905. terminal,
  3906. version: "0.1.0",
  3907. workspaceDir: "/workspace",
  3908. });
  3909. app.start();
  3910. await app.ready;
  3911. await app.submit("Measure this turn");
  3912. await vi.waitFor(() => {
  3913. const rendered = app.tui.render(120).join("\n");
  3914. expect(rendered).toContain("5h 30%");
  3915. expect(rendered).not.toContain("Week 64%");
  3916. });
  3917. await app.stop();
  3918. });
  3919. it("keeps Token Plan subscription state out of the status rail when no quota exists", async () => {
  3920. const terminal = new FakeTerminal();
  3921. const runtime = createRuntime();
  3922. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  3923. status: "ready",
  3924. defaultModel: "minimax/MiniMax-M3",
  3925. providerId: "minimax",
  3926. modelId: "MiniMax-M3",
  3927. authMode: "managed-login",
  3928. managedTokenPresent: true,
  3929. modelSource: "token-plan",
  3930. tokenPlanQuotaState: "not-subscribed",
  3931. warnings: [],
  3932. });
  3933. const app = createTuiApp({
  3934. runtime,
  3935. terminal,
  3936. version: "0.1.0",
  3937. workspaceDir: "/workspace",
  3938. });
  3939. app.start();
  3940. await app.ready;
  3941. await app.submit("Measure this turn");
  3942. await vi.waitFor(() => {
  3943. const rendered = app.tui.render(120).join("\n");
  3944. expect(rendered).toContain("✦ MiniMax M2.7");
  3945. expect(rendered).not.toMatch(/Context 5%|Quota|Plan|5h|Week/u);
  3946. });
  3947. await app.stop();
  3948. });
  3949. it("keeps the current permission mode when an Alt+M update fails", async () => {
  3950. const terminal = new FakeTerminal();
  3951. const runtime = createRuntime();
  3952. vi.mocked(runtime.setPermissionMode).mockRejectedValueOnce(
  3953. new Error("config is read-only"),
  3954. );
  3955. const app = createTuiApp({
  3956. runtime,
  3957. terminal,
  3958. version: "0.1.0",
  3959. workspaceDir: "/workspace",
  3960. });
  3961. app.start();
  3962. await app.ready;
  3963. terminal.input?.("\x1bm");
  3964. await vi.waitFor(() => {
  3965. expect(app.tui.render(80).join("\n")).toContain("Auto");
  3966. expect(app.tui.render(80).join("\n")).not.toContain("FULL");
  3967. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  3968. kind: "warning",
  3969. content:
  3970. "Permission mode was not changed: config is read-only. Retry /permission or Alt+M.",
  3971. });
  3972. });
  3973. await app.stop();
  3974. });
  3975. it("arms Plan with Shift+Tab and sends the one-shot Runtime intent", async () => {
  3976. const terminal = new FakeTerminal();
  3977. const runtime = createRuntime();
  3978. const app = createTuiApp({
  3979. runtime,
  3980. terminal,
  3981. version: "0.1.0",
  3982. workspaceDir: "/workspace",
  3983. });
  3984. app.start();
  3985. await app.ready;
  3986. terminal.input?.("\x1b[Z");
  3987. expect(app.tui.render(100).join("\n")).toContain("PLAN next");
  3988. expect(app.tui.render(100).join("\n")).toContain(
  3989. "Plan Mode · next message enters Plan",
  3990. );
  3991. terminal.input?.("计");
  3992. expect(app.tui.render(100).join("\n")).toContain(
  3993. "Plan Mode · next message enters Plan",
  3994. );
  3995. expect(app.tui.render(32).join("\n")).toContain("Plan Mode");
  3996. terminal.input?.("\x7f");
  3997. expect(app.editor.getText()).toBe("");
  3998. expect(app.tui.render(100).join("\n")).toContain(
  3999. "Plan Mode · next message enters Plan",
  4000. );
  4001. terminal.input?.("计");
  4002. terminal.input?.("划");
  4003. expect(app.editor.getText()).toBe("计划");
  4004. expect(app.tui.render(100).join("\n")).toContain("PLAN next");
  4005. expect(app.tui.render(100).join("\n")).toContain(
  4006. "Plan Mode · next message enters Plan",
  4007. );
  4008. terminal.input?.("\r");
  4009. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
  4010. await app.controller.whenIdle();
  4011. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4012. expect.objectContaining({
  4013. content: "计划",
  4014. clientIntent: "plan-entry",
  4015. }),
  4016. expect.any(AbortSignal),
  4017. );
  4018. expect(app.tui.render(100).join("\n")).toContain("PLAN");
  4019. expect(app.tui.render(100).join("\n")).toContain("Auto");
  4020. await app.stop();
  4021. });
  4022. it("keeps ordinary messages in Plan and exits only with an explicit one-shot intent", async () => {
  4023. const runtime = createRuntime();
  4024. const app = createTuiApp({
  4025. runtime,
  4026. terminal: new FakeTerminal(),
  4027. version: "0.1.0",
  4028. workspaceDir: "/workspace",
  4029. });
  4030. app.start();
  4031. await app.ready;
  4032. await app.submit("/plan on");
  4033. await app.submit("Draft the implementation plan");
  4034. await app.submit("Refine the verification section");
  4035. expect(runtime.sendMessage).toHaveBeenNthCalledWith(
  4036. 2,
  4037. expect.not.objectContaining({ clientIntent: expect.anything() }),
  4038. expect.any(AbortSignal),
  4039. );
  4040. expect(app.tui.render(100).join("\n")).toContain(
  4041. "/workspace │ PLAN │ Auto",
  4042. );
  4043. await app.submit("/plan off");
  4044. await app.submit("Implement the approved direction");
  4045. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  4046. expect.objectContaining({ clientIntent: "plan-exit" }),
  4047. expect.any(AbortSignal),
  4048. );
  4049. expect(app.tui.render(100).join("\n")).not.toContain("PLAN");
  4050. await app.stop();
  4051. });
  4052. it("keeps the one-shot Plan intent armed when direct admission rejects it", async () => {
  4053. const runtime = createRuntime();
  4054. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  4055. async function* rejectedAdmission() {
  4056. yield* [] as TuiStreamEvent[];
  4057. throw Object.assign(new Error("Plan entry is disabled"), {
  4058. code: "local_plan_entry_disabled",
  4059. });
  4060. },
  4061. );
  4062. const app = createTuiApp({
  4063. runtime,
  4064. terminal: new FakeTerminal(),
  4065. version: "0.1.0",
  4066. workspaceDir: "/workspace",
  4067. });
  4068. app.start();
  4069. await app.ready;
  4070. await app.submit("/plan on");
  4071. await app.submit("Plan this after the feature is enabled");
  4072. expect(app.tui.render(100).join("\n")).toContain("PLAN next");
  4073. await app.submit("Retry the same Plan intent");
  4074. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  4075. expect.objectContaining({ clientIntent: "plan-entry" }),
  4076. expect.any(AbortSignal),
  4077. );
  4078. await app.stop();
  4079. });
  4080. it("settles a Plan transition from authoritative Session metadata when the stream is empty", async () => {
  4081. const runtime = createRuntime();
  4082. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  4083. async function* emptyAcceptedStream() {
  4084. yield* [] as TuiStreamEvent[];
  4085. },
  4086. );
  4087. vi.mocked(runtime.getSession).mockResolvedValue({
  4088. sessionId: "session-1",
  4089. workspace: "/workspace",
  4090. interactionMode: "plan",
  4091. });
  4092. const app = createTuiApp({
  4093. runtime,
  4094. terminal: new FakeTerminal(),
  4095. version: "0.1.0",
  4096. workspaceDir: "/workspace",
  4097. });
  4098. app.start();
  4099. await app.ready;
  4100. await app.submit("/plan on");
  4101. await app.submit("Plan without emitting a stream event");
  4102. expect(runtime.getSession).toHaveBeenCalledWith("session-1");
  4103. expect(app.tui.render(100).join("\n")).toContain(
  4104. "/workspace │ PLAN │ Auto",
  4105. );
  4106. expect(app.tui.render(100).join("\n")).not.toContain("PLAN next");
  4107. await app.stop();
  4108. });
  4109. it("clears accepted Plan entry while authoritative metadata refresh is unavailable", async () => {
  4110. const runtime = createRuntime();
  4111. vi.mocked(runtime.getSession).mockRejectedValue(
  4112. new Error("metadata temporarily unavailable"),
  4113. );
  4114. const app = createTuiApp({
  4115. runtime,
  4116. terminal: new FakeTerminal(),
  4117. version: "0.1.0",
  4118. workspaceDir: "/workspace",
  4119. });
  4120. app.start();
  4121. await app.ready;
  4122. await app.submit("/plan on");
  4123. await app.submit("OK");
  4124. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4125. expect.objectContaining({ content: "OK", clientIntent: "plan-entry" }),
  4126. expect.any(AbortSignal),
  4127. );
  4128. expect(app.tui.render(100).join("\n")).not.toContain("/workspace │ PLAN");
  4129. expect(app.tui.render(100).join("\n")).not.toContain("DEFAULT next");
  4130. await app.stop();
  4131. });
  4132. it("preserves Plan intent through direct busy fallback into the Runtime Queue", async () => {
  4133. const runtime = createRuntime();
  4134. vi.mocked(runtime.listModels).mockResolvedValue([
  4135. {
  4136. providerId: "minimax",
  4137. modelId: "MiniMax-M2.7",
  4138. selected: true,
  4139. variant: "",
  4140. },
  4141. ]);
  4142. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  4143. async function* busyAdmission() {
  4144. yield* [] as TuiStreamEvent[];
  4145. throw Object.assign(new Error("Session is busy"), {
  4146. code: "local_session_busy",
  4147. });
  4148. },
  4149. );
  4150. const app = createTuiApp({
  4151. runtime,
  4152. terminal: new FakeTerminal(),
  4153. version: "0.1.0",
  4154. workspaceDir: "/workspace",
  4155. });
  4156. app.start();
  4157. await app.ready;
  4158. await app.submit("/plan on");
  4159. await app.submit("Queue this Plan request");
  4160. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  4161. "session-1",
  4162. "Queue this Plan request",
  4163. {
  4164. attachments: [],
  4165. clientIntent: "plan-entry",
  4166. model: { providerId: "minimax", modelId: "MiniMax-M2.7", variant: "" },
  4167. },
  4168. );
  4169. expect(app.tui.render(100).join("\n")).not.toContain("PLAN queued");
  4170. await app.stop();
  4171. });
  4172. it("binds a one-shot Plan intent to only the first concurrent submission", async () => {
  4173. let releaseFirstEvent: (() => void) | undefined;
  4174. const firstEventGate = new Promise<void>((resolve) => {
  4175. releaseFirstEvent = resolve;
  4176. });
  4177. const runtime = createRuntime();
  4178. vi.mocked(runtime.sendMessage).mockImplementation(
  4179. async function* delayedAdmission() {
  4180. await firstEventGate;
  4181. yield { type: "delta", content: "Planning" };
  4182. yield { type: "done" };
  4183. },
  4184. );
  4185. const app = createTuiApp({
  4186. runtime,
  4187. terminal: new FakeTerminal(),
  4188. version: "0.1.0",
  4189. workspaceDir: "/workspace",
  4190. });
  4191. app.start();
  4192. await app.ready;
  4193. await app.submit("/plan on");
  4194. const first = app.submit("Plan the implementation");
  4195. await vi.waitFor(() =>
  4196. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  4197. );
  4198. await app.submit("Queue a follow-up while admission is quiet");
  4199. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4200. expect.objectContaining({ clientIntent: "plan-entry" }),
  4201. expect.any(AbortSignal),
  4202. );
  4203. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  4204. "session-1",
  4205. "Queue a follow-up while admission is quiet",
  4206. {
  4207. attachments: [],
  4208. model: { providerId: "minimax", modelId: "MiniMax-M2.7" },
  4209. },
  4210. );
  4211. releaseFirstEvent?.();
  4212. await first;
  4213. await app.stop();
  4214. });
  4215. it("shows the Desktop-aligned confirmation when the Agent calls EnterPlanMode", async () => {
  4216. let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  4217. const runtime = createRuntime();
  4218. vi.mocked(runtime.watchEvents).mockImplementation(
  4219. async function* watchEvents(signal) {
  4220. const event = await new Promise<TuiRuntimeEvent | undefined>(
  4221. (resolve) => {
  4222. emitEvent = resolve;
  4223. signal.addEventListener("abort", () => resolve(undefined), {
  4224. once: true,
  4225. });
  4226. },
  4227. );
  4228. if (event) yield event;
  4229. await new Promise<void>((resolve) => {
  4230. signal.addEventListener("abort", resolve, { once: true });
  4231. });
  4232. },
  4233. );
  4234. const app = createTuiApp({
  4235. runtime,
  4236. terminal: new FakeTerminal(),
  4237. version: "0.1.0",
  4238. workspaceDir: "/workspace",
  4239. });
  4240. app.start();
  4241. await app.ready;
  4242. await app.submit("Plan a complex change");
  4243. await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
  4244. const askEvent = runtimeEvent({
  4245. type: "questionnaire.ask",
  4246. timestamp: Date.now(),
  4247. source: "runtime",
  4248. payload: {
  4249. sessionId: "session-1",
  4250. agentName: "mavis",
  4251. request: planEntryEventRequest("plan-entry-agent-tool"),
  4252. },
  4253. });
  4254. expect(askEvent).toMatchObject({
  4255. type: "questionnaire.ask",
  4256. sessionId: "session-1",
  4257. request: { id: "plan-entry-agent-tool", mode: "plan" },
  4258. });
  4259. emitEvent?.(askEvent);
  4260. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  4261. const panel = app.interaction.current();
  4262. const rendered = panel?.render?.(100).join("\n") ?? "";
  4263. expect(rendered).toContain("Use Plan mode?");
  4264. expect(rendered).toContain(
  4265. "Plan mode structures complex tasks before execution.",
  4266. );
  4267. expect(rendered).toContain("Continue with plan");
  4268. expect(rendered).toContain("Deny");
  4269. panel?.handleInput?.("\r");
  4270. await vi.waitFor(() =>
  4271. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  4272. "mavis",
  4273. "plan-entry-agent-tool",
  4274. [
  4275. {
  4276. stepId: "plan-enter",
  4277. selectedOptionIds: ["confirm"],
  4278. selectedOther: false,
  4279. },
  4280. ],
  4281. ),
  4282. );
  4283. await app.stop();
  4284. });
  4285. it("keeps a pending Plan exit armed when steer guides the current Plan Turn", async () => {
  4286. let finishTurn: (() => void) | undefined;
  4287. let interactionMode: "plan" | undefined;
  4288. const runtime = createRuntime();
  4289. vi.mocked(runtime.getSession).mockImplementation(async () => ({
  4290. sessionId: "session-1",
  4291. workspace: "/workspace",
  4292. ...(interactionMode ? { interactionMode } : {}),
  4293. }));
  4294. vi.mocked(runtime.sendMessage).mockImplementation(
  4295. async function* activePlanTurn() {
  4296. interactionMode = "plan";
  4297. yield { type: "delta", content: "Drafting the plan" };
  4298. await new Promise<void>((resolve) => {
  4299. finishTurn = resolve;
  4300. });
  4301. yield { type: "done" };
  4302. },
  4303. );
  4304. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
  4305. schemaVersion: 1,
  4306. sessionId,
  4307. state: "running",
  4308. turnId: "turn-plan",
  4309. actions: { steer: true },
  4310. }));
  4311. vi.mocked(runtime.steer).mockResolvedValue({
  4312. turnId: "turn-plan",
  4313. mode: "steered",
  4314. });
  4315. const app = createTuiApp({
  4316. runtime,
  4317. terminal: new FakeTerminal(),
  4318. version: "0.1.0",
  4319. workspaceDir: "/workspace",
  4320. });
  4321. app.start();
  4322. await app.ready;
  4323. await app.submit("/plan on");
  4324. const planTurn = app.submit("Draft a plan");
  4325. await vi.waitFor(() =>
  4326. expect(app.tui.render(100).join("\n")).toContain(
  4327. "/workspace │ PLAN │ Auto",
  4328. ),
  4329. );
  4330. await app.submit("/plan off");
  4331. await app.submit("/steer include rollback checks");
  4332. expect(runtime.steer).toHaveBeenCalledWith(
  4333. expect.objectContaining({
  4334. sessionId: "session-1",
  4335. message: { content: "include rollback checks" },
  4336. }),
  4337. );
  4338. expect(app.tui.render(100).join("\n")).toContain("DEFAULT next");
  4339. finishTurn?.();
  4340. await planTurn;
  4341. await app.stop();
  4342. });
  4343. it("does not arm a mode transition while a Plan Review is pending", async () => {
  4344. let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  4345. const runtime = createRuntime();
  4346. vi.mocked(runtime.watchEvents).mockImplementation(
  4347. async function* watchEvents(signal) {
  4348. const event = await new Promise<TuiRuntimeEvent | undefined>(
  4349. (resolve) => {
  4350. emitEvent = resolve;
  4351. signal.addEventListener("abort", () => resolve(undefined), {
  4352. once: true,
  4353. });
  4354. },
  4355. );
  4356. if (event) yield event;
  4357. await new Promise<void>((resolve) => {
  4358. signal.addEventListener("abort", resolve, { once: true });
  4359. });
  4360. },
  4361. );
  4362. const terminal = new FakeTerminal();
  4363. const app = createTuiApp({
  4364. runtime,
  4365. terminal,
  4366. version: "0.1.0",
  4367. workspaceDir: "/workspace",
  4368. });
  4369. app.start();
  4370. await app.ready;
  4371. await app.submit("/plan on");
  4372. await app.submit("Draft a plan");
  4373. await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
  4374. emitEvent?.(
  4375. runtimeEvent({
  4376. type: "questionnaire.ask",
  4377. timestamp: Date.now(),
  4378. source: "runtime",
  4379. payload: {
  4380. sessionId: "session-1",
  4381. agentName: "mavis",
  4382. request: planReviewEventRequest("plan-review-mode-guard"),
  4383. },
  4384. }),
  4385. );
  4386. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  4387. // The compact panel owns the decision; the frozen plan is projected to the Transcript.
  4388. expect(app.interaction.current()?.render?.(100).join("\n")).toContain(
  4389. "Plan complete. What would you like to do?",
  4390. );
  4391. expect(app.tui.render(100).join("\n")).toContain("Frozen plan");
  4392. terminal.input?.("\x1b[Z");
  4393. expect(app.interaction.isActive()).toBe(true);
  4394. expect(app.tui.render(100).join("\n")).toContain(
  4395. "/workspace │ PLAN │ Auto",
  4396. );
  4397. expect(app.tui.render(100).join("\n")).not.toContain("DEFAULT next");
  4398. await app.submit("/plan off");
  4399. expect(app.interaction.isActive()).toBe(true);
  4400. expect(app.tui.render(100).join("\n")).toContain(
  4401. "/workspace │ PLAN │ Auto",
  4402. );
  4403. expect(app.tui.render(100).join("\n")).not.toContain("DEFAULT next");
  4404. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  4405. await app.submit("/steer bypass the review");
  4406. expect(app.interaction.isActive()).toBe(true);
  4407. expect(runtime.steer).not.toHaveBeenCalled();
  4408. app.interaction.current()?.handleInput?.("\u001b");
  4409. await vi.waitFor(() =>
  4410. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  4411. "mavis",
  4412. "plan-review-mode-guard",
  4413. [expect.objectContaining({ skipped: true })],
  4414. ),
  4415. );
  4416. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  4417. expect(app.tui.render(100).join("\n")).toContain(
  4418. "/workspace │ PLAN │ Auto",
  4419. );
  4420. await app.stop();
  4421. });
  4422. it("streams Plan feedback and replaces it with the revised Plan Review", async () => {
  4423. let emitReview: ((event: TuiRuntimeEvent) => void) | undefined;
  4424. let releaseContinuation: (() => void) | undefined;
  4425. let finishReply: ((value: boolean) => void) | undefined;
  4426. const runtime = createRuntime();
  4427. vi.mocked(runtime.replyQuestionnaire).mockImplementation(
  4428. async () =>
  4429. await new Promise<boolean>((resolve) => {
  4430. finishReply = resolve;
  4431. }),
  4432. );
  4433. vi.mocked(runtime.watchEvents).mockImplementation(
  4434. async function* watchEvents(signal) {
  4435. const review = await new Promise<TuiRuntimeEvent | undefined>(
  4436. (resolve) => {
  4437. emitReview = resolve;
  4438. signal.addEventListener("abort", () => resolve(undefined), {
  4439. once: true,
  4440. });
  4441. },
  4442. );
  4443. if (!review || signal.aborted) return;
  4444. yield review;
  4445. await new Promise<void>((resolve) => {
  4446. releaseContinuation = resolve;
  4447. signal.addEventListener("abort", resolve, { once: true });
  4448. });
  4449. if (signal.aborted) return;
  4450. const turnId = "turn-runtime-plan-feedback";
  4451. yield runtimeEvent({
  4452. type: "session.start",
  4453. timestamp: Date.now(),
  4454. source: "runtime",
  4455. payload: { sessionId: "session-1", turnId },
  4456. });
  4457. vi.mocked(runtime.getMessages).mockResolvedValue([
  4458. {
  4459. id: "assistant-revised-plan",
  4460. role: "assistant",
  4461. content: "I revised the plan with rollback coverage.",
  4462. },
  4463. ]);
  4464. yield runtimeEvent({
  4465. type: "questionnaire.ask",
  4466. timestamp: Date.now(),
  4467. source: "runtime",
  4468. payload: {
  4469. sessionId: "session-1",
  4470. agentName: "mavis",
  4471. request: {
  4472. ...planReviewEventRequest("plan-review-feedback-revised"),
  4473. modePayload: {
  4474. planReview: {
  4475. markdown:
  4476. "# Revised frozen plan\n\nIncludes rollback coverage.",
  4477. path: "/history/session-1/artifacts/plan.md",
  4478. },
  4479. },
  4480. },
  4481. },
  4482. });
  4483. yield runtimeEvent({
  4484. type: "session.finish",
  4485. timestamp: Date.now(),
  4486. source: "runtime",
  4487. payload: { sessionId: "session-1", turnId },
  4488. });
  4489. finishReply?.(true);
  4490. await new Promise<void>((resolve) => {
  4491. signal.addEventListener("abort", resolve, { once: true });
  4492. });
  4493. },
  4494. );
  4495. const terminal = new FakeTerminal();
  4496. const app = createTuiApp({
  4497. runtime,
  4498. terminal,
  4499. version: "0.1.0",
  4500. workspaceDir: "/workspace",
  4501. });
  4502. app.start();
  4503. await app.ready;
  4504. await app.submit("/plan on");
  4505. await app.submit("Draft a plan");
  4506. await vi.waitFor(() => expect(emitReview).toBeTypeOf("function"));
  4507. emitReview?.(
  4508. runtimeEvent({
  4509. type: "questionnaire.ask",
  4510. timestamp: Date.now(),
  4511. source: "runtime",
  4512. payload: {
  4513. sessionId: "session-1",
  4514. agentName: "mavis",
  4515. request: planReviewEventRequest("plan-review-feedback-live"),
  4516. },
  4517. }),
  4518. );
  4519. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  4520. terminal.input?.("\u001b[B");
  4521. terminal.input?.("\u001b[B");
  4522. terminal.input?.("\r");
  4523. for (const character of "Add rollback coverage")
  4524. terminal.input?.(character);
  4525. terminal.input?.("\r");
  4526. await vi.waitFor(() => expect(finishReply).toBeTypeOf("function"));
  4527. releaseContinuation?.();
  4528. await vi.waitFor(() =>
  4529. expect(
  4530. app.transcript
  4531. .snapshot()
  4532. .map((cell) => cell.content)
  4533. .join("\n"),
  4534. ).toContain("I revised the plan with rollback coverage."),
  4535. );
  4536. expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
  4537. "session-1",
  4538. "turn-runtime-plan-feedback",
  4539. expect.any(AbortSignal),
  4540. );
  4541. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  4542. // The revised plan is projected to the Transcript; the panel stays the compact decision.
  4543. expect(app.interaction.current()?.render?.(100).join("\n")).toContain(
  4544. "Plan complete. What would you like to do?",
  4545. );
  4546. expect(app.tui.render(100).join("\n")).toContain("Revised frozen plan");
  4547. expect(app.tui.render(100).join("\n")).not.toContain(
  4548. "Message · Enter send",
  4549. );
  4550. await app.stop();
  4551. });
  4552. it("supports explicit /plan and /permission mode commands", async () => {
  4553. const runtime = createRuntime();
  4554. const app = createTuiApp({
  4555. runtime,
  4556. terminal: new FakeTerminal(),
  4557. version: "0.1.0",
  4558. workspaceDir: "/workspace",
  4559. });
  4560. app.start();
  4561. await app.ready;
  4562. await app.submit("/plan on");
  4563. expect(app.tui.render(100).join("\n")).toContain("PLAN next");
  4564. await app.submit("/permission full");
  4565. expect(runtime.setPermissionMode).toHaveBeenCalledWith("bypassPermissions");
  4566. expect(app.tui.render(100).join("\n")).toContain("Full access");
  4567. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4568. await app.submit("Plan with Full access");
  4569. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4570. expect.objectContaining({ clientIntent: "plan-entry" }),
  4571. expect.any(AbortSignal),
  4572. );
  4573. expect(app.tui.render(100).join("\n")).toContain("PLAN");
  4574. expect(app.tui.render(100).join("\n")).toContain("Full access");
  4575. await app.stop();
  4576. });
  4577. it("opens a permission mode selector for bare /permission", async () => {
  4578. const runtime = createRuntime();
  4579. const terminal = new FakeTerminal();
  4580. const app = createTuiApp({
  4581. runtime,
  4582. terminal,
  4583. version: "0.1.0",
  4584. workspaceDir: "/workspace",
  4585. });
  4586. app.start();
  4587. await app.ready;
  4588. await app.submit("/permission");
  4589. expect(app.interaction.isActive()).toBe(true);
  4590. const rendered = app.interaction.current()?.render?.(100).join("\n") ?? "";
  4591. expect(rendered).toContain("╭─ Permission");
  4592. expect(rendered).toContain("Current · Auto");
  4593. expect(rendered).toContain("ASK");
  4594. expect(rendered).toContain("› AUTO");
  4595. expect(rendered).toContain("FULL");
  4596. expect(runtime.setPermissionMode).not.toHaveBeenCalled();
  4597. terminal.input?.("\u001b[B");
  4598. terminal.input?.("\r");
  4599. await vi.waitFor(() =>
  4600. expect(runtime.setPermissionMode).toHaveBeenCalledWith(
  4601. "bypassPermissions",
  4602. ),
  4603. );
  4604. expect(app.interaction.isActive()).toBe(false);
  4605. expect(app.tui.render(100).join("\n")).toContain("Full access");
  4606. await app.submit("/permission status");
  4607. expect(app.interaction.isActive()).toBe(false);
  4608. expect(
  4609. app.transcript
  4610. .snapshot()
  4611. .map((cell) => cell.content)
  4612. .join("\n"),
  4613. ).toContain("Permission mode: Full access.");
  4614. await app.stop();
  4615. });
  4616. it("opens the latest settled Plan as a read-only full snapshot", async () => {
  4617. const runtime = createRuntime();
  4618. vi.mocked(runtime.getLatestPlanReview).mockResolvedValue(
  4619. planReviewEventRequest("plan-review-settled"),
  4620. );
  4621. const app = createTuiApp({
  4622. runtime,
  4623. terminal: new FakeTerminal(),
  4624. version: "0.1.0",
  4625. workspaceDir: "/workspace",
  4626. });
  4627. app.start();
  4628. await app.ready;
  4629. await app.openSession("session-1");
  4630. await app.submit("/plan view");
  4631. expect(runtime.getLatestPlanReview).toHaveBeenCalledWith(
  4632. "mavis",
  4633. "session-1",
  4634. );
  4635. const rendered = app.interaction.current()?.render?.(100).join("\n") ?? "";
  4636. expect(rendered).toContain("Frozen plan");
  4637. expect(rendered).toContain("/history/session-1/artifacts/plan.md");
  4638. expect(rendered).not.toContain("Agree and start implementation");
  4639. app.interaction.current()?.handleInput?.("\u001b");
  4640. expect(app.interaction.isActive()).toBe(false);
  4641. await app.stop();
  4642. });
  4643. it("does not open a settled Plan after the active Session changes", async () => {
  4644. let resolveReview:
  4645. | ((request: TuiQuestionnaireRequest | undefined) => void)
  4646. | undefined;
  4647. const runtime = createRuntime();
  4648. vi.mocked(runtime.getLatestPlanReview).mockImplementation(
  4649. async () =>
  4650. await new Promise<TuiQuestionnaireRequest | undefined>((resolve) => {
  4651. resolveReview = resolve;
  4652. }),
  4653. );
  4654. const app = createTuiApp({
  4655. runtime,
  4656. terminal: new FakeTerminal(),
  4657. version: "0.1.0",
  4658. workspaceDir: "/workspace",
  4659. });
  4660. app.start();
  4661. await app.ready;
  4662. await app.openSession("session-1");
  4663. const viewing = app.submit("/plan view");
  4664. await vi.waitFor(() => expect(resolveReview).toBeTypeOf("function"));
  4665. await app.openSession("session-2");
  4666. resolveReview?.(planReviewEventRequest("stale-plan-review"));
  4667. await viewing;
  4668. expect(app.interaction.isActive()).toBe(false);
  4669. expect(app.tui.render(100).join("\n")).not.toContain("Frozen plan");
  4670. await app.stop();
  4671. });
  4672. it("blocks Plan entry but still allows Plan exit when the Runtime capability is disabled", async () => {
  4673. const runtime = createRuntime();
  4674. vi.mocked(runtime.getPlanModeCapabilities).mockResolvedValue({
  4675. entryEnabled: false,
  4676. });
  4677. const terminal = new FakeTerminal();
  4678. const app = createTuiApp({
  4679. runtime,
  4680. terminal,
  4681. version: "0.1.0",
  4682. workspaceDir: "/workspace",
  4683. });
  4684. app.start();
  4685. await app.ready;
  4686. await app.openSession("session-1");
  4687. terminal.input?.("\x1b[Z");
  4688. await app.submit("/plan on");
  4689. expect(app.tui.render(100).join("\n")).not.toContain("PLAN next");
  4690. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4691. vi.mocked(runtime.getSession).mockResolvedValue({
  4692. sessionId: "session-1",
  4693. workspace: "/workspace",
  4694. interactionMode: "plan",
  4695. });
  4696. await app.controller.refreshSessionMetadata("session-1");
  4697. terminal.input?.("\x1b[Z");
  4698. expect(app.tui.render(100).join("\n")).toContain("DEFAULT next");
  4699. await app.stop();
  4700. });
  4701. it("fails closed when the Runtime Plan capability cannot be loaded", async () => {
  4702. const runtime = createRuntime();
  4703. vi.mocked(runtime.getPlanModeCapabilities).mockRejectedValue(
  4704. new Error("Runtime unavailable"),
  4705. );
  4706. const terminal = new FakeTerminal();
  4707. const app = createTuiApp({
  4708. runtime,
  4709. terminal,
  4710. version: "0.1.0",
  4711. workspaceDir: "/workspace",
  4712. });
  4713. app.start();
  4714. await app.ready;
  4715. terminal.input?.("\x1b[Z");
  4716. await app.submit("/plan on");
  4717. expect(app.tui.render(100).join("\n")).not.toContain("PLAN next");
  4718. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4719. await app.stop();
  4720. });
  4721. it("submits the hidden Runtime engineering log command name as an ordinary prompt", async () => {
  4722. const terminal = new FakeTerminal();
  4723. const runtime = createRuntime();
  4724. const app = createTuiApp({
  4725. runtime,
  4726. terminal,
  4727. version: "0.1.0",
  4728. workspaceDir: "/workspace",
  4729. runtimeLogDirectory: "/home/dev/.minimax/v2/observability/logs",
  4730. });
  4731. await app.submit("/logs");
  4732. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4733. expect.objectContaining({ id: "session-1", content: "/logs" }),
  4734. expect.any(AbortSignal),
  4735. );
  4736. });
  4737. it("exposes sanitized checks and submits the hidden /config name as ordinary text", async () => {
  4738. const terminal = new FakeTerminal();
  4739. const runtime = createRuntime();
  4740. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  4741. {
  4742. requestId: "permission-1",
  4743. sessionId: "session-1",
  4744. toolName: "bash",
  4745. toolDescription: "Run tests",
  4746. },
  4747. ]);
  4748. const app = createTuiApp({
  4749. runtime,
  4750. terminal,
  4751. version: "0.1.0",
  4752. workspaceDir: "/workspace",
  4753. });
  4754. await app.submit("/doctor");
  4755. const doctorOutput = app.transcript.snapshot().at(-1)?.content ?? "";
  4756. expect(app.interaction.current()).toBeUndefined();
  4757. await app.submit("/config");
  4758. expect(app.interaction.current()).toBeUndefined();
  4759. await app.submit("/skills docs");
  4760. const skillsPanel = app.interaction.current();
  4761. const skillsOutput = skillsPanel?.render(80).join("\n") ?? "";
  4762. expect(app.tui.render(80).join("\n")).not.toContain("Message · Enter");
  4763. skillsPanel?.handleInput?.("\x1b");
  4764. await app.submit("/mcp browser");
  4765. const mcpPanel = app.interaction.current();
  4766. const mcpOutput = mcpPanel?.render(80).join("\n") ?? "";
  4767. expect(app.tui.render(80).join("\n")).not.toContain("Message · Enter");
  4768. mcpPanel?.handleInput?.("\x1b");
  4769. await app.submit("/permissions");
  4770. const output = app.transcript
  4771. .snapshot()
  4772. .map((cell) => cell.content)
  4773. .join("\n");
  4774. expect(runtime.getRuntimeDiagnostics).toHaveBeenCalledTimes(1);
  4775. expect(runtime.listSkills).toHaveBeenCalledWith("mavis", "docs");
  4776. expect(runtime.listMcpServers).toHaveBeenCalledWith("browser", "session-1");
  4777. expect(runtime.listPendingPermissions).toHaveBeenCalled();
  4778. expect(doctorOutput).toContain("Configuration check");
  4779. expect(doctorOutput).toContain("Status: Valid");
  4780. expect(doctorOutput).not.toContain("/doctor");
  4781. expect(output).toContain("Configuration check");
  4782. expect(output).not.toContain("Effective configuration");
  4783. expect(skillsOutput).toContain("Skills");
  4784. expect(skillsOutput).toContain("Built-in · 1");
  4785. expect(skillsOutput).toContain("Docs");
  4786. expect(skillsOutput).toContain("● available · builtin");
  4787. expect(mcpOutput).toContain("MCP servers");
  4788. expect(mcpOutput).toContain("browser");
  4789. expect(mcpOutput).toContain("◆ configured · stdio");
  4790. expect(output).toContain("bash · Run tests");
  4791. expect(output).not.toContain("TOKEN");
  4792. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  4793. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4794. expect.objectContaining({ id: "session-1", content: "/config" }),
  4795. expect.any(AbortSignal),
  4796. );
  4797. });
  4798. it("previews /feedback without uploading until Enter confirms the Runtime draft", async () => {
  4799. const terminal = new FakeTerminal();
  4800. terminal.rows = 30;
  4801. const runtime = createRuntime();
  4802. const app = createTuiApp({
  4803. runtime,
  4804. terminal,
  4805. version: "0.1.0",
  4806. workspaceDir: "/workspace",
  4807. });
  4808. app.start();
  4809. await app.ready;
  4810. await app.submit("/feedback Upload failed token=****");
  4811. expect(runtime.prepareFeedback).toHaveBeenCalledWith({
  4812. description: "Upload failed token=****",
  4813. });
  4814. expect(runtime.submitFeedback).not.toHaveBeenCalled();
  4815. expect(app.tui.hasOverlay()).toBe(false);
  4816. expect(app.interaction.isActive()).toBe(true);
  4817. const panel = app.interaction.current();
  4818. expect(panel?.render(80).join("\n")).toContain("Review feedback");
  4819. panel?.handleInput?.("d");
  4820. expect(panel?.render(80).join("\n")).toContain("Client mcode 0.1.0");
  4821. terminal.input?.("\r");
  4822. await vi.waitFor(() =>
  4823. expect(runtime.submitFeedback).toHaveBeenCalledWith(
  4824. "feedback-draft-1",
  4825. expect.objectContaining({ onPhase: expect.any(Function) }),
  4826. ),
  4827. );
  4828. expect(panel?.render(80).join("\n")).toContain("ticket-1");
  4829. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4830. terminal.input?.("\x1b");
  4831. expect(app.interaction.isActive()).toBe(false);
  4832. await app.stop();
  4833. });
  4834. it("cancels /feedback without uploading and keeps missing descriptions out of the Agent", async () => {
  4835. const terminal = new FakeTerminal();
  4836. const runtime = createRuntime();
  4837. const app = createTuiApp({
  4838. runtime,
  4839. terminal,
  4840. version: "0.1.0",
  4841. workspaceDir: "/workspace",
  4842. });
  4843. app.start();
  4844. await app.ready;
  4845. await app.submit("/feedback");
  4846. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  4847. kind: "final-summary",
  4848. content: "Usage: /feedback <message>",
  4849. });
  4850. expect(runtime.prepareFeedback).not.toHaveBeenCalled();
  4851. await app.submit("/feedback Cancel this report");
  4852. terminal.input?.("\x1b");
  4853. await vi.waitFor(() =>
  4854. expect(runtime.cancelFeedback).toHaveBeenCalledWith("feedback-draft-1"),
  4855. );
  4856. expect(runtime.submitFeedback).not.toHaveBeenCalled();
  4857. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4858. await app.stop();
  4859. });
  4860. it("keeps the status report local and submits the hidden /config name as text", async () => {
  4861. const terminal = new FakeTerminal();
  4862. terminal.rows = 24;
  4863. const runtime = createRuntime();
  4864. const app = createTuiApp({
  4865. runtime,
  4866. terminal,
  4867. version: "0.1.0",
  4868. workspaceDir: "/workspace",
  4869. });
  4870. app.start();
  4871. await app.ready;
  4872. const transcriptBeforeStatus = app.transcript.snapshot();
  4873. await app.submit("/status");
  4874. expect(app.tui.hasOverlay()).toBe(false);
  4875. expect(app.interaction.isActive()).toBe(true);
  4876. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  4877. const statusOutput = app.tui.render(80).join("\n");
  4878. expect(statusOutput).toContain("MCode status");
  4879. expect(statusOutput).toContain("Model");
  4880. expect(statusOutput).not.toContain("/status");
  4881. expect(statusOutput).toContain("/workspace");
  4882. expect(statusOutput).toMatch(/Branch:\s+Not a Git repository/u);
  4883. expect(statusOutput).toContain("Not applicable");
  4884. expect(statusOutput).toContain("Session");
  4885. expect(statusOutput).toContain("Permissions");
  4886. expect(statusOutput).toContain("Auto");
  4887. app.interaction.current()?.handleInput?.("\x1b");
  4888. expect(app.interaction.isActive()).toBe(false);
  4889. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  4890. await app.submit("/config");
  4891. expect(app.tui.hasOverlay()).toBe(false);
  4892. expect(app.interaction.isActive()).toBe(false);
  4893. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4894. expect.objectContaining({ id: "session-1", content: "/config" }),
  4895. expect.any(AbortSignal),
  4896. );
  4897. expect(runtime.getRuntimeDiagnostics).not.toHaveBeenCalled();
  4898. await app.stop();
  4899. });
  4900. it("commits the first frame immediately when the Pi renderer starts", async () => {
  4901. const terminal = new FakeTerminal();
  4902. const app = createTuiApp({
  4903. runtime: createRuntime(),
  4904. terminal,
  4905. version: "0.1.0",
  4906. workspaceDir: "/workspace",
  4907. });
  4908. let firstFrameCommitted = false;
  4909. void app.firstFrame.then(() => {
  4910. firstFrameCommitted = true;
  4911. });
  4912. app.start();
  4913. await app.firstFrame;
  4914. expect(terminal.started).toBe(true);
  4915. expect(firstFrameCommitted).toBe(true);
  4916. expect(terminal.writes.join("")).toContain("Tips for getting started");
  4917. await app.stop();
  4918. });
  4919. it("chooses the account region before routing login through the auth application", async () => {
  4920. const runtime = createRuntime();
  4921. const openedTargets: string[] = [];
  4922. const logoutUrl =
  4923. "https://agent.minimax.io/auth/logout?logout_redirect_uri=https%3A%2F%2Fagent.minimax.io";
  4924. let authenticated = false;
  4925. vi.mocked(runtime.getAccountStatus).mockImplementation(async () =>
  4926. authenticated
  4927. ? {
  4928. status: "ready",
  4929. defaultModel: "minimax/MiniMax-M2.7",
  4930. providerId: "minimax",
  4931. modelId: "MiniMax-M2.7",
  4932. authMode: "managed-login",
  4933. managedTokenPresent: true,
  4934. warnings: [],
  4935. }
  4936. : {
  4937. status: "needs-login",
  4938. authMode: "managed-login",
  4939. managedTokenPresent: false,
  4940. warnings: [],
  4941. },
  4942. );
  4943. const auth = {
  4944. login: vi.fn(
  4945. async (
  4946. onProgress?: (progress: McodeAuthProgress) => void,
  4947. _region?: "cn" | "en",
  4948. ) => {
  4949. authenticated = true;
  4950. onProgress?.({
  4951. state: "device-authorization",
  4952. userCode: "ABCD-EFGH",
  4953. verificationUri: "https://account.example.test/device",
  4954. expiresInSec: 300,
  4955. });
  4956. return {
  4957. state: "authenticated" as const,
  4958. message:
  4959. _region === "en"
  4960. ? "Signed in with MiniMax Global. Restart MCode to use this account region."
  4961. : "Signed in with MiniMax.",
  4962. };
  4963. },
  4964. ),
  4965. logout: vi.fn(async () => {
  4966. authenticated = false;
  4967. return {
  4968. state: "signed-out" as const,
  4969. message: "Signed out of MiniMax.",
  4970. logoutUrl,
  4971. };
  4972. }),
  4973. };
  4974. const notifyAuthContextChanged = vi.fn(async () => {
  4975. throw new Error("Hook lifecycle cleanup failed");
  4976. });
  4977. const app = createTuiApp({
  4978. runtime,
  4979. auth,
  4980. terminal: new FakeTerminal(),
  4981. version: "0.1.0",
  4982. workspaceDir: "/workspace",
  4983. openExternalTarget: async (target) => {
  4984. openedTargets.push(target);
  4985. throw new Error("no desktop session");
  4986. },
  4987. notifyAuthContextChanged,
  4988. });
  4989. app.start();
  4990. await app.ready;
  4991. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login");
  4992. await app.submit("/login");
  4993. expect(auth.login).not.toHaveBeenCalled();
  4994. expect(app.interaction.render(80).join("\n")).toContain("China (CN)");
  4995. expect(app.interaction.render(80).join("\n")).toContain("Global");
  4996. app.interaction.current()?.handleInput("\u001b[B");
  4997. app.interaction.current()?.handleInput("\r");
  4998. await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
  4999. await vi.waitFor(() =>
  5000. expect(app.controller.snapshot().account?.managedTokenPresent).toBe(true),
  5001. );
  5002. expect(app.getSurface()).toBe("conversation");
  5003. expect(app.tui.render(80).join("\n")).not.toContain("Sign in with /login");
  5004. expect(app.tui.render(80).join("\n")).not.toContain("Login required");
  5005. await app.submit("/logout");
  5006. await vi.waitFor(() =>
  5007. expect(app.controller.snapshot().account?.managedTokenPresent).toBe(
  5008. false,
  5009. ),
  5010. );
  5011. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login");
  5012. expect(auth.login).toHaveBeenCalledWith(expect.any(Function), "en");
  5013. expect(openedTargets).toEqual([
  5014. "https://account.example.test/device?client_surface=tui&download_source=mcode-internal",
  5015. logoutUrl,
  5016. ]);
  5017. await vi.waitFor(() =>
  5018. expect(app.transcript.snapshot()).toEqual(
  5019. expect.arrayContaining([
  5020. expect.objectContaining({
  5021. kind: "warning",
  5022. content:
  5023. "Couldn't open the default browser. Open the authorization URL above manually.",
  5024. }),
  5025. expect.objectContaining({
  5026. kind: "warning",
  5027. content:
  5028. "Couldn't open the default browser. Open the sign-out URL above manually.",
  5029. }),
  5030. ]),
  5031. ),
  5032. );
  5033. expect(app.transcript.snapshot().slice(-6)).toMatchObject([
  5034. {
  5035. kind: "final-summary",
  5036. content:
  5037. "Complete MiniMax login in your browser:\nhttps://account.example.test/device?client_surface=tui&download_source=mcode-internal\nCode: ABCD-EFGH",
  5038. },
  5039. {
  5040. kind: "warning",
  5041. content:
  5042. "Couldn't open the default browser. Open the authorization URL above manually.",
  5043. },
  5044. {
  5045. kind: "final-summary",
  5046. content:
  5047. "Signed in with MiniMax Global. Restart MCode to use this account region.",
  5048. },
  5049. {
  5050. kind: "final-summary",
  5051. content: "Signed out of MiniMax.",
  5052. },
  5053. {
  5054. kind: "final-summary",
  5055. content: `Finish signing out in your browser:\n${logoutUrl}`,
  5056. },
  5057. {
  5058. kind: "warning",
  5059. content:
  5060. "Couldn't open the default browser. Open the sign-out URL above manually.",
  5061. },
  5062. ]);
  5063. expect(auth.login).toHaveBeenCalledOnce();
  5064. expect(auth.logout).toHaveBeenCalledOnce();
  5065. expect(notifyAuthContextChanged.mock.calls).toEqual([
  5066. ["authenticated"],
  5067. ["logged_out"],
  5068. ]);
  5069. expect(
  5070. app.transcript
  5071. .snapshot()
  5072. .map((cell) => cell.content)
  5073. .join("\n"),
  5074. ).not.toContain("Sign-in wasn't completed");
  5075. expect(
  5076. app.transcript
  5077. .snapshot()
  5078. .map((cell) => cell.content)
  5079. .join("\n"),
  5080. ).not.toContain("Couldn't sign out");
  5081. expect(runtime.sendMessage).not.toHaveBeenCalled();
  5082. await app.stop();
  5083. });
  5084. it("clears Runtime auth context when the shared account is already signed out", async () => {
  5085. const notifyAuthContextChanged = vi.fn(async () => undefined);
  5086. const logoutUrl =
  5087. "https://agent.minimax.cn/auth/logout?logout_redirect_uri=https%3A%2F%2Fagent.minimax.cn";
  5088. const openExternalTarget = vi.fn(() => new Promise<void>(() => {}));
  5089. const app = createTuiApp({
  5090. runtime: createRuntime(),
  5091. auth: {
  5092. login: vi.fn(),
  5093. logout: vi.fn(async () => ({
  5094. state: "already-signed-out" as const,
  5095. message: "Already signed out of MiniMax.",
  5096. logoutUrl,
  5097. })),
  5098. },
  5099. terminal: new FakeTerminal(),
  5100. version: "0.1.0",
  5101. workspaceDir: "/workspace",
  5102. notifyAuthContextChanged,
  5103. openExternalTarget,
  5104. });
  5105. app.start();
  5106. await app.ready;
  5107. await app.submit("/logout");
  5108. expect(notifyAuthContextChanged).toHaveBeenCalledOnce();
  5109. expect(notifyAuthContextChanged).toHaveBeenCalledWith("logged_out");
  5110. expect(openExternalTarget).toHaveBeenCalledWith(logoutUrl);
  5111. expect(app.transcript.snapshot()).toEqual(
  5112. expect.arrayContaining([
  5113. expect.objectContaining({
  5114. content: `Finish signing out in your browser:\n${logoutUrl}`,
  5115. }),
  5116. ]),
  5117. );
  5118. await app.stop();
  5119. });
  5120. it("refreshes Runtime auth context when login renews an existing account", async () => {
  5121. const runtime = createRuntime();
  5122. let authenticated = false;
  5123. vi.mocked(runtime.getAccountStatus).mockImplementation(async () =>
  5124. authenticated
  5125. ? {
  5126. status: "ready",
  5127. defaultModel: "minimax/MiniMax-M2.7",
  5128. providerId: "minimax",
  5129. modelId: "MiniMax-M2.7",
  5130. authMode: "managed-login",
  5131. managedTokenPresent: true,
  5132. warnings: [],
  5133. }
  5134. : {
  5135. status: "needs-login",
  5136. authMode: "managed-login",
  5137. managedTokenPresent: false,
  5138. warnings: [],
  5139. },
  5140. );
  5141. const notifyAuthContextChanged = vi.fn(async () => undefined);
  5142. const auth = {
  5143. login: vi.fn(async () => {
  5144. authenticated = true;
  5145. return {
  5146. state: "already-authenticated" as const,
  5147. message: "Already signed in with MiniMax.",
  5148. };
  5149. }),
  5150. logout: vi.fn(async () => ({
  5151. state: "signed-out" as const,
  5152. message: "Signed out of MiniMax.",
  5153. })),
  5154. };
  5155. const app = createTuiApp({
  5156. runtime,
  5157. auth,
  5158. notifyAuthContextChanged,
  5159. terminal: new FakeTerminal(),
  5160. version: "0.1.0",
  5161. workspaceDir: "/workspace",
  5162. });
  5163. app.start();
  5164. await app.ready;
  5165. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login");
  5166. await app.submit("/login");
  5167. app.interaction.current()?.handleInput("\u001b[B");
  5168. app.interaction.current()?.handleInput("\r");
  5169. await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
  5170. expect(notifyAuthContextChanged).toHaveBeenCalledOnce();
  5171. expect(notifyAuthContextChanged).toHaveBeenCalledWith("authenticated");
  5172. await vi.waitFor(() =>
  5173. expect(app.controller.snapshot().account?.managedTokenPresent).toBe(true),
  5174. );
  5175. expect(app.getSurface()).toBe("conversation");
  5176. expect(app.tui.render(80).join("\n")).not.toContain("Sign in with /login");
  5177. expect(app.tui.render(80).join("\n")).not.toContain("Login required");
  5178. await app.stop();
  5179. });
  5180. it("exits immediately through /quit without aborting the shared Runtime turn", async () => {
  5181. const terminal = new FakeTerminal();
  5182. const runtime = createRuntime();
  5183. const abortSession = vi.spyOn(runtime, "abortSession");
  5184. const app = createTuiApp({
  5185. runtime,
  5186. terminal,
  5187. version: "0.1.0",
  5188. workspaceDir: "/workspace",
  5189. });
  5190. app.start();
  5191. await app.ready;
  5192. await app.submit("/quit");
  5193. await app.stopped;
  5194. expect(terminal.stopped).toBe(true);
  5195. expect(abortSession).not.toHaveBeenCalled();
  5196. });
  5197. it("does not restore /quit after reopening the exited Session", async () => {
  5198. const dataDir = await mkdtemp(join(tmpdir(), "mcode-quit-draft-"));
  5199. try {
  5200. const first = createTuiApp({
  5201. runtime: createRuntime(),
  5202. terminal: new FakeTerminal(),
  5203. version: "0.1.0",
  5204. dataDir,
  5205. workspaceDir: "/workspace",
  5206. });
  5207. await first.ready;
  5208. await first.openSession("session-1");
  5209. first.editor.setText("/quit");
  5210. first.editor.handleInput("\r");
  5211. await first.stopped;
  5212. const restored = createTuiApp({
  5213. runtime: createRuntime(),
  5214. terminal: new FakeTerminal(),
  5215. version: "0.1.0",
  5216. dataDir,
  5217. workspaceDir: "/workspace",
  5218. });
  5219. await restored.ready;
  5220. await restored.openSession("session-1");
  5221. expect(restored.editor.getText()).toBe("");
  5222. await restored.stop();
  5223. } finally {
  5224. await rm(dataDir, { recursive: true, force: true });
  5225. }
  5226. });
  5227. it("keeps warning status details visible until the local panel closes", async () => {
  5228. const terminal = new FakeTerminal();
  5229. terminal.rows = 40;
  5230. const runtime = createRuntime();
  5231. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  5232. status: "warning",
  5233. defaultModel: "minimax/MiniMax-M2.7",
  5234. providerId: "minimax",
  5235. modelId: "MiniMax-M2.7",
  5236. authMode: "managed-login",
  5237. managedTokenPresent: true,
  5238. warnings: ["Desktop login should be refreshed soon."],
  5239. });
  5240. const app = createTuiApp({
  5241. runtime,
  5242. terminal,
  5243. version: "0.1.0",
  5244. workspaceDir: "/workspace",
  5245. });
  5246. app.start();
  5247. await app.ready;
  5248. const transcriptBeforeStatus = app.transcript.snapshot();
  5249. await app.submit("/status");
  5250. const rendered = app.tui.render(80).join("\n");
  5251. expect(app.interaction.current()).toBeDefined();
  5252. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  5253. expect(rendered).toContain("Needs attention");
  5254. expect(rendered).toContain("Connected with warnings");
  5255. expect(rendered).toContain("Model");
  5256. expect(rendered).toContain("Desktop login should be refreshed");
  5257. expect(rendered).toContain("soon.");
  5258. app.interaction.current()?.handleInput?.("\x1b");
  5259. expect(app.interaction.current()).toBeUndefined();
  5260. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  5261. expect(app.tui.render(80).join("\n")).not.toContain(
  5262. "Desktop login should be refreshed",
  5263. );
  5264. await app.stop();
  5265. });
  5266. it("reports doctor failures and submits the hidden /config name as text", async () => {
  5267. const runtime = createRuntime();
  5268. vi.mocked(runtime.getRuntimeDiagnostics).mockRejectedValue(
  5269. new Error("Diagnostics unavailable"),
  5270. );
  5271. const app = createTuiApp({
  5272. runtime,
  5273. terminal: new FakeTerminal(),
  5274. version: "0.1.0",
  5275. workspaceDir: "/workspace",
  5276. });
  5277. await app.submit("/doctor");
  5278. expect(app.tui.hasOverlay()).toBe(false);
  5279. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  5280. kind: "error",
  5281. content:
  5282. "Couldn't load configuration check: Diagnostics unavailable. Retry.",
  5283. });
  5284. await app.submit("/config");
  5285. expect(app.tui.hasOverlay()).toBe(false);
  5286. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5287. expect.objectContaining({ id: "session-1", content: "/config" }),
  5288. expect.any(AbortSignal),
  5289. );
  5290. expect(runtime.getRuntimeDiagnostics).toHaveBeenCalledTimes(1);
  5291. });
  5292. it("lets an async Session card replace a local status panel", async () => {
  5293. const terminal = new FakeTerminal();
  5294. const runtime = createRuntime();
  5295. let resolveSessionPage:
  5296. | ((page: {
  5297. sessions: Array<{
  5298. sessionId: string;
  5299. title: string;
  5300. workspaceDir: string;
  5301. updatedAt: number;
  5302. }>;
  5303. hasMore: boolean;
  5304. }) => void)
  5305. | undefined;
  5306. vi.mocked(runtime.listSessionPage).mockImplementationOnce(
  5307. async () =>
  5308. await new Promise((resolve) => {
  5309. resolveSessionPage = resolve;
  5310. }),
  5311. );
  5312. const app = createTuiApp({
  5313. runtime,
  5314. terminal,
  5315. version: "0.1.0",
  5316. workspaceDir: "/workspace",
  5317. });
  5318. await app.ready;
  5319. const transcriptBeforeStatus = app.transcript.snapshot();
  5320. const sessionCard = app.submit("/sessions");
  5321. await vi.waitFor(() =>
  5322. expect(runtime.listSessionPage).toHaveBeenCalledOnce(),
  5323. );
  5324. await app.submit("/status");
  5325. expect(app.tui.hasOverlay()).toBe(false);
  5326. expect(app.interaction.isActive()).toBe(true);
  5327. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  5328. expect(app.tui.render(80).join("\n")).toContain("MCode status");
  5329. resolveSessionPage?.({
  5330. sessions: [
  5331. {
  5332. sessionId: "session-race",
  5333. title: "Session opened after status",
  5334. workspaceDir: "/workspace",
  5335. updatedAt: Date.now(),
  5336. },
  5337. ],
  5338. hasMore: false,
  5339. });
  5340. await sessionCard;
  5341. expect(app.tui.hasOverlay()).toBe(false);
  5342. expect(app.interaction.isActive()).toBe(true);
  5343. app.interaction.current()?.handleInput?.("\x03");
  5344. expect(runtime.getSession).not.toHaveBeenCalled();
  5345. expect(app.interaction.isActive()).toBe(false);
  5346. expect(app.tui.hasOverlay()).toBe(false);
  5347. await app.stop();
  5348. });
  5349. it("keeps unsupported standalone MCP inspection concise and recoverable", async () => {
  5350. const runtime = createRuntime();
  5351. vi.mocked(runtime.listMcpServers).mockRejectedValue(
  5352. Object.assign(new Error("DesktopService implementation detail"), {
  5353. status: 501,
  5354. code: "NOT_IMPLEMENTED",
  5355. }),
  5356. );
  5357. const app = createTuiApp({
  5358. runtime,
  5359. terminal: new FakeTerminal(),
  5360. version: "0.1.0",
  5361. workspaceDir: "/workspace",
  5362. });
  5363. await app.submit("/mcp");
  5364. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  5365. kind: "warning",
  5366. content:
  5367. "MCP status is not available in this build. Configured MCP tools remain available.",
  5368. });
  5369. });
  5370. it("registers enabled Skills as discoverable slash commands without shadowing built-ins", async () => {
  5371. const terminal = new FakeTerminal();
  5372. const runtime = createRuntime();
  5373. vi.mocked(runtime.listSkills).mockResolvedValue({
  5374. skills: [
  5375. {
  5376. name: "docs",
  5377. displayName: "Docs",
  5378. description: "Read project docs",
  5379. enabled: true,
  5380. sourceKind: "builtin",
  5381. },
  5382. {
  5383. name: "disabled-skill",
  5384. enabled: false,
  5385. },
  5386. {
  5387. name: "help",
  5388. enabled: true,
  5389. },
  5390. ...Array.from({ length: 14 }, (_, index) => ({
  5391. name: `skill-${index}`,
  5392. description: `Generated skill ${index}`,
  5393. enabled: true,
  5394. })),
  5395. ],
  5396. hasMore: false,
  5397. });
  5398. const app = createTuiApp({
  5399. runtime,
  5400. terminal,
  5401. version: "0.1.0",
  5402. workspaceDir: "/workspace",
  5403. });
  5404. app.start();
  5405. await app.ready;
  5406. app.editor.setText("/docs summarize this repository");
  5407. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5408. "Skill · instructions · Enter invoke",
  5409. );
  5410. app.editor.setText("/context");
  5411. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5412. "Command · Enter run",
  5413. );
  5414. app.editor.setText("/context explain this repository");
  5415. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5416. "Prompt · Enter send",
  5417. );
  5418. app.editor.setText("/stop");
  5419. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5420. "Command · Enter run",
  5421. );
  5422. app.editor.setText("/config");
  5423. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5424. "Prompt · Enter send",
  5425. );
  5426. app.editor.setText("");
  5427. await app.submit("/help");
  5428. expect(app.transcript.snapshot()).toEqual([]);
  5429. expect(app.tui.hasOverlay()).toBe(false);
  5430. expect(app.interaction.isActive()).toBe(true);
  5431. for (const character of "docs") terminal.input?.(character);
  5432. terminal.input?.("\r");
  5433. expect(app.tui.hasOverlay()).toBe(false);
  5434. expect(app.interaction.isActive()).toBe(false);
  5435. expect(app.editor.getText()).toBe("");
  5436. await app.submit("/docs summarize this repository");
  5437. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5438. expect.objectContaining({
  5439. id: "session-1",
  5440. content: "/docs summarize this repository",
  5441. }),
  5442. expect.any(AbortSignal),
  5443. );
  5444. vi.mocked(runtime.sendMessage).mockClear();
  5445. await app.submit("/disabled-skill");
  5446. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5447. expect.objectContaining({ id: "session-1", content: "/disabled-skill" }),
  5448. expect.any(AbortSignal),
  5449. );
  5450. await app.stop();
  5451. });
  5452. it("deduplicates configured Skills case-insensitively and reserves built-in names", async () => {
  5453. const terminal = new FakeTerminal();
  5454. const runtime = createRuntime();
  5455. vi.mocked(runtime.listSkills).mockResolvedValue({
  5456. skills: [
  5457. {
  5458. name: "HELP",
  5459. description: "A Skill that must not shadow /help",
  5460. enabled: true,
  5461. },
  5462. {
  5463. name: "Docs",
  5464. description: "Read project docs",
  5465. enabled: true,
  5466. },
  5467. {
  5468. name: "docs",
  5469. description: "Duplicate project docs command",
  5470. enabled: true,
  5471. },
  5472. ],
  5473. hasMore: false,
  5474. });
  5475. const app = createTuiApp({
  5476. runtime,
  5477. terminal,
  5478. version: "0.1.0",
  5479. workspaceDir: "/workspace",
  5480. });
  5481. app.start();
  5482. await app.ready;
  5483. await app.submit("/help");
  5484. const helpPanel = app.interaction.current();
  5485. expect(helpPanel).toBeDefined();
  5486. helpPanel?.handleInput?.("\x1b");
  5487. await app.submit("/help [arguments]");
  5488. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5489. expect.objectContaining({
  5490. id: "session-1",
  5491. content: "/help [arguments]",
  5492. }),
  5493. expect.any(AbortSignal),
  5494. );
  5495. vi.mocked(runtime.sendMessage).mockClear();
  5496. await app.submit("/docs explain this repository");
  5497. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5498. expect.objectContaining({
  5499. id: "session-1",
  5500. content: "/docs explain this repository",
  5501. }),
  5502. expect.any(AbortSignal),
  5503. );
  5504. await app.stop();
  5505. });
  5506. it("uses public Runtime owners for Session inspection commands", async () => {
  5507. const terminal = new FakeTerminal();
  5508. terminal.rows = 40;
  5509. const runtime = createRuntime();
  5510. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  5511. status: "ready",
  5512. defaultModel: "minimax/MiniMax-M3",
  5513. providerId: "minimax-cn-coding-plan",
  5514. authMode: "managed-login",
  5515. managedTokenPresent: true,
  5516. modelSource: "token-plan",
  5517. tokenPlanQuotaState: "available",
  5518. tokenPlanSummary: { tier: "Ultra Plan", creditBalance: "0" },
  5519. tokenPlanQuota: {
  5520. fiveHour: { remainingPercent: 100, unlimited: false },
  5521. weekly: { remainingPercent: 99, unlimited: false },
  5522. video: { remainingCount: 5, totalCount: 5, unlimited: false },
  5523. },
  5524. warnings: [],
  5525. });
  5526. const app = createTuiApp({
  5527. runtime,
  5528. terminal,
  5529. version: "0.1.0",
  5530. workspaceDir: "/workspace",
  5531. });
  5532. await app.submit("Create a session");
  5533. vi.mocked(runtime.sendMessage).mockClear();
  5534. vi.mocked(runtime.getSessionUsage).mockClear();
  5535. vi.mocked(runtime.getContextSnapshot).mockResolvedValueOnce({
  5536. status: "live",
  5537. contextUsage: {
  5538. contextWindowTokens: 10_000,
  5539. usedTokens: 3_000,
  5540. totalCountSource: "PROVIDER_USAGE_ANCHORED",
  5541. components: [],
  5542. },
  5543. });
  5544. const transcriptBeforeUsage = app.transcript.snapshot();
  5545. await app.submit("/usage");
  5546. const usageOutput = app.tui.render(80).join("\n");
  5547. expect(app.interaction.current()).toBeDefined();
  5548. expect(app.transcript.snapshot()).toEqual(transcriptBeforeUsage);
  5549. expect(usageOutput).toContain("Usage");
  5550. expect(usageOutput).toContain("120 total");
  5551. expect(usageOutput).toContain("30% used · 70% free");
  5552. expect(usageOutput).toContain("Ultra Plan");
  5553. expect(usageOutput).toContain("100% left");
  5554. app.interaction.current()?.handleInput?.("\x1b");
  5555. expect(app.interaction.current()).toBeUndefined();
  5556. expect(app.transcript.snapshot()).toEqual(transcriptBeforeUsage);
  5557. await app.submit("/compact keep test evidence");
  5558. expect(runtime.getSessionUsage).toHaveBeenCalledWith("session-1");
  5559. expect(runtime.getContextSnapshot).toHaveBeenCalledWith("session-1");
  5560. expect(runtime.getAccountStatus).toHaveBeenCalledWith("session-1", {
  5561. includeMembership: true,
  5562. forceRefresh: true,
  5563. });
  5564. expect(runtime.requestCompaction).toHaveBeenCalledWith(
  5565. "session-1",
  5566. "mavis",
  5567. "keep test evidence",
  5568. );
  5569. expect(runtime.sendMessage).not.toHaveBeenCalled();
  5570. const output = app.transcript
  5571. .snapshot()
  5572. .map((cell) => cell.content)
  5573. .join("\n");
  5574. expect(output).not.toContain("Session usage");
  5575. expect(output).not.toMatch(
  5576. /Turns|Total tokens|Cost|Reasoning|Cache|Runtime|source|compaction|snapshot/i,
  5577. );
  5578. expect(output).not.toContain("Compaction completed");
  5579. expect(output).not.toContain("4,000 → 1,200 tokens");
  5580. expect(output).not.toContain("compact-1");
  5581. });
  5582. it("shows compaction as live activity until the Runtime request settles", async () => {
  5583. const runtime = createRuntime();
  5584. let resolveCompaction:
  5585. | ((result: {
  5586. success: true;
  5587. sessionId: string;
  5588. compactionId: string;
  5589. }) => void)
  5590. | undefined;
  5591. vi.mocked(runtime.requestCompaction).mockImplementationOnce(
  5592. async () =>
  5593. await new Promise((resolve) => {
  5594. resolveCompaction = resolve;
  5595. }),
  5596. );
  5597. const app = createTuiApp({
  5598. runtime,
  5599. terminal: new FakeTerminal(),
  5600. version: "0.1.0",
  5601. workspaceDir: "/workspace",
  5602. });
  5603. await app.submit("Create a session");
  5604. const pending = app.submit("/compact keep decisions");
  5605. await vi.waitFor(() =>
  5606. expect(app.tui.render(80).join("\n")).toContain("Compacting context"),
  5607. );
  5608. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
  5609. resolveCompaction?.({
  5610. success: true,
  5611. sessionId: "session-1",
  5612. compactionId: "compact-1",
  5613. });
  5614. await pending;
  5615. expect(app.tui.render(80).join("\n")).not.toContain("Compacting context");
  5616. });
  5617. it("treats Runtime NOTHING_TO_COMPACT as a recoverable Session state", async () => {
  5618. const runtime = createRuntime();
  5619. vi.mocked(runtime.requestCompaction).mockRejectedValue(
  5620. Object.assign(new Error("HTTP 400 implementation detail"), {
  5621. status: 400,
  5622. code: "NOTHING_TO_COMPACT",
  5623. }),
  5624. );
  5625. const app = createTuiApp({
  5626. runtime,
  5627. terminal: new FakeTerminal(),
  5628. version: "0.1.0",
  5629. workspaceDir: "/workspace",
  5630. });
  5631. await app.submit("Create a session");
  5632. await app.submit("/compact");
  5633. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  5634. kind: "final-summary",
  5635. content: "No compaction is needed for this conversation yet.",
  5636. });
  5637. });
  5638. it("shows account usage before a Session exists and keeps Session-only inspection recoverable", async () => {
  5639. const runtime = createRuntime();
  5640. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  5641. status: "ready",
  5642. authMode: "byok",
  5643. managedTokenPresent: false,
  5644. modelSource: "byok",
  5645. tokenPlanQuotaState: "available",
  5646. tokenPlanSummary: { tier: "Pro Plan" },
  5647. tokenPlanQuota: {
  5648. fiveHour: { remainingPercent: 75, unlimited: false },
  5649. weekly: { remainingPercent: 50, unlimited: false },
  5650. },
  5651. warnings: [],
  5652. });
  5653. const terminal = new FakeTerminal();
  5654. terminal.rows = 40;
  5655. const app = createTuiApp({
  5656. runtime,
  5657. terminal,
  5658. version: "0.1.0",
  5659. workspaceDir: "/workspace",
  5660. });
  5661. await app.submit("/usage");
  5662. const usageOutput = app.tui.render(80).join("\n");
  5663. expect(app.interaction.current()).toBeDefined();
  5664. expect(app.transcript.snapshot()).toEqual([]);
  5665. expect(usageOutput).toContain("Usage");
  5666. expect(usageOutput).toContain("Account only");
  5667. expect(usageOutput).toContain("Pro Plan");
  5668. expect(usageOutput).toContain("75% left");
  5669. app.interaction.current()?.handleInput?.("\x1b");
  5670. expect(app.interaction.current()).toBeUndefined();
  5671. expect(app.transcript.snapshot()).toEqual([]);
  5672. await app.submit("/compact");
  5673. expect(runtime.getSessionUsage).not.toHaveBeenCalled();
  5674. expect(runtime.getContextSnapshot).not.toHaveBeenCalled();
  5675. expect(runtime.getAccountStatus).toHaveBeenCalledWith(undefined, {
  5676. includeMembership: true,
  5677. forceRefresh: true,
  5678. });
  5679. expect(app.transcript.snapshot()).toEqual([]);
  5680. expect(app.tui.render(80).join("\n")).toContain(
  5681. "Start or resume a Session before compacting it.",
  5682. );
  5683. });
  5684. it("keeps prompt history and long bracketed paste intact in the Composer", async () => {
  5685. const terminal = new FakeTerminal();
  5686. const runtime = createRuntime();
  5687. const app = createTuiApp({
  5688. runtime,
  5689. terminal,
  5690. version: "0.1.0",
  5691. workspaceDir: "/workspace",
  5692. });
  5693. app.start();
  5694. await app.ready;
  5695. terminal.input?.("first prompt");
  5696. terminal.input?.("\r");
  5697. await vi.waitFor(() =>
  5698. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  5699. );
  5700. terminal.input?.("second prompt");
  5701. terminal.input?.("\r");
  5702. await vi.waitFor(() =>
  5703. expect(runtime.sendMessage).toHaveBeenCalledTimes(2),
  5704. );
  5705. terminal.input?.("\x1b[A");
  5706. expect(app.editor.getText()).toBe("second prompt");
  5707. terminal.input?.("\x1b[A");
  5708. expect(app.editor.getText()).toBe("first prompt");
  5709. terminal.input?.("\x1b[B");
  5710. expect(app.editor.getText()).toBe("second prompt");
  5711. app.editor.setText("");
  5712. const pasted = `Explain this payload:\n${"x".repeat(1_200)}`;
  5713. terminal.input?.(`\x1b[200~${pasted}\x1b[201~`);
  5714. expect(app.editor.getText()).toContain("[paste #");
  5715. expect(app.editor.getExpandedText()).toBe(pasted);
  5716. terminal.input?.("\r");
  5717. await vi.waitFor(() =>
  5718. expect(runtime.sendMessage).toHaveBeenCalledTimes(3),
  5719. );
  5720. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  5721. expect.objectContaining({ id: "session-1", content: pasted }),
  5722. expect.any(AbortSignal),
  5723. );
  5724. await app.stop();
  5725. });
  5726. it("trusts bracketed paste and submits dense typed input without a false newline", async () => {
  5727. const terminal = new FakeTerminal();
  5728. Object.defineProperty(terminal, "capabilities", {
  5729. value: {
  5730. terminalId: "unknown",
  5731. platform: "linux",
  5732. isTTY: true,
  5733. transport: "local",
  5734. multiplexer: "none",
  5735. color: true,
  5736. colorLevel: 3,
  5737. } satisfies TerminalCapabilities,
  5738. });
  5739. const runtime = createRuntime();
  5740. const app = createTuiApp({
  5741. runtime,
  5742. terminal,
  5743. version: "0.1.0",
  5744. workspaceDir: "/workspace",
  5745. });
  5746. app.start();
  5747. await app.ready;
  5748. for (const character of "abcdefgh") terminal.input?.(character);
  5749. terminal.input?.("\r");
  5750. await vi.waitFor(() =>
  5751. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  5752. );
  5753. expect(app.editor.getText()).toBe("");
  5754. await app.stop();
  5755. });
  5756. it("projects an otty image paste as an inline editor placeholder", async () => {
  5757. const terminal = new FakeTerminal();
  5758. const resolveAttachment = vi.fn(async () => ({
  5759. type: "image" as const,
  5760. filePath: "/tmp/otty-paste/image-123.png",
  5761. fileName: "image-123.png",
  5762. mimeType: "image/png",
  5763. sizeBytes: 1_024,
  5764. }));
  5765. const app = createTuiApp({
  5766. runtime: createRuntime(),
  5767. terminal,
  5768. version: "0.1.0",
  5769. workspaceDir: "/workspace",
  5770. resolveAttachment,
  5771. });
  5772. app.start();
  5773. await app.ready;
  5774. terminal.input?.("\x1b[200~/tmp/otty-paste/image-123.png\x1b[201~");
  5775. await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledTimes(1));
  5776. const rendered = app.tui.render(80).join("\n");
  5777. expect(app.editor.getText()).toBe("[Image #1] ");
  5778. expect(rendered).toContain("[Image #1]");
  5779. expect(rendered).not.toContain("/tmp/otty-paste/");
  5780. await app.stop();
  5781. });
  5782. it.each(["regular", "fullscreen"] as const)(
  5783. "keeps image preview controls separate from Enter submission in %s mode",
  5784. async (tuiMode) => {
  5785. const terminal = new FakeTerminal();
  5786. terminal.rows = 40;
  5787. const runtime = createRuntime();
  5788. const app = createTuiApp({
  5789. runtime,
  5790. terminal,
  5791. tuiMode,
  5792. version: "0.1.0",
  5793. workspaceDir: "/workspace",
  5794. resolveAttachment: async () => ({
  5795. type: "image",
  5796. filePath: "/tmp/image-preview-missing.png",
  5797. fileName: "preview.png",
  5798. mimeType: "image/png",
  5799. sizeBytes: 32768,
  5800. }),
  5801. });
  5802. app.start();
  5803. await app.ready;
  5804. terminal.input?.("\x1b[200~/tmp/image-preview-missing.png\x1b[201~");
  5805. await vi.waitFor(() =>
  5806. expect(app.editor.getAttachmentPreview()?.id).toBe(
  5807. "/tmp/image-preview-missing.png",
  5808. ),
  5809. );
  5810. expect(app.editor.getText()).toBe("[Image #1] ");
  5811. expect(app.tui.render(80).join("\n")).toContain("preview.png");
  5812. expect(app.tui.render(80).join("\n")).toContain("32 KB");
  5813. expect(app.tui.render(80).join("\n")).not.toMatch(/Option\+I|Alt\+I/);
  5814. expect(runtime.sendMessage).not.toHaveBeenCalled();
  5815. terminal.input?.("\x1b");
  5816. expect(app.editor.getAttachmentPreview()).toBeUndefined();
  5817. terminal.input?.("\x1b[D");
  5818. expect(app.editor.getAttachmentPreview()?.id).toBe(
  5819. "/tmp/image-preview-missing.png",
  5820. );
  5821. terminal.input?.("\r");
  5822. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalled());
  5823. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5824. expect.objectContaining({
  5825. content: "",
  5826. attachments: [
  5827. expect.objectContaining({
  5828. local: { filePath: "/tmp/image-preview-missing.png" },
  5829. }),
  5830. ],
  5831. }),
  5832. expect.any(AbortSignal),
  5833. );
  5834. expect(app.editor.getAttachmentPreview()).toBeUndefined();
  5835. await app.stop();
  5836. },
  5837. );
  5838. it("projects a pasted absolute WeChat image path as a short inline placeholder", async () => {
  5839. const terminal = new FakeTerminal();
  5840. const runtime = createRuntime();
  5841. const wechatImagePath =
  5842. "D:\\Yingyong\\social\\wechat\\xwechat_files\\wxid_demo\\temp\\RWTemp\\2026-08\\3336519cd4d5351f4bc5a5a68c7fea75.png";
  5843. const resolveAttachment = vi.fn(async () => ({
  5844. type: "image" as const,
  5845. filePath: wechatImagePath,
  5846. fileName: "3336519cd4d5351f4bc5a5a68c7fea75.png",
  5847. mimeType: "image/png",
  5848. sizeBytes: 1_024,
  5849. }));
  5850. const app = createTuiApp({
  5851. runtime,
  5852. terminal,
  5853. version: "0.1.0",
  5854. workspaceDir: "D:\\workspace",
  5855. resolveAttachment,
  5856. });
  5857. app.start();
  5858. await app.ready;
  5859. terminal.input?.(`\x1b[200~'${wechatImagePath}'\x1b[201~`);
  5860. await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledOnce());
  5861. expect(resolveAttachment).toHaveBeenCalledWith(`'${wechatImagePath}'`, {
  5862. source: "terminal-paste",
  5863. workspaceDir: "D:\\workspace",
  5864. });
  5865. expect(app.editor.getText()).toBe("[Image #1] ");
  5866. expect(app.tui.render(80).join("\n")).not.toContain("xwechat_files");
  5867. await app.submit("Inspect this image");
  5868. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5869. expect.objectContaining({
  5870. content: "Inspect this image",
  5871. attachments: [
  5872. expect.objectContaining({
  5873. local: { filePath: wechatImagePath },
  5874. }),
  5875. ],
  5876. }),
  5877. expect.any(AbortSignal),
  5878. );
  5879. await app.stop();
  5880. });
  5881. it("keeps an image placeholder visible before a long CJK prompt", async () => {
  5882. const terminal = new FakeTerminal();
  5883. const resolveAttachment = vi.fn(async () => ({
  5884. type: "image" as const,
  5885. filePath: "/tmp/otty-paste/logo.png",
  5886. fileName: "logo.png",
  5887. mimeType: "image/png",
  5888. sizeBytes: 1_024,
  5889. }));
  5890. const app = createTuiApp({
  5891. runtime: createRuntime(),
  5892. terminal,
  5893. version: "0.1.0",
  5894. workspaceDir: "/workspace",
  5895. resolveAttachment,
  5896. });
  5897. app.start();
  5898. await app.ready;
  5899. terminal.input?.("\x1b[200~/tmp/otty-paste/logo.png\x1b[201~");
  5900. await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledTimes(1));
  5901. app.editor.insertTextAtCursor(
  5902. "logo 不太对还是,还出现了奇怪的--; logo你自己截取把:",
  5903. );
  5904. const rendered = app.tui.render(80).join("\n");
  5905. expect(rendered).toContain("[Image #1]");
  5906. await app.stop();
  5907. });
  5908. it("removes an inline image placeholder and its attachment with Backspace", async () => {
  5909. const terminal = new FakeTerminal();
  5910. const resolveAttachment = vi.fn(async () => ({
  5911. type: "image" as const,
  5912. filePath: "/tmp/otty-paste/image-123.png",
  5913. fileName: "image-123.png",
  5914. mimeType: "image/png",
  5915. sizeBytes: 1_024,
  5916. }));
  5917. const app = createTuiApp({
  5918. runtime: createRuntime(),
  5919. terminal,
  5920. version: "0.1.0",
  5921. workspaceDir: "/workspace",
  5922. resolveAttachment,
  5923. });
  5924. app.start();
  5925. await app.ready;
  5926. app.editor.setText("first line\nsecond line");
  5927. terminal.input?.("\x1b[200~/tmp/otty-paste/image-123.png\x1b[201~");
  5928. await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledTimes(1));
  5929. expect(app.editor.getText()).toBe("first line\nsecond line [Image #1] ");
  5930. expect(app.tui.render(80).join("\n")).toContain("[Image #1]");
  5931. terminal.input?.("\x7f");
  5932. await vi.waitFor(() =>
  5933. expect(app.editor.getText().trimEnd()).toBe("first line\nsecond line"),
  5934. );
  5935. expect(app.tui.render(80).join("\n")).not.toContain("[Image #1]");
  5936. await app.stop();
  5937. });
  5938. it("resumes Desktop history, supports rename, and executes the files-unchanged fork flow", async () => {
  5939. const terminal = new FakeTerminal();
  5940. const runtime = createRuntime();
  5941. vi.mocked(runtime.listSessions).mockResolvedValue([
  5942. {
  5943. sessionId: "session-existing",
  5944. title: "Existing session",
  5945. workspaceDir: "/workspace",
  5946. updatedAt: 200,
  5947. },
  5948. ]);
  5949. const history = [
  5950. {
  5951. id: "msg-user-v1-fork-source",
  5952. turnId: "turn-history",
  5953. role: "user" as const,
  5954. content: "Try the original approach",
  5955. timestamp: 90,
  5956. },
  5957. {
  5958. id: "assistant-fork-source",
  5959. turnId: "turn-history",
  5960. role: "assistant" as const,
  5961. content: "Recovered answer",
  5962. timestamp: 100,
  5963. actions: { fork: true },
  5964. },
  5965. ];
  5966. const forkRuntime = runtime as TuiRuntime & TuiSessionForkPort;
  5967. vi.mocked(runtime.getMessages).mockResolvedValue(history);
  5968. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  5969. messages: history,
  5970. hasMore: false,
  5971. });
  5972. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  5973. sessionId === "session-fork"
  5974. ? {
  5975. sessionId,
  5976. parentSessionId: "session-existing",
  5977. title: "Existing session (fork 1)",
  5978. workspaceDir: "/workspace",
  5979. }
  5980. : {
  5981. sessionId,
  5982. title: "Existing session",
  5983. workspaceDir: "/workspace",
  5984. },
  5985. );
  5986. vi.mocked(forkRuntime.getSessionForkOptions).mockResolvedValue({
  5987. canFork: true,
  5988. suggestedTitle: "Existing session (fork 1)",
  5989. worktreeVisible: false,
  5990. worktreeEligible: false,
  5991. });
  5992. vi.mocked(forkRuntime.forkSession).mockResolvedValue({
  5993. session: {
  5994. sessionId: "session-fork",
  5995. parentSessionId: "session-existing",
  5996. title: "Existing session (fork 1)",
  5997. workspaceDir: "/workspace",
  5998. },
  5999. });
  6000. const app = createTuiApp({
  6001. runtime,
  6002. terminal,
  6003. version: "0.1.0",
  6004. workspaceDir: "/workspace",
  6005. });
  6006. app.start();
  6007. await app.ready;
  6008. await app.submit("/sessions");
  6009. expect(app.tui.hasOverlay()).toBe(false);
  6010. expect(app.interaction.isActive()).toBe(true);
  6011. app.interaction.current()?.handleInput?.("\x1b");
  6012. expect(app.interaction.isActive()).toBe(false);
  6013. await app.submit("/resume 1");
  6014. expect(app.getSurface()).toBe("conversation");
  6015. vi.mocked(runtime.renameSession).mockClear();
  6016. await app.submit("/rename");
  6017. expect(runtime.renameSession).not.toHaveBeenCalled();
  6018. expect(app.interaction.isActive()).toBe(true);
  6019. expect(app.tui.render(100).join("\n")).toContain(
  6020. "Sessions / Rename session",
  6021. );
  6022. app.interaction.current()?.handleInput?.("\x1b");
  6023. expect(app.tui.render(100).join("\n")).toContain("Sessions");
  6024. app.interaction.current()?.handleInput?.("\x1b");
  6025. expect(app.interaction.isActive()).toBe(false);
  6026. await app.submit("/rename Renamed session");
  6027. vi.mocked(runtime.createSession).mockClear();
  6028. await app.submit("/fork");
  6029. await vi.waitFor(() =>
  6030. expect(runtime.listSessionInputSummaries).toHaveBeenCalledWith(
  6031. "session-existing",
  6032. {
  6033. limit: 100,
  6034. },
  6035. ),
  6036. );
  6037. // The new fork flow owns the surface with the history picker, not the
  6038. // generic transcript panel.
  6039. expect(renderTerminalViewport(app, terminal)).toContain(
  6040. "Fork from a previous message",
  6041. );
  6042. expect(renderTerminalViewport(app, terminal)).not.toContain("Transcript");
  6043. // Esc cancels without calling the fork Runtime API.
  6044. const beforeForkCalls = vi.mocked(runtime.forkSession).mock.calls.length;
  6045. app.surfaceHost.popFeature();
  6046. expect(vi.mocked(runtime.forkSession).mock.calls.length).toBe(
  6047. beforeForkCalls,
  6048. );
  6049. const transcriptBeforeStatus = app.transcript.snapshot();
  6050. await app.submit("/status");
  6051. expect(runtime.getSession).toHaveBeenCalledWith("session-existing");
  6052. expect(app.interaction.current()).toBeDefined();
  6053. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  6054. expect(app.tui.render(100).join("\n")).toContain("MCode status");
  6055. expect(runtime.renameSession).toHaveBeenCalledWith(
  6056. "session-existing",
  6057. "Renamed session",
  6058. );
  6059. expect(runtime.createSession).not.toHaveBeenCalled();
  6060. expect(app.transcript.snapshot()).not.toEqual(
  6061. expect.arrayContaining([
  6062. expect.objectContaining({ content: "Unknown command. Use /help." }),
  6063. ]),
  6064. );
  6065. app.interaction.current()?.handleInput?.("\x1b");
  6066. await app.stop();
  6067. });
  6068. it.each(["regular", "fullscreen"] as const)(
  6069. "presents /history in %s mode and returns to chat on cancel",
  6070. async (tuiMode) => {
  6071. const terminal = new FakeTerminal();
  6072. const runtime = createRuntime();
  6073. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6074. {
  6075. userMessageId: "msg-user-history",
  6076. assistantMessageId: "msg-assistant-history",
  6077. contentHead: "Inspect the Session UI",
  6078. timestamp: 1_700_000_000_000,
  6079. fileChangeCount: 1,
  6080. },
  6081. ]);
  6082. const app = createTuiApp({
  6083. runtime,
  6084. terminal,
  6085. version: "0.1.0",
  6086. workspaceDir: "/workspace",
  6087. tuiMode,
  6088. });
  6089. app.start();
  6090. await app.ready;
  6091. await app.submit("Seed the session");
  6092. await app.submit("/history");
  6093. await vi.waitFor(() =>
  6094. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6095. kind: "feature",
  6096. id: "session-history:explorer",
  6097. }),
  6098. );
  6099. expect(renderTerminalViewport(app, terminal)).toContain(
  6100. "Inspect the Session UI",
  6101. );
  6102. expect(renderTerminalViewport(app, terminal)).toContain("Search:");
  6103. expect(renderTerminalViewport(app, terminal)).toContain("Enter actions");
  6104. terminal.input?.("\u001b");
  6105. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6106. kind: "chat",
  6107. id: "chat",
  6108. });
  6109. await app.stop();
  6110. },
  6111. );
  6112. it("forks with the assistant boundary and starts a new operation after a terminal failure", async () => {
  6113. const terminal = new FakeTerminal();
  6114. const runtime = createRuntime();
  6115. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6116. {
  6117. userMessageId: "msg-user-1",
  6118. assistantMessageId: "msg-assistant-1",
  6119. contentHead: "Investigate flaky login tests",
  6120. timestamp: 1_700_000_000_000,
  6121. fileChangeCount: 2,
  6122. },
  6123. {
  6124. userMessageId: "msg-user-2",
  6125. assistantMessageId: "msg-assistant-2",
  6126. contentHead: "Draft a new CLI handler",
  6127. timestamp: 1_699_999_000_000,
  6128. fileChangeCount: 0,
  6129. },
  6130. ]);
  6131. vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
  6132. canFork: true,
  6133. worktreeVisible: false,
  6134. worktreeEligible: false,
  6135. });
  6136. vi.mocked(runtime.forkSession).mockRejectedValueOnce(
  6137. Object.assign(new Error("persisted fork recovery failed"), {
  6138. key: "FORK_RECOVERY_FAILED",
  6139. }),
  6140. );
  6141. const app = createTuiApp({
  6142. runtime,
  6143. terminal,
  6144. version: "0.1.0",
  6145. workspaceDir: "/workspace",
  6146. });
  6147. app.start();
  6148. await app.ready;
  6149. // Submit a message so the controller has an active session id.
  6150. await app.submit("Seed the session");
  6151. await vi.waitFor(() =>
  6152. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6153. );
  6154. const sourceSessionId = app.controller.snapshot().session?.sessionId;
  6155. expect(sourceSessionId).toBe("session-1");
  6156. const transcriptBefore = app.transcript.snapshot();
  6157. vi.mocked(runtime.createSession).mockClear();
  6158. vi.mocked(runtime.forkSession).mockClear();
  6159. vi.mocked(runtime.getSessionForkOptions).mockClear();
  6160. vi.mocked(runtime.listSessionInputSummaries).mockClear();
  6161. await app.submit("/fork");
  6162. // 1. /fork loads input summaries, not the generic transcript.
  6163. await vi.waitFor(() =>
  6164. expect(runtime.listSessionInputSummaries).toHaveBeenCalledWith(
  6165. sourceSessionId,
  6166. {
  6167. limit: 100,
  6168. },
  6169. ),
  6170. );
  6171. expect(renderTerminalViewport(app, terminal)).toContain(
  6172. "Fork from a previous message",
  6173. );
  6174. expect(renderTerminalViewport(app, terminal)).not.toContain("Transcript");
  6175. // 2. The newest summary (last entry) is selected by default; confirm with Enter.
  6176. await vi.waitFor(() =>
  6177. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6178. kind: "feature",
  6179. id: "session-mutation:history",
  6180. }),
  6181. );
  6182. terminal.input?.("\r");
  6183. // The history selection only fetches options; it must not mutate yet.
  6184. await vi.waitFor(() =>
  6185. expect(runtime.getSessionForkOptions).toHaveBeenCalledWith(
  6186. sourceSessionId,
  6187. "msg-assistant-2",
  6188. ),
  6189. );
  6190. await vi.waitFor(() =>
  6191. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6192. kind: "feature",
  6193. id: "session-mutation:fork-confirm",
  6194. }),
  6195. );
  6196. expect(runtime.forkSession).not.toHaveBeenCalled();
  6197. expect(renderTerminalViewport(app, terminal)).toContain("Confirm fork");
  6198. // 3. Explicit confirmation performs the mutation.
  6199. terminal.input?.("\r");
  6200. await vi.waitFor(() =>
  6201. expect(runtime.forkSession).toHaveBeenCalledWith(
  6202. expect.objectContaining({
  6203. sessionId: sourceSessionId,
  6204. assistantMessageId: "msg-assistant-2",
  6205. useSuggestedTitle: true,
  6206. createIsolatedWorktree: false,
  6207. }),
  6208. ),
  6209. );
  6210. await vi.waitFor(() =>
  6211. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6212. kind: "feature",
  6213. id: "session-mutation:fork-confirm",
  6214. }),
  6215. );
  6216. terminal.input?.("\r");
  6217. await vi.waitFor(() =>
  6218. expect(runtime.forkSession).toHaveBeenCalledTimes(2),
  6219. );
  6220. const forkCalls = vi.mocked(runtime.forkSession).mock.calls;
  6221. const operationIds = forkCalls.map(([input]) => input.clientRequestId);
  6222. expect(operationIds[0]).toBeTruthy();
  6223. expect(operationIds[1]).toBeTruthy();
  6224. expect(operationIds[0]).not.toBe(operationIds[1]);
  6225. // 5. Activation moves the controller to the child session id.
  6226. await vi.waitFor(() =>
  6227. expect(app.controller.snapshot().session?.sessionId).toBe("session-fork"),
  6228. );
  6229. expect(runtime.createSession).not.toHaveBeenCalled();
  6230. // The user message that seeded the source session was already projected
  6231. // into the transcript before the fork ran; the fork flow must not write
  6232. // any new user-typed cell while the picker is open or the mutation runs.
  6233. expect(
  6234. transcriptBefore.filter((cell) => cell.kind === "user").length,
  6235. ).toBeGreaterThan(0);
  6236. });
  6237. it("does not call forkSession when /fork is cancelled, unavailable, or fails", async () => {
  6238. const scenarios: ReadonlyArray<{
  6239. readonly label: string;
  6240. readonly setup: (runtime: ReturnType<typeof createRuntime>) => void;
  6241. readonly interact: (terminal: FakeTerminal) => void | Promise<void>;
  6242. /** When true, expect forkSession to have been called exactly once. */
  6243. readonly expectForkCall: boolean;
  6244. readonly confirmAfterSelection?: boolean;
  6245. }> = [
  6246. {
  6247. label: "esc cancels the picker without invoking fork",
  6248. setup: (runtime) => {
  6249. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6250. {
  6251. userMessageId: "msg-user-1",
  6252. assistantMessageId: "msg-assistant-1",
  6253. contentHead: "Investigate flaky login tests",
  6254. timestamp: 1_700_000_000_000,
  6255. fileChangeCount: 0,
  6256. },
  6257. ]);
  6258. },
  6259. interact: (terminal) => {
  6260. terminal.input?.("\u001b");
  6261. },
  6262. expectForkCall: false,
  6263. },
  6264. {
  6265. label: "unavailable fork surfaces a warning without invoking fork",
  6266. setup: (runtime) => {
  6267. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6268. {
  6269. userMessageId: "msg-user-1",
  6270. assistantMessageId: "msg-assistant-1",
  6271. contentHead: "Investigate flaky login tests",
  6272. timestamp: 1_700_000_000_000,
  6273. fileChangeCount: 0,
  6274. },
  6275. ]);
  6276. vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
  6277. canFork: false,
  6278. unavailableReason: "No persisted user prompts yet.",
  6279. worktreeVisible: false,
  6280. worktreeEligible: false,
  6281. });
  6282. },
  6283. interact: (terminal) => {
  6284. terminal.input?.("\r");
  6285. },
  6286. expectForkCall: false,
  6287. },
  6288. {
  6289. label:
  6290. "forkSession failure preserves the source session and transcript",
  6291. setup: (runtime) => {
  6292. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6293. {
  6294. userMessageId: "msg-user-1",
  6295. assistantMessageId: "msg-assistant-1",
  6296. contentHead: "Investigate flaky login tests",
  6297. timestamp: 1_700_000_000_000,
  6298. fileChangeCount: 0,
  6299. },
  6300. ]);
  6301. vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
  6302. canFork: true,
  6303. worktreeVisible: false,
  6304. worktreeEligible: false,
  6305. });
  6306. vi.mocked(runtime.forkSession).mockRejectedValue(
  6307. new Error("Runtime offline."),
  6308. );
  6309. },
  6310. interact: (terminal) => {
  6311. terminal.input?.("\r");
  6312. },
  6313. expectForkCall: true,
  6314. confirmAfterSelection: true,
  6315. },
  6316. ];
  6317. for (const scenario of scenarios) {
  6318. const terminal = new FakeTerminal();
  6319. const runtime = createRuntime();
  6320. scenario.setup(runtime);
  6321. const app = createTuiApp({
  6322. runtime,
  6323. terminal,
  6324. version: "0.1.0",
  6325. workspaceDir: "/workspace",
  6326. });
  6327. app.start();
  6328. await app.ready;
  6329. await app.submit("Seed the session");
  6330. await vi.waitFor(() =>
  6331. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6332. );
  6333. const sourceSessionId = app.controller.snapshot().session?.sessionId;
  6334. const transcriptBefore = app.transcript.snapshot();
  6335. await app.submit("/fork");
  6336. await vi.waitFor(() =>
  6337. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6338. kind: "feature",
  6339. id: "session-mutation:history",
  6340. }),
  6341. );
  6342. await scenario.interact(terminal);
  6343. if (scenario.expectForkCall || scenario.label.includes("unavailable")) {
  6344. await vi.waitFor(() =>
  6345. expect(runtime.getSessionForkOptions).toHaveBeenCalled(),
  6346. );
  6347. }
  6348. expect(runtime.forkSession).not.toHaveBeenCalled();
  6349. if (scenario.confirmAfterSelection) {
  6350. terminal.input?.("\r");
  6351. }
  6352. // Give the async fork pipeline a chance to settle.
  6353. await new Promise((resolve) => setTimeout(resolve, 40));
  6354. if (scenario.expectForkCall) {
  6355. expect(
  6356. vi.mocked(runtime.forkSession).mock.calls.length,
  6357. `${scenario.label} should call forkSession once`,
  6358. ).toBe(1);
  6359. } else {
  6360. expect(
  6361. vi.mocked(runtime.forkSession).mock.calls.length,
  6362. `${scenario.label} should not call forkSession`,
  6363. ).toBe(0);
  6364. }
  6365. expect(
  6366. app.controller.snapshot().session?.sessionId,
  6367. `${scenario.label} must not switch sessions`,
  6368. ).toBe(sourceSessionId);
  6369. expect(
  6370. app.transcript.snapshot().filter((cell) => cell.kind === "user").length,
  6371. `${scenario.label} must preserve the source transcript`,
  6372. ).toBe(transcriptBefore.filter((cell) => cell.kind === "user").length);
  6373. await app.stop();
  6374. }
  6375. });
  6376. it("does not call forkSession when the source session changes between summary and selection", async () => {
  6377. const terminal = new FakeTerminal();
  6378. const runtime = createRuntime();
  6379. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6380. {
  6381. userMessageId: "msg-user-1",
  6382. assistantMessageId: "msg-assistant-1",
  6383. contentHead: "Investigate flaky login tests",
  6384. timestamp: 1_700_000_000_000,
  6385. fileChangeCount: 0,
  6386. },
  6387. ]);
  6388. vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
  6389. canFork: true,
  6390. worktreeVisible: false,
  6391. worktreeEligible: false,
  6392. });
  6393. const app = createTuiApp({
  6394. runtime,
  6395. terminal,
  6396. version: "0.1.0",
  6397. workspaceDir: "/workspace",
  6398. });
  6399. app.start();
  6400. await app.ready;
  6401. await app.submit("Seed the session");
  6402. await vi.waitFor(() =>
  6403. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6404. );
  6405. await app.submit("/fork");
  6406. await vi.waitFor(() =>
  6407. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6408. kind: "feature",
  6409. id: "session-mutation:history",
  6410. }),
  6411. );
  6412. // Simulate the source session changing while the picker is open.
  6413. const otherSession = {
  6414. sessionId: "session-other",
  6415. title: "Other session",
  6416. workspaceDir: "/workspace",
  6417. };
  6418. vi.mocked(runtime.listSessions).mockResolvedValue([otherSession]);
  6419. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  6420. sessionId === otherSession.sessionId
  6421. ? otherSession
  6422. : { sessionId, workspaceDir: "/workspace" },
  6423. );
  6424. await app.openSession(otherSession.sessionId);
  6425. expect(app.controller.snapshot().session?.sessionId).toBe(
  6426. otherSession.sessionId,
  6427. );
  6428. // Confirming the picker now must not call forkSession.
  6429. terminal.input?.("\r");
  6430. await new Promise((resolve) => setTimeout(resolve, 20));
  6431. expect(vi.mocked(runtime.forkSession)).not.toHaveBeenCalled();
  6432. expect(vi.mocked(runtime.getSessionForkOptions).mock.calls.length).toBe(0);
  6433. });
  6434. it("preserves the /fork command draft and skips mutation when a turn is running", async () => {
  6435. const terminal = new FakeTerminal();
  6436. const runtime = createRuntime();
  6437. let finishTurn: (() => void) | undefined;
  6438. vi.mocked(runtime.sendMessage).mockImplementation(
  6439. async function* sendMessage() {
  6440. await new Promise<void>((resolve) => {
  6441. finishTurn = resolve;
  6442. });
  6443. yield { type: "done" };
  6444. },
  6445. );
  6446. const app = createTuiApp({
  6447. runtime,
  6448. terminal,
  6449. version: "0.1.0",
  6450. workspaceDir: "/workspace",
  6451. });
  6452. app.start();
  6453. await app.ready;
  6454. const submission = app.submit("Seed the session");
  6455. await vi.waitFor(() =>
  6456. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6457. );
  6458. await vi.waitFor(() =>
  6459. expect(vi.mocked(runtime.sendMessage)).toHaveBeenCalled(),
  6460. );
  6461. const summariesBefore = vi.mocked(runtime.listSessionInputSummaries).mock
  6462. .calls.length;
  6463. const forkOptionsBefore = vi.mocked(runtime.getSessionForkOptions).mock
  6464. .calls.length;
  6465. const forkBefore = vi.mocked(runtime.forkSession).mock.calls.length;
  6466. // While the turn is still running, /fork should preserve the draft and
  6467. // skip every runtime mutation method.
  6468. app.editor.setText("/fork");
  6469. await app.submit("/fork");
  6470. expect(app.editor.getText()).toBe("/fork");
  6471. expect(vi.mocked(runtime.listSessionInputSummaries).mock.calls.length).toBe(
  6472. summariesBefore,
  6473. );
  6474. expect(vi.mocked(runtime.getSessionForkOptions).mock.calls.length).toBe(
  6475. forkOptionsBefore,
  6476. );
  6477. expect(vi.mocked(runtime.forkSession).mock.calls.length).toBe(forkBefore);
  6478. // The fork surface should not have been pushed either.
  6479. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6480. kind: "chat",
  6481. id: "chat",
  6482. });
  6483. finishTurn?.();
  6484. await submission;
  6485. await app.stop();
  6486. });
  6487. it.each([
  6488. ["conversation", []],
  6489. ["conversation_and_files", ["\u001b[B"]],
  6490. ] as const)(
  6491. "runs /rewind with explicit %s scope and stable operation id",
  6492. async (scope, navigation) => {
  6493. const terminal = new FakeTerminal();
  6494. const runtime = createRuntime();
  6495. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6496. {
  6497. userMessageId: "msg-user-rewind",
  6498. contentHead: "Undo this point",
  6499. timestamp: 1_700_000_000_000,
  6500. fileChangeCount: 2,
  6501. },
  6502. ]);
  6503. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  6504. turns: [
  6505. {
  6506. turnId: "turn-1",
  6507. files: [
  6508. { filePath: "src/ready.ts", action: "modified", skipped: false },
  6509. { filePath: "src/skipped.ts", action: "deleted", skipped: true },
  6510. ],
  6511. },
  6512. ],
  6513. });
  6514. vi.mocked(runtime.rewindSession).mockResolvedValue(
  6515. scope === "conversation"
  6516. ? { rewound: true }
  6517. : {
  6518. rewound: true,
  6519. turnDiffRewind: {
  6520. status: "rewound",
  6521. revertedTurnIds: ["turn-1"],
  6522. },
  6523. },
  6524. );
  6525. const app = createTuiApp({
  6526. runtime,
  6527. terminal,
  6528. version: "0.1.0",
  6529. workspaceDir: "/workspace",
  6530. });
  6531. app.start();
  6532. await app.ready;
  6533. await app.submit("Seed rewind session");
  6534. await vi.waitFor(() =>
  6535. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6536. );
  6537. expect(
  6538. app.transcript.snapshot().some((cell) => cell.kind === "turn-duration"),
  6539. ).toBe(true);
  6540. vi.mocked(runtime.getMessages).mockResolvedValue([]);
  6541. await app.submit("/rewind");
  6542. await vi.waitFor(() =>
  6543. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6544. kind: "feature",
  6545. id: "session-mutation:history",
  6546. }),
  6547. );
  6548. terminal.input?.("\r");
  6549. await vi.waitFor(() =>
  6550. expect(runtime.getSessionRewindPreview).toHaveBeenCalledWith({
  6551. sessionId: "session-1",
  6552. userMessageId: "msg-user-rewind",
  6553. }),
  6554. );
  6555. await vi.waitFor(() =>
  6556. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6557. kind: "feature",
  6558. id: "session-mutation:rewind-preview",
  6559. }),
  6560. );
  6561. expect(renderTerminalViewport(app, terminal)).toContain("src/ready.ts");
  6562. expect(renderTerminalViewport(app, terminal)).toContain("src/skipped.ts");
  6563. terminal.input?.("\r");
  6564. await vi.waitFor(() =>
  6565. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6566. kind: "feature",
  6567. id: "session-mutation:scope",
  6568. }),
  6569. );
  6570. for (const key of navigation) terminal.input?.(key);
  6571. terminal.input?.("\r");
  6572. await vi.waitFor(() =>
  6573. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6574. kind: "feature",
  6575. id: "session-mutation:rewind-confirm",
  6576. }),
  6577. );
  6578. expect(runtime.rewindSession).not.toHaveBeenCalled();
  6579. terminal.input?.("\r");
  6580. await vi.waitFor(() =>
  6581. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  6582. );
  6583. const input = vi.mocked(runtime.rewindSession).mock.calls[0]?.[0];
  6584. expect(input).toEqual({
  6585. sessionId: "session-1",
  6586. userMessageId: "msg-user-rewind",
  6587. clientRequestId: expect.stringMatching(/^tui-rewind_/),
  6588. ...(scope === "conversation_and_files" ? { rewindTurnDiff: true } : {}),
  6589. });
  6590. expect(input?.clientRequestId).toMatch(/^tui-rewind_/);
  6591. await vi.waitFor(() => expect(runtime.getMessages).toHaveBeenCalled());
  6592. await vi.waitFor(() =>
  6593. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6594. kind: "chat",
  6595. id: "chat",
  6596. }),
  6597. );
  6598. expect(
  6599. app.transcript
  6600. .snapshot()
  6601. .some((cell) => cell.content === "Rewind completed."),
  6602. ).toBe(false);
  6603. expect(app.transcript.snapshot()).toEqual([]);
  6604. await app.stop();
  6605. },
  6606. );
  6607. it("edits only the latest user turn, hides that turn while editing, and adds no completion cell", async () => {
  6608. const terminal = new FakeTerminal();
  6609. const runtime = createRuntime();
  6610. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6611. {
  6612. userMessageId: "msg-user-older",
  6613. assistantMessageId: "msg-assistant-older",
  6614. contentHead: "Older prompt",
  6615. timestamp: 1,
  6616. fileChangeCount: 0,
  6617. },
  6618. {
  6619. userMessageId: "msg-user-latest",
  6620. assistantMessageId: "msg-assistant-latest",
  6621. contentHead: "Latest prompt",
  6622. timestamp: 2,
  6623. fileChangeCount: 0,
  6624. },
  6625. ]);
  6626. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  6627. messages: [
  6628. {
  6629. id: "msg-user-older",
  6630. role: "user",
  6631. content: "Older prompt",
  6632. timestamp: 1,
  6633. },
  6634. {
  6635. id: "msg-user-latest",
  6636. role: "user",
  6637. content: "Latest prompt",
  6638. timestamp: 2,
  6639. },
  6640. ],
  6641. hasMore: false,
  6642. });
  6643. const app = createTuiApp({
  6644. runtime,
  6645. terminal,
  6646. version: "0.1.0",
  6647. workspaceDir: "/workspace",
  6648. });
  6649. app.start();
  6650. await app.ready;
  6651. await app.submit("Seed edit session");
  6652. await vi.waitFor(() =>
  6653. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6654. );
  6655. app.transcript.upsert({
  6656. id: "older-user-cell",
  6657. kind: "user",
  6658. status: "succeeded",
  6659. content: "Older prompt",
  6660. sourceMessageId: "msg-user-older",
  6661. turnId: "turn-older",
  6662. createdAtMs: 1,
  6663. });
  6664. app.transcript.upsert({
  6665. id: "latest-user-cell",
  6666. kind: "user",
  6667. status: "succeeded",
  6668. content: "Latest prompt",
  6669. sourceMessageId: "msg-user-latest",
  6670. turnId: "turn-latest",
  6671. createdAtMs: 2,
  6672. });
  6673. app.transcript.upsert({
  6674. id: "latest-assistant-cell",
  6675. kind: "assistant",
  6676. status: "succeeded",
  6677. content: "Latest response",
  6678. sourceMessageId: "msg-assistant-latest",
  6679. turnId: "turn-latest",
  6680. createdAtMs: 3,
  6681. });
  6682. await app.submit("/edit");
  6683. await vi.waitFor(() =>
  6684. expect(app.editor.getExpandedText()).toBe("Latest prompt"),
  6685. );
  6686. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6687. kind: "chat",
  6688. id: "chat",
  6689. });
  6690. const editingFrame = app.tui.render(100).join("\n");
  6691. expect(editingFrame).toContain("Older prompt");
  6692. expect(editingFrame).not.toContain("Latest response");
  6693. const historyRefreshCount = vi.mocked(runtime.getMessages).mock.calls
  6694. .length;
  6695. app.editor.setText("Edited latest prompt");
  6696. app.editor.handleInput("\r");
  6697. await vi.waitFor(() =>
  6698. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  6699. );
  6700. await vi.waitFor(() =>
  6701. expect(vi.mocked(runtime.getMessages).mock.calls.length).toBeGreaterThan(
  6702. historyRefreshCount,
  6703. ),
  6704. );
  6705. expect(
  6706. app.transcript
  6707. .snapshot()
  6708. .some(
  6709. (cell) =>
  6710. cell.content ===
  6711. "Edited message submitted; regenerating from this point.",
  6712. ),
  6713. ).toBe(false);
  6714. expect(runtime.editSessionMessage).toHaveBeenCalledWith(
  6715. expect.objectContaining({
  6716. userMessageId: "msg-user-latest",
  6717. content: "Edited latest prompt",
  6718. }),
  6719. );
  6720. await app.stop();
  6721. });
  6722. it("restores the hidden latest turn when Edit is cancelled", async () => {
  6723. const terminal = new FakeTerminal();
  6724. const runtime = createRuntime();
  6725. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6726. {
  6727. userMessageId: "msg-user-latest",
  6728. assistantMessageId: "msg-assistant-latest",
  6729. contentHead: "Latest prompt",
  6730. timestamp: 2,
  6731. fileChangeCount: 0,
  6732. },
  6733. ]);
  6734. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  6735. messages: [
  6736. {
  6737. id: "msg-user-latest",
  6738. role: "user",
  6739. content: "Latest prompt",
  6740. timestamp: 2,
  6741. },
  6742. ],
  6743. hasMore: false,
  6744. });
  6745. const app = createTuiApp({
  6746. runtime,
  6747. terminal,
  6748. version: "0.1.0",
  6749. workspaceDir: "/workspace",
  6750. });
  6751. app.start();
  6752. await app.ready;
  6753. await app.submit("Seed edit session");
  6754. app.transcript.upsert({
  6755. id: "latest-user-cell",
  6756. kind: "user",
  6757. status: "succeeded",
  6758. content: "Latest prompt",
  6759. sourceMessageId: "msg-user-latest",
  6760. turnId: "turn-latest",
  6761. createdAtMs: 2,
  6762. });
  6763. app.transcript.upsert({
  6764. id: "latest-assistant-cell",
  6765. kind: "assistant",
  6766. status: "succeeded",
  6767. content: "Latest response restored on cancel",
  6768. sourceMessageId: "msg-assistant-latest",
  6769. turnId: "turn-latest",
  6770. createdAtMs: 3,
  6771. });
  6772. await app.submit("/edit");
  6773. await vi.waitFor(() =>
  6774. expect(app.editor.getExpandedText()).toBe("Latest prompt"),
  6775. );
  6776. expect(app.tui.render(100).join("\n")).not.toContain(
  6777. "Latest response restored on cancel",
  6778. );
  6779. terminal.input?.("\u001b");
  6780. await vi.waitFor(() => expect(app.editor.getExpandedText()).toBe(""));
  6781. expect(app.tui.render(100).join("\n")).toContain(
  6782. "Latest response restored on cancel",
  6783. );
  6784. expect(runtime.editSessionMessage).not.toHaveBeenCalled();
  6785. await app.stop();
  6786. });
  6787. it.each([
  6788. { reference: "filePath", action: "cancel" },
  6789. { reference: "assetId", action: "send" },
  6790. { reference: "assetId", action: "delete" },
  6791. { reference: "filePath", action: "undo" },
  6792. { reference: "assetId", action: "add" },
  6793. { reference: "filePath", action: "clear-restore" },
  6794. { reference: "filePath", action: "cached" },
  6795. ] as const)(
  6796. "restores editable image chips after double Escape and retry ($reference / $action)",
  6797. async ({ reference, action }) => {
  6798. const terminal = new FakeTerminal();
  6799. const runtime = createRuntime();
  6800. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6801. {
  6802. userMessageId: "msg-user-latest",
  6803. assistantMessageId: "msg-assistant-latest",
  6804. contentHead: "Latest prompt from shortcut",
  6805. timestamp: 2,
  6806. fileChangeCount: 0,
  6807. },
  6808. ]);
  6809. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  6810. messages: [
  6811. {
  6812. id: "msg-user-latest",
  6813. role: "user",
  6814. content: "Latest prompt from shortcut",
  6815. attachments: [
  6816. {
  6817. type: "image",
  6818. fileName: "edit-reference.png",
  6819. mimeType: "image/png",
  6820. [reference]:
  6821. reference === "filePath"
  6822. ? "/workspace/edit-reference.png"
  6823. : "asset-edit-image",
  6824. },
  6825. ],
  6826. timestamp: 2,
  6827. },
  6828. ],
  6829. hasMore: false,
  6830. });
  6831. const app = createTuiApp({
  6832. runtime,
  6833. terminal,
  6834. version: "0.1.0",
  6835. workspaceDir: "/workspace",
  6836. resolveAttachment: async (path) => ({
  6837. type: "image",
  6838. filePath: path,
  6839. fileName: path.endsWith("new.png") ? "new.png" : "edit-reference.png",
  6840. mimeType: "image/png",
  6841. sizeBytes: 123,
  6842. }),
  6843. });
  6844. app.start();
  6845. await app.ready;
  6846. let restoredText = "Latest prompt from shortcut [Image #1] ";
  6847. if (action === "cached") {
  6848. terminal.input?.("\x1b[200~/workspace/edit-reference.png\x1b[201~");
  6849. await vi.waitFor(() =>
  6850. expect(app.editor.getText()).toContain("[Image #1]"),
  6851. );
  6852. app.editor.handleInput("Latest prompt from shortcut");
  6853. restoredText = app.editor.getText();
  6854. app.editor.handleInput("\r");
  6855. await vi.waitFor(() =>
  6856. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  6857. );
  6858. await vi.waitFor(() =>
  6859. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  6860. );
  6861. } else {
  6862. await app.submit("Seed edit session");
  6863. }
  6864. terminal.input?.("\u001b");
  6865. terminal.input?.("\u001b");
  6866. await vi.waitFor(() =>
  6867. expect(app.editor.getExpandedText()).toBe(restoredText),
  6868. );
  6869. expect(runtime.listSessionInputSummaries).toHaveBeenCalledWith(
  6870. "session-1",
  6871. { limit: 100 },
  6872. );
  6873. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6874. kind: "chat",
  6875. id: "chat",
  6876. });
  6877. expect(stripAnsi(app.tui.render(100).join("\n"))).toContain("[Image #1]");
  6878. vi.mocked(runtime.editSessionMessage).mockRejectedValueOnce(
  6879. new Error("Temporary failure"),
  6880. );
  6881. app.editor.handleInput("\r");
  6882. await vi.waitFor(() =>
  6883. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  6884. );
  6885. await vi.waitFor(() =>
  6886. expect(app.editor.getExpandedText()).toBe(restoredText),
  6887. );
  6888. expect(stripAnsi(app.tui.render(100).join("\n"))).toContain("[Image #1]");
  6889. expect(runtime.editSessionMessage).toHaveBeenCalledWith(
  6890. expect.objectContaining({
  6891. content: "Latest prompt from shortcut",
  6892. attachments: [
  6893. expect.objectContaining({
  6894. fileName: "edit-reference.png",
  6895. [reference]:
  6896. reference === "filePath"
  6897. ? "/workspace/edit-reference.png"
  6898. : "asset-edit-image",
  6899. }),
  6900. ],
  6901. }),
  6902. );
  6903. if (action === "delete" || action === "undo") {
  6904. app.editor.handleInput("\x05");
  6905. app.editor.handleInput("\x7f");
  6906. await vi.waitFor(() =>
  6907. expect(app.editor.getText()).not.toContain("[Image #1]"),
  6908. );
  6909. if (action === "undo") {
  6910. app.editor.handleInput("\x1f");
  6911. expect(app.editor.getText()).toContain("[Image #1]");
  6912. }
  6913. }
  6914. if (action === "add") {
  6915. terminal.input?.("\x1b[200~/workspace/new.png\x1b[201~");
  6916. await vi.waitFor(() =>
  6917. expect(app.editor.getText()).toContain("[Image #2]"),
  6918. );
  6919. expect(app.editor.captureDraft().attachmentPlaceholders).toHaveLength(
  6920. 2,
  6921. );
  6922. }
  6923. if (action === "clear-restore") {
  6924. terminal.input?.("\x03");
  6925. expect(app.editor.getText()).toBe("");
  6926. terminal.input?.("\x1f");
  6927. expect(app.editor.getText()).toContain("[Image #1]");
  6928. }
  6929. if (action === "cancel") {
  6930. terminal.input?.("\u001b");
  6931. } else {
  6932. app.editor.handleInput("\r");
  6933. await vi.waitFor(() =>
  6934. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(2),
  6935. );
  6936. const sent = vi.mocked(runtime.editSessionMessage).mock.calls[1]?.[0];
  6937. expect(sent?.content).toBe("Latest prompt from shortcut");
  6938. expect(sent?.attachments ?? []).toHaveLength(
  6939. action === "delete" ? 0 : action === "add" ? 2 : 1,
  6940. );
  6941. if (action !== "delete")
  6942. expect(sent?.attachments?.[0]?.fileName).toBe("edit-reference.png");
  6943. }
  6944. await vi.waitFor(() =>
  6945. expect(stripAnsi(app.tui.render(100).join("\n"))).not.toContain(
  6946. "[Image #1]",
  6947. ),
  6948. );
  6949. await app.stop();
  6950. },
  6951. );
  6952. it("edits the latest committed user turn through the desktop-aligned mutation contract", async () => {
  6953. const terminal = new FakeTerminal();
  6954. const runtime = createRuntime();
  6955. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6956. {
  6957. userMessageId: "msg-user-v1-target",
  6958. assistantMessageId: "msg-assistant-v1-target",
  6959. contentHead: "Original prompt head",
  6960. timestamp: 1_700_000_000_000,
  6961. fileChangeCount: 1,
  6962. },
  6963. ]);
  6964. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  6965. messages: [
  6966. {
  6967. id: "msg-user-v1-target",
  6968. role: "user",
  6969. content: "Original complete prompt",
  6970. attachments: [
  6971. {
  6972. type: "file",
  6973. fileName: "spec.md",
  6974. mimeType: "text/markdown",
  6975. sizeBytes: 42,
  6976. filePath: "/workspace/spec.md",
  6977. },
  6978. ],
  6979. timestamp: 1_700_000_000_000,
  6980. },
  6981. ],
  6982. hasMore: false,
  6983. });
  6984. const app = createTuiApp({
  6985. runtime,
  6986. terminal,
  6987. version: "0.1.0",
  6988. workspaceDir: "/workspace",
  6989. });
  6990. app.start();
  6991. await app.ready;
  6992. await app.submit("Seed edit session");
  6993. await vi.waitFor(() =>
  6994. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6995. );
  6996. await app.submit("/edit");
  6997. await vi.waitFor(() =>
  6998. expect(app.editor.getExpandedText()).toBe(
  6999. "Original complete prompt [File #1] ",
  7000. ),
  7001. );
  7002. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7003. kind: "chat",
  7004. id: "chat",
  7005. });
  7006. app.editor.setText("Updated prompt");
  7007. app.editor.handleInput("\r");
  7008. await vi.waitFor(() =>
  7009. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7010. );
  7011. expect(runtime.editSessionMessage).toHaveBeenCalledWith({
  7012. sessionId: "session-1",
  7013. userMessageId: "msg-user-v1-target",
  7014. clientRequestId: expect.stringMatching(/^tui-edit_/u),
  7015. content: "Updated prompt",
  7016. attachments: [
  7017. {
  7018. type: "file",
  7019. fileName: "spec.md",
  7020. mimeType: "text/markdown",
  7021. sizeBytes: 42,
  7022. filePath: "/workspace/spec.md",
  7023. },
  7024. ],
  7025. rewindTurnDiff: true,
  7026. });
  7027. await app.stop();
  7028. });
  7029. it("keeps hidden chat context out of the editor and restores it for Edit transport", async () => {
  7030. const terminal = new FakeTerminal();
  7031. const runtime = createRuntime();
  7032. const transportContent = [
  7033. "<user-provided-context>",
  7034. "Referenced context",
  7035. "</user-provided-context>",
  7036. "",
  7037. "Original visible prompt",
  7038. ].join("\n");
  7039. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7040. {
  7041. userMessageId: "msg-user-v1-context",
  7042. assistantMessageId: "msg-assistant-v1-context",
  7043. contentHead: "Original visible prompt",
  7044. timestamp: 1_700_000_000_000,
  7045. fileChangeCount: 0,
  7046. },
  7047. ]);
  7048. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7049. messages: [
  7050. {
  7051. id: "msg-user-v1-context",
  7052. role: "user",
  7053. content: transportContent,
  7054. timestamp: 1_700_000_000_000,
  7055. },
  7056. ],
  7057. hasMore: false,
  7058. });
  7059. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7060. const app = createTuiApp({
  7061. runtime,
  7062. terminal,
  7063. version: "0.1.0",
  7064. workspaceDir: "/workspace",
  7065. });
  7066. app.start();
  7067. await app.ready;
  7068. await app.submit("Seed edit session");
  7069. await app.submit("/edit");
  7070. await vi.waitFor(() =>
  7071. expect(app.editor.getExpandedText()).toBe("Original visible prompt"),
  7072. );
  7073. expect(app.editor.getExpandedText()).not.toContain("user-provided-context");
  7074. app.editor.setText("Updated visible prompt");
  7075. app.editor.handleInput("\r");
  7076. await vi.waitFor(() =>
  7077. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7078. );
  7079. expect(runtime.editSessionMessage).toHaveBeenCalledWith(
  7080. expect.objectContaining({
  7081. content: [
  7082. "<user-provided-context>",
  7083. "Referenced context",
  7084. "</user-provided-context>",
  7085. "",
  7086. "Updated visible prompt",
  7087. ].join("\n"),
  7088. }),
  7089. );
  7090. await app.stop();
  7091. });
  7092. it("preserves hidden context and attachments when Edit recovery requires a new message", async () => {
  7093. const terminal = new FakeTerminal();
  7094. const runtime = createRuntime();
  7095. const transportContent = [
  7096. "<mavis-chat-context>",
  7097. "Referenced context",
  7098. "</mavis-chat-context>",
  7099. "",
  7100. "Original visible prompt",
  7101. ].join("\n");
  7102. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7103. {
  7104. userMessageId: "msg-user-v1-recovery",
  7105. assistantMessageId: "msg-assistant-v1-recovery",
  7106. contentHead: "Original visible prompt",
  7107. timestamp: 1_700_000_000_000,
  7108. fileChangeCount: 0,
  7109. },
  7110. ]);
  7111. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7112. messages: [
  7113. {
  7114. id: "msg-user-v1-recovery",
  7115. role: "user",
  7116. content: transportContent,
  7117. attachments: [
  7118. {
  7119. type: "file",
  7120. fileName: "context.md",
  7121. mimeType: "text/markdown",
  7122. sizeBytes: 42,
  7123. assetId: "asset-context-md",
  7124. },
  7125. ],
  7126. timestamp: 1_700_000_000_000,
  7127. },
  7128. ],
  7129. hasMore: false,
  7130. });
  7131. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7132. vi.mocked(runtime.editSessionMessage).mockRejectedValueOnce(
  7133. Object.assign(new Error("history already rewound"), {
  7134. key: "EDIT_RESTART_NEEDS_RESUBMIT",
  7135. }),
  7136. );
  7137. const app = createTuiApp({
  7138. runtime,
  7139. terminal,
  7140. version: "0.1.0",
  7141. workspaceDir: "/workspace",
  7142. });
  7143. app.start();
  7144. await app.ready;
  7145. await app.submit("Seed edit session");
  7146. const sendCountBeforeEdit = vi.mocked(runtime.sendMessage).mock.calls
  7147. .length;
  7148. await app.submit("/edit");
  7149. await vi.waitFor(() =>
  7150. expect(app.editor.getExpandedText()).toBe(
  7151. "Original visible prompt [File #1] ",
  7152. ),
  7153. );
  7154. app.editor.setText("/help should remain message text");
  7155. app.editor.handleInput("\r");
  7156. await vi.waitFor(() =>
  7157. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7158. );
  7159. await vi.waitFor(() =>
  7160. expect(app.editor.getExpandedText()).toBe(
  7161. "/help should remain message text [File #1] ",
  7162. ),
  7163. );
  7164. expect(app.editor.getExpandedText()).not.toContain("mavis-chat-context");
  7165. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
  7166. let releaseAdmission!: () => void;
  7167. vi.mocked(runtime.getAccountStatus).mockImplementationOnce(
  7168. async () =>
  7169. await new Promise((resolve) => {
  7170. releaseAdmission = () =>
  7171. resolve({
  7172. status: "ready",
  7173. defaultModel: "minimax/MiniMax-M2.7",
  7174. providerId: "minimax",
  7175. modelId: "MiniMax-M2.7",
  7176. authMode: "managed-login",
  7177. managedTokenPresent: true,
  7178. warnings: [],
  7179. });
  7180. }),
  7181. );
  7182. app.editor.handleInput("\r");
  7183. await vi.waitFor(() =>
  7184. expect(app.controller.snapshot().activeTurnId).toBeDefined(),
  7185. );
  7186. terminal.input?.("\u001b");
  7187. releaseAdmission();
  7188. await vi.waitFor(() =>
  7189. expect(app.editor.getExpandedText()).toBe(
  7190. "/help should remain message text [File #1] ",
  7191. ),
  7192. );
  7193. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
  7194. app.editor.handleInput("\r");
  7195. await vi.waitFor(() =>
  7196. expect(runtime.sendMessage).toHaveBeenCalledTimes(
  7197. sendCountBeforeEdit + 1,
  7198. ),
  7199. );
  7200. expect(vi.mocked(runtime.sendMessage).mock.calls.at(-1)?.[0]).toMatchObject(
  7201. {
  7202. content: [
  7203. "<mavis-chat-context>",
  7204. "Referenced context",
  7205. "</mavis-chat-context>",
  7206. "",
  7207. "/help should remain message text",
  7208. ].join("\n"),
  7209. attachments: [
  7210. {
  7211. meta: {
  7212. attachmentType: "file",
  7213. fileName: "context.md",
  7214. mimeType: "text/markdown",
  7215. sizeBytes: 42,
  7216. },
  7217. local: { assetId: "asset-context-md" },
  7218. },
  7219. ],
  7220. },
  7221. );
  7222. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1);
  7223. expect(
  7224. app.transcript
  7225. .snapshot()
  7226. .filter((cell) => cell.kind === "user")
  7227. .map((cell) => cell.content)
  7228. .join("\n"),
  7229. ).toContain("/help should remain message text");
  7230. expect(
  7231. app.transcript
  7232. .snapshot()
  7233. .filter((cell) => cell.kind === "user")
  7234. .map((cell) => cell.content)
  7235. .join("\n"),
  7236. ).not.toContain("mavis-chat-context");
  7237. await app.stop();
  7238. });
  7239. it("allows an attachment-only committed message to enter Edit and gain a body", async () => {
  7240. const terminal = new FakeTerminal();
  7241. const runtime = createRuntime();
  7242. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7243. {
  7244. userMessageId: "msg-user-v1-attachment-only",
  7245. assistantMessageId: "msg-assistant-v1-attachment-only",
  7246. timestamp: 1_700_000_000_000,
  7247. fileChangeCount: 0,
  7248. },
  7249. ]);
  7250. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7251. messages: [
  7252. {
  7253. id: "msg-user-v1-attachment-only",
  7254. role: "user",
  7255. content: "",
  7256. attachments: [
  7257. {
  7258. type: "image",
  7259. fileName: "reference.png",
  7260. mimeType: "image/png",
  7261. filePath: "/workspace/reference.png",
  7262. },
  7263. ],
  7264. timestamp: 1_700_000_000_000,
  7265. },
  7266. ],
  7267. hasMore: false,
  7268. });
  7269. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7270. const app = createTuiApp({
  7271. runtime,
  7272. terminal,
  7273. version: "0.1.0",
  7274. workspaceDir: "/workspace",
  7275. });
  7276. app.start();
  7277. await app.ready;
  7278. await app.submit("Seed edit session");
  7279. const sendCountBeforeEdit = vi.mocked(runtime.sendMessage).mock.calls
  7280. .length;
  7281. await app.submit("/edit");
  7282. await vi.waitFor(() =>
  7283. expect(app.tui.render(100).join("\n")).toContain(
  7284. "Editing the selected message",
  7285. ),
  7286. );
  7287. expect(app.editor.getExpandedText()).toBe("[Image #1] ");
  7288. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7289. kind: "chat",
  7290. id: "chat",
  7291. });
  7292. app.editor.setText("Describe this reference");
  7293. app.editor.handleInput("\r");
  7294. await vi.waitFor(() =>
  7295. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7296. );
  7297. expect(runtime.editSessionMessage).toHaveBeenCalledWith({
  7298. sessionId: "session-1",
  7299. userMessageId: "msg-user-v1-attachment-only",
  7300. clientRequestId: expect.stringMatching(/^tui-edit_/u),
  7301. content: "Describe this reference",
  7302. attachments: [
  7303. {
  7304. type: "image",
  7305. fileName: "reference.png",
  7306. mimeType: "image/png",
  7307. filePath: "/workspace/reference.png",
  7308. },
  7309. ],
  7310. rewindTurnDiff: true,
  7311. });
  7312. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
  7313. await app.stop();
  7314. });
  7315. it("keeps a second composer submission while an edit request is still in flight", async () => {
  7316. const terminal = new FakeTerminal();
  7317. const runtime = createRuntime();
  7318. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7319. {
  7320. userMessageId: "msg-user-v1-target",
  7321. assistantMessageId: "msg-assistant-v1-target",
  7322. contentHead: "Original prompt",
  7323. timestamp: 1,
  7324. fileChangeCount: 0,
  7325. },
  7326. ]);
  7327. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7328. messages: [
  7329. {
  7330. id: "msg-user-v1-target",
  7331. role: "user",
  7332. content: "Original prompt",
  7333. timestamp: 1,
  7334. },
  7335. ],
  7336. hasMore: false,
  7337. });
  7338. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7339. let resolveEdit!: (value: {
  7340. rewound: boolean;
  7341. turnId: string;
  7342. userMessageId: string;
  7343. }) => void;
  7344. vi.mocked(runtime.editSessionMessage).mockImplementation(
  7345. () =>
  7346. new Promise((resolve) => {
  7347. resolveEdit = resolve;
  7348. }),
  7349. );
  7350. const app = createTuiApp({
  7351. runtime,
  7352. terminal,
  7353. version: "0.1.0",
  7354. workspaceDir: "/workspace",
  7355. });
  7356. app.start();
  7357. await app.ready;
  7358. await app.submit("Seed edit session");
  7359. const sendCountBeforeEdit = vi.mocked(runtime.sendMessage).mock.calls
  7360. .length;
  7361. await app.submit("/edit");
  7362. await vi.waitFor(() =>
  7363. expect(app.editor.getText()).toBe("Original prompt"),
  7364. );
  7365. app.editor.setText("First edited prompt");
  7366. app.editor.handleInput("\r");
  7367. await vi.waitFor(() =>
  7368. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7369. );
  7370. app.editor.setText("Keep this until edit settles");
  7371. app.editor.handleInput("\r");
  7372. await vi.waitFor(() =>
  7373. expect(app.editor.getText()).toBe("Keep this until edit settles"),
  7374. );
  7375. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
  7376. resolveEdit({
  7377. rewound: true,
  7378. turnId: "turn-edit-1",
  7379. userMessageId: "msg-user-v1-edited",
  7380. });
  7381. await app.stop();
  7382. });
  7383. it("preserves the edit and retries the same operation when submission fails after rewind", async () => {
  7384. const terminal = new FakeTerminal();
  7385. const runtime = createRuntime();
  7386. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7387. {
  7388. userMessageId: "msg-user-v1-target",
  7389. assistantMessageId: "msg-assistant-v1-target",
  7390. contentHead: "Original prompt",
  7391. timestamp: 1,
  7392. fileChangeCount: 0,
  7393. },
  7394. ]);
  7395. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7396. messages: [
  7397. {
  7398. id: "msg-user-v1-target",
  7399. role: "user",
  7400. content: "Original prompt",
  7401. timestamp: 1,
  7402. },
  7403. ],
  7404. hasMore: false,
  7405. });
  7406. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7407. vi.mocked(runtime.editSessionMessage)
  7408. .mockRejectedValueOnce(
  7409. Object.assign(new Error("submit failed"), {
  7410. key: "EDIT_SUBMIT_FAILED_AFTER_REWIND",
  7411. }),
  7412. )
  7413. .mockResolvedValueOnce({
  7414. rewound: true,
  7415. turnId: "turn-edit-retry",
  7416. userMessageId: "msg-user-v1-edited",
  7417. });
  7418. const app = createTuiApp({
  7419. runtime,
  7420. terminal,
  7421. version: "0.1.0",
  7422. workspaceDir: "/workspace",
  7423. });
  7424. app.start();
  7425. await app.ready;
  7426. await app.submit("Seed edit session");
  7427. await app.submit("/edit");
  7428. await vi.waitFor(() =>
  7429. expect(app.editor.getText()).toBe("Original prompt"),
  7430. );
  7431. app.editor.setText("Preserve this edited prompt");
  7432. app.editor.handleInput("\r");
  7433. await vi.waitFor(() =>
  7434. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7435. );
  7436. await vi.waitFor(() =>
  7437. expect(app.editor.getText()).toBe("Preserve this edited prompt"),
  7438. );
  7439. expect(
  7440. app.transcript
  7441. .snapshot()
  7442. .some((cell) => cell.content.includes("History was rewound")),
  7443. ).toBe(true);
  7444. const firstOperationId = vi.mocked(runtime.editSessionMessage).mock
  7445. .calls[0]?.[0].clientRequestId;
  7446. const sendCount = vi.mocked(runtime.sendMessage).mock.calls.length;
  7447. app.editor.handleInput("\r");
  7448. await vi.waitFor(() =>
  7449. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(2),
  7450. );
  7451. expect(runtime.editSessionMessage).toHaveBeenLastCalledWith(
  7452. expect.objectContaining({ clientRequestId: firstOperationId }),
  7453. );
  7454. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCount);
  7455. await app.stop();
  7456. });
  7457. it.each(['/rewind', '/fork'])(
  7458. 'clears the loading hint after %s history loads and stays clear after cancellation',
  7459. async (command) => {
  7460. const terminal = new FakeTerminal();
  7461. const runtime = createRuntime();
  7462. let resolveHistory!: (
  7463. value: Awaited<ReturnType<TuiRuntime['listSessionInputSummaries']>>,
  7464. ) => void;
  7465. vi.mocked(runtime.listSessionInputSummaries).mockImplementation(
  7466. () =>
  7467. new Promise((resolve) => {
  7468. resolveHistory = resolve;
  7469. }),
  7470. );
  7471. const app = createTuiApp({ runtime, terminal, version: '0.1.0', workspaceDir: '/workspace' });
  7472. app.start();
  7473. try {
  7474. await app.ready;
  7475. await app.submit('Seed session');
  7476. await app.submit(command);
  7477. const loadingChat = stripAnsi(app.tui.render(120).join('\n'));
  7478. expect(loadingChat).toMatch(/Loading|Finding/);
  7479. resolveHistory([{ userMessageId: 'history-user', timestamp: 1, fileChangeCount: 0 }]);
  7480. await vi.waitFor(() =>
  7481. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7482. kind: 'feature',
  7483. id: 'session-mutation:history',
  7484. }),
  7485. );
  7486. expect(stripAnsi(app.tui.render(120).join('\n'))).not.toMatch(
  7487. /Loading (?:rewind|fork) history|Finding messages/,
  7488. );
  7489. terminal.input?.('\x1b');
  7490. expect(app.surfaceHost.getActiveSurface()).toEqual({ kind: 'chat', id: 'chat' });
  7491. expect(stripAnsi(app.tui.render(120).join('\n'))).not.toMatch(
  7492. /Loading (?:rewind|fork) history|Finding messages/,
  7493. );
  7494. } finally {
  7495. await app.stop();
  7496. }
  7497. },
  7498. );
  7499. it("cancels /rewind preview and ignores duplicate scope submission", async () => {
  7500. const terminal = new FakeTerminal();
  7501. const runtime = createRuntime();
  7502. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7503. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7504. ]);
  7505. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7506. turns: [
  7507. {
  7508. turnId: "turn-1",
  7509. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7510. },
  7511. ],
  7512. });
  7513. let resolveRewind!: (value: { rewound: boolean }) => void;
  7514. vi.mocked(runtime.rewindSession).mockImplementation(
  7515. () =>
  7516. new Promise((resolve) => {
  7517. resolveRewind = resolve;
  7518. }),
  7519. );
  7520. const app = createTuiApp({
  7521. runtime,
  7522. terminal,
  7523. version: "0.1.0",
  7524. workspaceDir: "/workspace",
  7525. });
  7526. app.start();
  7527. await app.ready;
  7528. await app.submit("Seed rewind session");
  7529. await app.submit("/rewind");
  7530. await vi.waitFor(() =>
  7531. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7532. kind: "feature",
  7533. id: "session-mutation:history",
  7534. }),
  7535. );
  7536. terminal.input?.("\r");
  7537. await vi.waitFor(() =>
  7538. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7539. kind: "feature",
  7540. id: "session-mutation:rewind-preview",
  7541. }),
  7542. );
  7543. terminal.input?.("\u001b");
  7544. expect(runtime.rewindSession).not.toHaveBeenCalled();
  7545. await app.submit("/rewind");
  7546. await vi.waitFor(() =>
  7547. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7548. kind: "feature",
  7549. id: "session-mutation:history",
  7550. }),
  7551. );
  7552. terminal.input?.("\r");
  7553. await vi.waitFor(() =>
  7554. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7555. kind: "feature",
  7556. id: "session-mutation:rewind-preview",
  7557. }),
  7558. );
  7559. terminal.input?.("\r");
  7560. await vi.waitFor(() =>
  7561. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7562. kind: "feature",
  7563. id: "session-mutation:scope",
  7564. }),
  7565. );
  7566. terminal.input?.("\r");
  7567. await vi.waitFor(() =>
  7568. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7569. kind: "feature",
  7570. id: "session-mutation:rewind-confirm",
  7571. }),
  7572. );
  7573. terminal.input?.("\r");
  7574. await vi.waitFor(() =>
  7575. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  7576. );
  7577. terminal.input?.("\u001b");
  7578. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7579. kind: "feature",
  7580. id: "session-mutation:rewind-confirm",
  7581. });
  7582. resolveRewind({ rewound: true });
  7583. await vi.waitFor(() => expect(app.surfaceHost.getActiveSurface()).toEqual({ kind: 'chat', id: 'chat' }));
  7584. expect(stripAnsi(app.tui.render(120).join('\n'))).toContain('Rewound 1 turn');
  7585. expect(stripAnsi(app.tui.render(120).join('\n'))).not.toMatch(/Loading rewind history|Finding messages/);
  7586. await app.stop();
  7587. });
  7588. it("invalidates /rewind when the active session switches before mutation", async () => {
  7589. const terminal = new FakeTerminal();
  7590. const runtime = createRuntime();
  7591. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7592. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 0 },
  7593. ]);
  7594. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7595. const app = createTuiApp({
  7596. runtime,
  7597. terminal,
  7598. version: "0.1.0",
  7599. workspaceDir: "/workspace",
  7600. });
  7601. app.start();
  7602. await app.ready;
  7603. await app.submit("Seed rewind session");
  7604. await app.submit("/rewind");
  7605. await vi.waitFor(() =>
  7606. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7607. kind: "feature",
  7608. id: "session-mutation:history",
  7609. }),
  7610. );
  7611. const other = {
  7612. sessionId: "session-other",
  7613. title: "Other",
  7614. workspaceDir: "/workspace",
  7615. };
  7616. vi.mocked(runtime.getSession).mockResolvedValue(other);
  7617. await app.openSession(other.sessionId);
  7618. terminal.input?.("\r");
  7619. await new Promise((resolve) => setTimeout(resolve, 20));
  7620. expect(runtime.getSessionRewindPreview).not.toHaveBeenCalled();
  7621. expect(runtime.rewindSession).not.toHaveBeenCalled();
  7622. expect(app.controller.snapshot().session?.sessionId).toBe(other.sessionId);
  7623. await app.stop();
  7624. });
  7625. it("retries a failed file rewind with the same operation id", async () => {
  7626. const terminal = new FakeTerminal();
  7627. const runtime = createRuntime();
  7628. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7629. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7630. ]);
  7631. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7632. turns: [
  7633. {
  7634. turnId: "turn-1",
  7635. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7636. },
  7637. ],
  7638. });
  7639. vi.mocked(runtime.rewindSession)
  7640. .mockRejectedValueOnce(new Error("temporary conflict"))
  7641. .mockResolvedValueOnce({
  7642. rewound: true,
  7643. turnDiffRewind: { status: "rewound", revertedTurnIds: ["turn-1"] },
  7644. });
  7645. const app = createTuiApp({
  7646. runtime,
  7647. terminal,
  7648. version: "0.1.0",
  7649. workspaceDir: "/workspace",
  7650. });
  7651. app.start();
  7652. await app.ready;
  7653. await app.submit("Seed rewind session");
  7654. await app.submit("/rewind");
  7655. await vi.waitFor(() =>
  7656. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7657. kind: "feature",
  7658. id: "session-mutation:history",
  7659. }),
  7660. );
  7661. terminal.input?.("\r");
  7662. await vi.waitFor(() =>
  7663. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7664. kind: "feature",
  7665. id: "session-mutation:rewind-preview",
  7666. }),
  7667. );
  7668. terminal.input?.("\r");
  7669. await vi.waitFor(() =>
  7670. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7671. kind: "feature",
  7672. id: "session-mutation:scope",
  7673. }),
  7674. );
  7675. terminal.input?.("\u001b[B");
  7676. terminal.input?.("\r");
  7677. await vi.waitFor(() =>
  7678. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7679. kind: "feature",
  7680. id: "session-mutation:rewind-confirm",
  7681. }),
  7682. );
  7683. terminal.input?.("\r");
  7684. await vi.waitFor(() =>
  7685. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  7686. );
  7687. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7688. kind: "feature",
  7689. id: "session-mutation:rewind-confirm",
  7690. });
  7691. terminal.input?.("\r");
  7692. await vi.waitFor(() =>
  7693. expect(runtime.rewindSession).toHaveBeenCalledTimes(2),
  7694. );
  7695. const ids = vi
  7696. .mocked(runtime.rewindSession)
  7697. .mock.calls.map(([input]) => input.clientRequestId);
  7698. expect(ids[0]).toBe(ids[1]);
  7699. await app.stop();
  7700. });
  7701. it.each([
  7702. [
  7703. "terminal busy failure",
  7704. "CONVERSATION_MUTATION_BUSY",
  7705. "Stop the running response and try again.",
  7706. false,
  7707. ],
  7708. [
  7709. "pending display publication",
  7710. "REWIND_DISPLAY_COMMIT_FAILED",
  7711. "retry with the same operation id",
  7712. true,
  7713. ],
  7714. ] as const)(
  7715. "keeps a failed conversation rewind open and retries %s with the correct operation id",
  7716. async (_label, errorCode, expectedCopy, reuseOperationId) => {
  7717. const terminal = new FakeTerminal();
  7718. const runtime = createRuntime();
  7719. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7720. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 0 },
  7721. ]);
  7722. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7723. turns: [],
  7724. });
  7725. vi.mocked(runtime.rewindSession)
  7726. .mockRejectedValueOnce(
  7727. Object.assign(new Error("rewind failed"), { key: errorCode }),
  7728. )
  7729. .mockResolvedValueOnce({ rewound: true });
  7730. const app = createTuiApp({
  7731. runtime,
  7732. terminal,
  7733. version: "0.1.0",
  7734. workspaceDir: "/workspace",
  7735. });
  7736. app.start();
  7737. await app.ready;
  7738. await app.submit("Seed rewind session");
  7739. await app.submit("/rewind");
  7740. await vi.waitFor(() =>
  7741. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7742. kind: "feature",
  7743. id: "session-mutation:history",
  7744. }),
  7745. );
  7746. terminal.input?.("\r");
  7747. await vi.waitFor(() =>
  7748. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7749. kind: "feature",
  7750. id: "session-mutation:rewind-preview",
  7751. }),
  7752. );
  7753. terminal.input?.("\r");
  7754. await vi.waitFor(() =>
  7755. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7756. kind: "feature",
  7757. id: "session-mutation:scope",
  7758. }),
  7759. );
  7760. terminal.input?.("\r");
  7761. await vi.waitFor(() =>
  7762. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7763. kind: "feature",
  7764. id: "session-mutation:rewind-confirm",
  7765. }),
  7766. );
  7767. terminal.input?.("\r");
  7768. await vi.waitFor(() =>
  7769. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  7770. );
  7771. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7772. kind: "feature",
  7773. id: "session-mutation:rewind-confirm",
  7774. });
  7775. expect(renderTerminalViewport(app, terminal)).toContain(expectedCopy);
  7776. terminal.input?.("\r");
  7777. await vi.waitFor(() =>
  7778. expect(runtime.rewindSession).toHaveBeenCalledTimes(2),
  7779. );
  7780. const ids = vi
  7781. .mocked(runtime.rewindSession)
  7782. .mock.calls.map(([input]) => input.clientRequestId);
  7783. if (reuseOperationId) expect(ids[0]).toBe(ids[1]);
  7784. else expect(ids[0]).not.toBe(ids[1]);
  7785. await app.stop();
  7786. },
  7787. );
  7788. it.each([
  7789. [
  7790. "failed-after-rewind",
  7791. {
  7792. status: "failed-after-rewind",
  7793. revertedTurnIds: ["turn-1"],
  7794. errorCode: "conflict",
  7795. },
  7796. ],
  7797. ["empty-reverted-ids", { status: "rewound", revertedTurnIds: [] }],
  7798. [
  7799. "unknown-status",
  7800. { status: "future-runtime-status", revertedTurnIds: ["turn-1"] },
  7801. ],
  7802. ] as const)(
  7803. "does not report %s as a successful file rewind",
  7804. async (_label, turnDiffRewind) => {
  7805. const terminal = new FakeTerminal();
  7806. const runtime = createRuntime();
  7807. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7808. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7809. ]);
  7810. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7811. turns: [
  7812. {
  7813. turnId: "turn-1",
  7814. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7815. },
  7816. ],
  7817. });
  7818. vi.mocked(runtime.rewindSession).mockResolvedValue({
  7819. rewound: true,
  7820. turnDiffRewind,
  7821. });
  7822. const app = createTuiApp({
  7823. runtime,
  7824. terminal,
  7825. version: "0.1.0",
  7826. workspaceDir: "/workspace",
  7827. });
  7828. app.start();
  7829. await app.ready;
  7830. await app.submit("Seed rewind session");
  7831. await app.submit("/rewind");
  7832. await vi.waitFor(() =>
  7833. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7834. kind: "feature",
  7835. id: "session-mutation:history",
  7836. }),
  7837. );
  7838. terminal.input?.("\r");
  7839. await vi.waitFor(() =>
  7840. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7841. kind: "feature",
  7842. id: "session-mutation:rewind-preview",
  7843. }),
  7844. );
  7845. terminal.input?.("\r");
  7846. await vi.waitFor(() =>
  7847. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7848. kind: "feature",
  7849. id: "session-mutation:scope",
  7850. }),
  7851. );
  7852. terminal.input?.("\u001b[B");
  7853. terminal.input?.("\r");
  7854. await vi.waitFor(() =>
  7855. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7856. kind: "feature",
  7857. id: "session-mutation:rewind-confirm",
  7858. }),
  7859. );
  7860. terminal.input?.("\r");
  7861. await vi.waitFor(() =>
  7862. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  7863. );
  7864. await vi.waitFor(() =>
  7865. expect(app.transcript.snapshot().at(-1)?.content).toMatch(
  7866. /did not complete|No file changes/,
  7867. ),
  7868. );
  7869. expect(app.transcript.snapshot().at(-1)?.content).not.toContain(
  7870. "Files rewound; conversation history was kept.",
  7871. );
  7872. await app.stop();
  7873. },
  7874. );
  7875. it.each([
  7876. [
  7877. "MESSAGE_BOUNDARY_INVALID",
  7878. "This conversation point is no longer available.",
  7879. ],
  7880. [
  7881. "CONVERSATION_MUTATION_REQUEST_CONFLICT",
  7882. "This action was already submitted or became stale.",
  7883. ],
  7884. ["CONVERSATION_MUTATION_BUSY", "Stop the running response and try again."],
  7885. ] as const)(
  7886. "maps rewind Runtime error %s to stable copy",
  7887. async (code, expected) => {
  7888. const terminal = new FakeTerminal();
  7889. const runtime = createRuntime();
  7890. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7891. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7892. ]);
  7893. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7894. turns: [
  7895. {
  7896. turnId: "turn-1",
  7897. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7898. },
  7899. ],
  7900. });
  7901. vi.mocked(runtime.rewindSession).mockRejectedValue(
  7902. Object.assign(new Error("raw prompt token=secret"), { key: code }),
  7903. );
  7904. const app = createTuiApp({
  7905. runtime,
  7906. terminal,
  7907. version: "0.1.0",
  7908. workspaceDir: "/workspace",
  7909. });
  7910. app.start();
  7911. await app.ready;
  7912. await app.submit("Seed rewind session");
  7913. await app.submit("/rewind");
  7914. await vi.waitFor(() =>
  7915. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7916. kind: "feature",
  7917. id: "session-mutation:history",
  7918. }),
  7919. );
  7920. terminal.input?.("\r");
  7921. await vi.waitFor(() =>
  7922. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7923. kind: "feature",
  7924. id: "session-mutation:rewind-preview",
  7925. }),
  7926. );
  7927. terminal.input?.("\r");
  7928. await vi.waitFor(() =>
  7929. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7930. kind: "feature",
  7931. id: "session-mutation:scope",
  7932. }),
  7933. );
  7934. terminal.input?.("\u001b[B");
  7935. terminal.input?.("\r");
  7936. await vi.waitFor(() =>
  7937. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7938. kind: "feature",
  7939. id: "session-mutation:rewind-confirm",
  7940. }),
  7941. );
  7942. terminal.input?.("\r");
  7943. await vi.waitFor(() =>
  7944. expect(
  7945. app.transcript.snapshot().some((cell) => cell.content === expected),
  7946. ),
  7947. );
  7948. expect(
  7949. app.transcript
  7950. .snapshot()
  7951. .some((cell) => cell.content.includes("raw prompt token")),
  7952. ).toBe(false);
  7953. await app.stop();
  7954. },
  7955. );
  7956. it("reports refresh failure without unhandled rejection after conversation-and-files rewind", async () => {
  7957. const terminal = new FakeTerminal();
  7958. const runtime = createRuntime();
  7959. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7960. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7961. ]);
  7962. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7963. turns: [
  7964. {
  7965. turnId: "turn-1",
  7966. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7967. },
  7968. ],
  7969. });
  7970. vi.mocked(runtime.rewindSession).mockResolvedValue({
  7971. rewound: true,
  7972. turnDiffRewind: { status: "rewound", revertedTurnIds: ["turn-1"] },
  7973. });
  7974. vi.mocked(runtime.getMessages).mockRejectedValueOnce(
  7975. new Error("refresh unavailable"),
  7976. );
  7977. const app = createTuiApp({
  7978. runtime,
  7979. terminal,
  7980. version: "0.1.0",
  7981. workspaceDir: "/workspace",
  7982. });
  7983. app.start();
  7984. await app.ready;
  7985. await app.submit("Seed rewind session");
  7986. await app.submit("/rewind");
  7987. await vi.waitFor(() =>
  7988. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7989. kind: "feature",
  7990. id: "session-mutation:history",
  7991. }),
  7992. );
  7993. terminal.input?.("\r");
  7994. await vi.waitFor(() =>
  7995. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7996. kind: "feature",
  7997. id: "session-mutation:rewind-preview",
  7998. }),
  7999. );
  8000. terminal.input?.("\r");
  8001. await vi.waitFor(() =>
  8002. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8003. kind: "feature",
  8004. id: "session-mutation:scope",
  8005. }),
  8006. );
  8007. terminal.input?.("\u001b[B");
  8008. terminal.input?.("\r");
  8009. await vi.waitFor(() =>
  8010. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8011. kind: "feature",
  8012. id: "session-mutation:rewind-confirm",
  8013. }),
  8014. );
  8015. terminal.input?.("\r");
  8016. await vi.waitFor(() =>
  8017. expect(
  8018. app.transcript
  8019. .snapshot()
  8020. .some((cell) => cell.content.includes("could not be refreshed")),
  8021. ),
  8022. );
  8023. await app.stop();
  8024. });
  8025. it("does not apply a pending rewind refresh result after switching sessions", async () => {
  8026. const terminal = new FakeTerminal();
  8027. const runtime = createRuntime();
  8028. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  8029. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  8030. ]);
  8031. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  8032. turns: [
  8033. {
  8034. turnId: "turn-1",
  8035. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  8036. },
  8037. ],
  8038. });
  8039. vi.mocked(runtime.rewindSession).mockResolvedValue({
  8040. rewound: true,
  8041. turnDiffRewind: { status: "rewound", revertedTurnIds: ["turn-1"] },
  8042. });
  8043. let resolveRefresh!: (messages: readonly TuiMessage[]) => void;
  8044. const refreshPromise = new Promise<readonly TuiMessage[]>((resolve) => {
  8045. resolveRefresh = resolve;
  8046. });
  8047. const app = createTuiApp({
  8048. runtime,
  8049. terminal,
  8050. version: "0.1.0",
  8051. workspaceDir: "/workspace",
  8052. });
  8053. app.start();
  8054. await app.ready;
  8055. await app.submit("Seed rewind session");
  8056. vi.mocked(runtime.getMessages).mockImplementationOnce(() => refreshPromise);
  8057. await app.submit("/rewind");
  8058. await vi.waitFor(() =>
  8059. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8060. kind: "feature",
  8061. id: "session-mutation:history",
  8062. }),
  8063. );
  8064. terminal.input?.("\r");
  8065. await vi.waitFor(() =>
  8066. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8067. kind: "feature",
  8068. id: "session-mutation:rewind-preview",
  8069. }),
  8070. );
  8071. terminal.input?.("\r");
  8072. await vi.waitFor(() =>
  8073. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8074. kind: "feature",
  8075. id: "session-mutation:scope",
  8076. }),
  8077. );
  8078. terminal.input?.("\u001b[B");
  8079. terminal.input?.("\r");
  8080. await vi.waitFor(() =>
  8081. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8082. kind: "feature",
  8083. id: "session-mutation:rewind-confirm",
  8084. }),
  8085. );
  8086. terminal.input?.("\r");
  8087. await vi.waitFor(() =>
  8088. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  8089. );
  8090. const other = {
  8091. sessionId: "session-other",
  8092. title: "Other",
  8093. workspaceDir: "/workspace",
  8094. };
  8095. vi.mocked(runtime.getSession).mockResolvedValue(other);
  8096. vi.mocked(runtime.getMessages).mockResolvedValue([]);
  8097. const open = app.openSession(other.sessionId);
  8098. resolveRefresh([
  8099. {
  8100. id: "stale-message",
  8101. role: "assistant",
  8102. content: "stale",
  8103. timestamp: 3,
  8104. },
  8105. ]);
  8106. await open;
  8107. expect(app.controller.snapshot().session?.sessionId).toBe(other.sessionId);
  8108. expect(
  8109. app.transcript
  8110. .snapshot()
  8111. .some((cell) => cell.content.includes("Files rewound")),
  8112. ).toBe(false);
  8113. await app.stop();
  8114. });
  8115. it("redirects a hidden task child to its parent before rendering", async () => {
  8116. const runtime = createRuntime();
  8117. const parent = {
  8118. sessionId: "session-parent",
  8119. title: "CLI integration",
  8120. workspaceDir: "/workspace",
  8121. };
  8122. const child = {
  8123. sessionId: "session-child",
  8124. parentSessionId: parent.sessionId,
  8125. title: "Review recent CLI changes",
  8126. workspaceDir: "/workspace",
  8127. sessionType: "branch",
  8128. sessionKind: "task",
  8129. visibility: "hidden",
  8130. purpose: "local-task:turn-1:tool-1",
  8131. agentName: "verifier",
  8132. };
  8133. vi.mocked(runtime.listSessions).mockResolvedValue([parent]);
  8134. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  8135. sessionId === child.sessionId ? child : parent,
  8136. );
  8137. const app = createTuiApp({
  8138. runtime,
  8139. terminal: new FakeTerminal(),
  8140. version: "0.1.0",
  8141. workspaceDir: "/workspace",
  8142. });
  8143. await app.ready;
  8144. await app.openSession(child.sessionId);
  8145. expect(runtime.getSession).toHaveBeenLastCalledWith(parent.sessionId);
  8146. expect(app.controller.snapshot().session?.sessionId).toBe(parent.sessionId);
  8147. expect(app.tui.render(140).join("\n")).not.toContain("Sub: verifier");
  8148. expect(app.transcript.snapshot().at(-1)?.content).toBe(
  8149. "Sub-agent Sessions are internal. Opened the parent Session instead.",
  8150. );
  8151. await app.stop();
  8152. });
  8153. it("shows compact Agent Team status without exposing child details or commands", async () => {
  8154. const terminal = new FakeTerminal();
  8155. terminal.rows = 24;
  8156. const runtime = createRuntime();
  8157. const parent = {
  8158. sessionId: "session-parent",
  8159. title: "Agent Team parent",
  8160. workspaceDir: "/workspace",
  8161. };
  8162. const child = {
  8163. sessionId: "session-child",
  8164. parentSessionId: parent.sessionId,
  8165. title: "Verify the TUI",
  8166. workspaceDir: "/workspace",
  8167. sessionType: "branch" as const,
  8168. sessionKind: "task",
  8169. visibility: "hidden" as const,
  8170. purpose: "local-task:turn-1:tool-1",
  8171. agentName: "verifier",
  8172. status: "finished",
  8173. };
  8174. vi.mocked(runtime.listSessions).mockResolvedValue([parent]);
  8175. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  8176. sessionId === child.sessionId ? child : parent,
  8177. );
  8178. vi.mocked(runtime.getDelegationSnapshot).mockResolvedValue({
  8179. schemaVersion: 1,
  8180. rootSessionId: parent.sessionId,
  8181. members: [
  8182. {
  8183. sessionId: child.sessionId,
  8184. parentSessionId: parent.sessionId,
  8185. agentName: child.agentName,
  8186. task: child.title,
  8187. status: "running",
  8188. createdAtMs: 100,
  8189. updatedAtMs: 200,
  8190. },
  8191. ],
  8192. });
  8193. vi.mocked(runtime.getMessages).mockImplementation(async (sessionId) =>
  8194. sessionId === child.sessionId
  8195. ? [
  8196. {
  8197. id: "child-answer",
  8198. turnId: "turn-child",
  8199. role: "assistant",
  8200. content: "Child verification result",
  8201. timestamp: 200,
  8202. },
  8203. ]
  8204. : [],
  8205. );
  8206. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
  8207. schemaVersion: 1,
  8208. sessionId,
  8209. state: sessionId === child.sessionId ? "running" : "idle",
  8210. ...(sessionId === child.sessionId ? { turnId: "turn-child" } : {}),
  8211. actions: { steer: false },
  8212. }));
  8213. const app = createTuiApp({
  8214. runtime,
  8215. terminal,
  8216. version: "0.1.0",
  8217. workspaceDir: "/workspace",
  8218. });
  8219. await app.ready;
  8220. await app.openSession(parent.sessionId);
  8221. app.start();
  8222. const summary = app.tui.render(100).join("\n");
  8223. expect(summary).toContain("Tasks · 1 agent active · /tasks details");
  8224. expect(summary).not.toContain("verifier");
  8225. expect(summary).not.toContain("/agents");
  8226. expect(
  8227. app.transcript.snapshot().some((cell) => cell.kind === "agent-team"),
  8228. ).toBe(false);
  8229. await app.submit("/agents");
  8230. await app.submit("/team");
  8231. expect(app.controller.snapshot().session?.sessionId).toBe(parent.sessionId);
  8232. expect(app.tui.hasOverlay()).toBe(false);
  8233. expect(app.interaction.isActive()).toBe(false);
  8234. expect(app.tui.render(100).join("\n")).not.toContain(
  8235. "Child verification result",
  8236. );
  8237. expect(
  8238. vi
  8239. .mocked(runtime.sendMessage)
  8240. .mock.calls.map(([request]) => request.content),
  8241. ).toEqual(["/agents", "/team"]);
  8242. await app.stop();
  8243. });
  8244. it("allocates enough standard-terminal space for ten session choices", async () => {
  8245. const terminal = new FakeTerminal();
  8246. terminal.rows = 24;
  8247. const runtime = createRuntime();
  8248. vi.mocked(runtime.listSessionPage).mockResolvedValue({
  8249. sessions: Array.from({ length: 12 }, (_, index) => ({
  8250. sessionId: `session-${String(index + 1).padStart(2, "0")}`,
  8251. title: `Session ${String(index + 1).padStart(2, "0")}`,
  8252. workspaceDir: "/workspace",
  8253. updatedAt: 12 - index,
  8254. })),
  8255. hasMore: false,
  8256. });
  8257. const app = createTuiApp({
  8258. runtime,
  8259. terminal,
  8260. version: "0.1.0",
  8261. workspaceDir: "/workspace",
  8262. });
  8263. await app.submit("/sessions");
  8264. const lines = app.interaction.current()?.render(80) ?? [];
  8265. const rendered = lines.join("\n");
  8266. expect(lines.length).toBeLessThanOrEqual(terminal.rows);
  8267. expect(rendered).toContain("Session 10");
  8268. expect(rendered).not.toContain("Session 11");
  8269. });
  8270. it("switches, restores, and resumes archived Desktop sessions from the session manager", async () => {
  8271. const terminal = new FakeTerminal();
  8272. const runtime = createRuntime();
  8273. let archived = true;
  8274. const activeSession = {
  8275. sessionId: "session-active",
  8276. title: "Active session",
  8277. workspaceDir: "/workspace",
  8278. updatedAt: 200,
  8279. };
  8280. const archivedSession = {
  8281. sessionId: "session-archived",
  8282. title: "Archived session",
  8283. workspaceDir: "/workspace",
  8284. updatedAt: 100,
  8285. archived: true,
  8286. };
  8287. vi.mocked(runtime.listSessions).mockResolvedValue([activeSession]);
  8288. vi.mocked(runtime.listSessionPage).mockResolvedValue({
  8289. sessions: [activeSession, archivedSession],
  8290. hasMore: false,
  8291. });
  8292. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) => ({
  8293. ...(sessionId === archivedSession.sessionId
  8294. ? archivedSession
  8295. : activeSession),
  8296. archived: sessionId === archivedSession.sessionId ? archived : false,
  8297. }));
  8298. vi.mocked(runtime.archiveSession).mockImplementation(
  8299. async (_sessionId, value) => {
  8300. archived = value;
  8301. },
  8302. );
  8303. const app = createTuiApp({
  8304. runtime,
  8305. terminal,
  8306. version: "0.1.0",
  8307. workspaceDir: "/workspace",
  8308. });
  8309. app.start();
  8310. await app.ready;
  8311. await app.submit("/sessions");
  8312. expect(runtime.listSessionPage).toHaveBeenCalledWith({
  8313. allAgents: true,
  8314. workspaceDir: "/workspace",
  8315. limit: 50,
  8316. includeArchived: true,
  8317. includeHidden: true,
  8318. });
  8319. expect(app.tui.hasOverlay()).toBe(false);
  8320. expect(app.interaction.isActive()).toBe(true);
  8321. terminal.input?.("\t");
  8322. terminal.input?.("\r");
  8323. await vi.waitFor(() =>
  8324. expect(runtime.archiveSession).toHaveBeenCalledWith(
  8325. "session-archived",
  8326. false,
  8327. ),
  8328. );
  8329. await vi.waitFor(() =>
  8330. expect(runtime.getMessages).toHaveBeenCalledWith("session-archived"),
  8331. );
  8332. expect(app.getSurface()).toBe("conversation");
  8333. expect(app.controller.snapshot().session?.sessionId).toBe(
  8334. "session-archived",
  8335. );
  8336. expect(app.tui.hasOverlay()).toBe(false);
  8337. await app.stop();
  8338. });
  8339. it("uses the resume alias to search every Desktop session page", async () => {
  8340. const terminal = new FakeTerminal();
  8341. const runtime = createRuntime();
  8342. vi.mocked(runtime.listSessionPage)
  8343. .mockResolvedValueOnce({
  8344. sessions: [
  8345. {
  8346. sessionId: "session-page-1",
  8347. title: "First page",
  8348. workspaceDir: "/workspace",
  8349. updatedAt: 200,
  8350. },
  8351. ],
  8352. hasMore: true,
  8353. nextCursor: "session-page-1",
  8354. })
  8355. .mockResolvedValueOnce({
  8356. sessions: [
  8357. {
  8358. sessionId: "session-page-2",
  8359. title: "Second page",
  8360. workspaceDir: "/workspace",
  8361. updatedAt: 100,
  8362. },
  8363. ],
  8364. hasMore: false,
  8365. });
  8366. const app = createTuiApp({
  8367. runtime,
  8368. terminal,
  8369. version: "0.1.0",
  8370. workspaceDir: "/workspace",
  8371. });
  8372. app.start();
  8373. await app.ready;
  8374. await app.submit("/resume Second page");
  8375. await vi.waitFor(() =>
  8376. expect(runtime.listSessionPage).toHaveBeenNthCalledWith(2, {
  8377. allAgents: true,
  8378. workspaceDir: "/workspace",
  8379. limit: 50,
  8380. cursor: "session-page-1",
  8381. includeArchived: true,
  8382. includeHidden: true,
  8383. }),
  8384. );
  8385. expect(app.tui.hasOverlay()).toBe(false);
  8386. expect(app.interaction.isActive()).toBe(true);
  8387. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8388. "Second page",
  8389. );
  8390. await app.stop();
  8391. });
  8392. it("queries the current workspace first and reloads the global catalog on Ctrl+A", async () => {
  8393. const terminal = new FakeTerminal();
  8394. const runtime = createRuntime();
  8395. vi.mocked(runtime.listSessionPage).mockImplementation(
  8396. async (input = {}) => {
  8397. if (input.cursor === "all-page-2") {
  8398. return {
  8399. sessions: [
  8400. {
  8401. sessionId: "session-other-older",
  8402. title: "Older session elsewhere",
  8403. workspaceDir: "/other-workspace",
  8404. updatedAt: 50,
  8405. },
  8406. ],
  8407. hasMore: false,
  8408. };
  8409. }
  8410. return input.workspaceDir
  8411. ? {
  8412. sessions: [
  8413. {
  8414. sessionId: "session-workspace-old",
  8415. title: "Older workspace session",
  8416. workspaceDir: "/workspace",
  8417. updatedAt: 100,
  8418. },
  8419. ],
  8420. hasMore: false,
  8421. }
  8422. : {
  8423. sessions: [
  8424. {
  8425. sessionId: "session-other-new",
  8426. title: "Newer session elsewhere",
  8427. workspaceDir: "/other-workspace",
  8428. updatedAt: 200,
  8429. },
  8430. {
  8431. sessionId: "session-workspace-old",
  8432. title: "Older workspace session",
  8433. workspaceDir: "/workspace",
  8434. updatedAt: 100,
  8435. },
  8436. ],
  8437. hasMore: true,
  8438. nextCursor: "all-page-2",
  8439. };
  8440. },
  8441. );
  8442. const app = createTuiApp({
  8443. runtime,
  8444. terminal,
  8445. version: "0.1.0",
  8446. workspaceDir: "/workspace",
  8447. });
  8448. app.start();
  8449. await app.ready;
  8450. await app.submit("/sessions");
  8451. expect(runtime.listSessionPage).toHaveBeenNthCalledWith(1, {
  8452. allAgents: true,
  8453. workspaceDir: "/workspace",
  8454. limit: 50,
  8455. includeArchived: true,
  8456. includeHidden: true,
  8457. });
  8458. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8459. "Older workspace session",
  8460. );
  8461. terminal.input?.("\x01");
  8462. await vi.waitFor(() =>
  8463. expect(runtime.listSessionPage).toHaveBeenNthCalledWith(2, {
  8464. allAgents: true,
  8465. limit: 50,
  8466. includeArchived: true,
  8467. includeHidden: true,
  8468. }),
  8469. );
  8470. await vi.waitFor(() =>
  8471. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8472. "Newer session elsewhere",
  8473. ),
  8474. );
  8475. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8476. "All sessions",
  8477. );
  8478. terminal.input?.("\x0c");
  8479. await vi.waitFor(() =>
  8480. expect(runtime.listSessionPage).toHaveBeenNthCalledWith(3, {
  8481. allAgents: true,
  8482. limit: 50,
  8483. cursor: "all-page-2",
  8484. includeArchived: true,
  8485. includeHidden: true,
  8486. }),
  8487. );
  8488. await vi.waitFor(() =>
  8489. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8490. "Older session elsewhere",
  8491. ),
  8492. );
  8493. await app.stop();
  8494. });
  8495. it("shows account status and resolves pending permission and questionnaire decisions", async () => {
  8496. const terminal = new FakeTerminal();
  8497. const runtime = createRuntime();
  8498. vi.mocked(runtime.listSessions).mockResolvedValue([
  8499. {
  8500. sessionId: "session-existing",
  8501. title: "Existing session",
  8502. workspaceDir: "/workspace",
  8503. },
  8504. ]);
  8505. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  8506. {
  8507. requestId: "permission-1",
  8508. sessionId: "session-existing",
  8509. agentName: "mavis",
  8510. toolName: "bash",
  8511. reason: "Run tests",
  8512. allowAlwaysSupported: true,
  8513. },
  8514. ]);
  8515. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8516. id: "question-1",
  8517. title: "Choose",
  8518. steps: [
  8519. {
  8520. id: "step-1",
  8521. question: "Proceed?",
  8522. selectionMode: "single",
  8523. options: [
  8524. { id: "yes", label: "Yes" },
  8525. { id: "no", label: "No" },
  8526. ],
  8527. },
  8528. ],
  8529. });
  8530. const app = createTuiApp({
  8531. runtime,
  8532. terminal,
  8533. version: "0.1.0",
  8534. workspaceDir: "/workspace",
  8535. });
  8536. await app.ready;
  8537. await app.submit("/resume session-existing");
  8538. expect(app.transcript.snapshot()).toEqual(
  8539. expect.arrayContaining([
  8540. expect.objectContaining({ kind: "permission", status: "blocked" }),
  8541. expect.objectContaining({ kind: "question", status: "blocked" }),
  8542. ]),
  8543. );
  8544. expect(app.transcript.get("permission:permission-1")).toMatchObject({
  8545. title: "bash",
  8546. content: "Run tests",
  8547. });
  8548. expect(
  8549. app.transcript.get("permission:permission-1")?.content,
  8550. ).not.toContain("decision panel");
  8551. expect(app.transcript.get("permission:permission-1")?.content).not.toMatch(
  8552. /\/(?:allow|always|deny)\b/u,
  8553. );
  8554. expect(app.transcript.get("question:question-1")?.content).toBe("");
  8555. await app.submit("/q1 1");
  8556. expect(runtime.replyQuestionnaire).not.toHaveBeenCalled();
  8557. expect(app.tui.hasOverlay()).toBe(false);
  8558. expect(app.interaction.isActive()).toBe(true);
  8559. expect(terminal.mouseTracking).toBe(false);
  8560. await app.submit("/allow");
  8561. await app.submit("/q1 1");
  8562. await app.submit("/status");
  8563. expect(runtime.replyPermission).toHaveBeenCalledWith(
  8564. "mavis",
  8565. "permission-1",
  8566. "allowOnce",
  8567. );
  8568. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  8569. "mavis",
  8570. "question-1",
  8571. [
  8572. {
  8573. stepId: "step-1",
  8574. selectedOptionIds: ["yes"],
  8575. selectedOther: false,
  8576. },
  8577. ],
  8578. );
  8579. expect(terminal.mouseTracking).toBe(false);
  8580. expect(app.transcript.get("question:question-1")).toMatchObject({
  8581. status: "resolved",
  8582. title: "Answers sent",
  8583. content: "Proceed? Yes",
  8584. });
  8585. expect(app.interaction.current()).toBeDefined();
  8586. expect(app.tui.render(80).join("\n")).toContain("MCode status");
  8587. expect(app.transcript.snapshot()).not.toEqual(
  8588. expect.arrayContaining([
  8589. expect.objectContaining({
  8590. kind: "inspection",
  8591. inspection: expect.objectContaining({
  8592. visualization: { kind: "status" },
  8593. }),
  8594. }),
  8595. ]),
  8596. );
  8597. });
  8598. it("does not let a stale permission response hide a newer decision surface", async () => {
  8599. const terminal = new FakeTerminal();
  8600. const runtime = createRuntime();
  8601. vi.mocked(runtime.listSessions).mockResolvedValue([
  8602. {
  8603. sessionId: "session-race",
  8604. title: "Decision race",
  8605. workspaceDir: "/workspace",
  8606. },
  8607. ]);
  8608. const firstPermission = {
  8609. requestId: "permission-first",
  8610. sessionId: "session-race",
  8611. agentName: "mavis",
  8612. toolName: "bash",
  8613. reason: "First request",
  8614. allowAlwaysSupported: true,
  8615. };
  8616. const secondPermission = {
  8617. requestId: "permission-second",
  8618. sessionId: "session-race",
  8619. agentName: "mavis",
  8620. toolName: "write_file",
  8621. reason: "Newer request",
  8622. allowAlwaysSupported: false,
  8623. };
  8624. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  8625. firstPermission,
  8626. ]);
  8627. let finishReply: ((value: boolean) => void) | undefined;
  8628. vi.mocked(runtime.replyPermission).mockImplementation(
  8629. async () =>
  8630. await new Promise<boolean>((resolve) => {
  8631. finishReply = resolve;
  8632. }),
  8633. );
  8634. let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  8635. vi.mocked(runtime.watchEvents).mockImplementation(
  8636. async function* watchEvents(signal) {
  8637. const event = await new Promise<TuiRuntimeEvent | undefined>(
  8638. (resolve) => {
  8639. emitEvent = resolve;
  8640. signal.addEventListener("abort", () => resolve(undefined), {
  8641. once: true,
  8642. });
  8643. },
  8644. );
  8645. if (event) yield event;
  8646. await new Promise<void>((resolve) => {
  8647. signal.addEventListener("abort", resolve, { once: true });
  8648. });
  8649. },
  8650. );
  8651. const app = createTuiApp({
  8652. runtime,
  8653. terminal,
  8654. version: "0.1.0",
  8655. workspaceDir: "/workspace",
  8656. });
  8657. app.start();
  8658. await app.ready;
  8659. await app.submit("/resume session-race");
  8660. const resolving = app.submit("/allow");
  8661. await vi.waitFor(() => expect(runtime.replyPermission).toHaveBeenCalled());
  8662. await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
  8663. emitEvent?.(
  8664. runtimeEvent({
  8665. type: "permission.ask",
  8666. timestamp: Date.now(),
  8667. source: "test",
  8668. payload: secondPermission,
  8669. }),
  8670. );
  8671. await vi.waitFor(() =>
  8672. expect(app.tui.render(80).join("\n")).toContain("Newer request"),
  8673. );
  8674. finishReply?.(true);
  8675. await resolving;
  8676. const rendered = app.tui.render(80).join("\n");
  8677. expect(rendered).toContain("Write file");
  8678. expect(rendered).toContain("Newer request");
  8679. expect(runtime.replyPermission).toHaveBeenCalledTimes(1);
  8680. await app.stop();
  8681. });
  8682. it("closes a permission that another surface resolved before the reply arrived", async () => {
  8683. const terminal = new FakeTerminal();
  8684. const runtime = createRuntime();
  8685. const permission = {
  8686. requestId: "permission-stale",
  8687. sessionId: "session-permission-stale",
  8688. agentName: "mavis",
  8689. toolName: "bash",
  8690. reason: "Run tests",
  8691. allowAlwaysSupported: true,
  8692. };
  8693. vi.mocked(runtime.listSessions).mockResolvedValue([
  8694. {
  8695. sessionId: "session-permission-stale",
  8696. title: "Permission race",
  8697. workspaceDir: "/workspace",
  8698. },
  8699. ]);
  8700. vi.mocked(runtime.listPendingPermissions)
  8701. .mockResolvedValueOnce([permission])
  8702. .mockResolvedValue([]);
  8703. vi.mocked(runtime.replyPermission).mockResolvedValue(false);
  8704. const app = createTuiApp({
  8705. runtime,
  8706. terminal,
  8707. version: "0.1.0",
  8708. workspaceDir: "/workspace",
  8709. });
  8710. await app.ready;
  8711. await app.submit("/resume session-permission-stale");
  8712. await app.submit("/allow");
  8713. expect(app.transcript.get("permission:permission-stale")).toMatchObject({
  8714. status: "resolved",
  8715. detail: "Resolved on another surface.",
  8716. });
  8717. expect(app.interaction.isActive()).toBe(false);
  8718. });
  8719. it("keeps an option-only questionnaire pending after an invalid slash answer", async () => {
  8720. const terminal = new FakeTerminal();
  8721. const runtime = createRuntime();
  8722. vi.mocked(runtime.listSessions).mockResolvedValue([
  8723. {
  8724. sessionId: "session-questionnaire",
  8725. title: "Questionnaire session",
  8726. workspaceDir: "/workspace",
  8727. },
  8728. ]);
  8729. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8730. id: "question-options-only",
  8731. title: "Choose",
  8732. steps: [
  8733. {
  8734. id: "channel",
  8735. question: "Choose a release channel",
  8736. selectionMode: "single",
  8737. options: [
  8738. { id: "preview", label: "Preview" },
  8739. { id: "stable", label: "Stable" },
  8740. ],
  8741. allowOther: false,
  8742. },
  8743. ],
  8744. });
  8745. const app = createTuiApp({
  8746. runtime,
  8747. terminal,
  8748. version: "0.1.0",
  8749. workspaceDir: "/workspace",
  8750. });
  8751. await app.ready;
  8752. await app.submit("/resume session-questionnaire");
  8753. await app.submit("/q1 nightly");
  8754. expect(runtime.replyQuestionnaire).not.toHaveBeenCalled();
  8755. expect(app.transcript.get("question:question-options-only")).toMatchObject({
  8756. status: "blocked",
  8757. });
  8758. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  8759. kind: "warning",
  8760. content:
  8761. "/q1 accepts only listed options. Use an option number, ID, or label.",
  8762. });
  8763. await app.submit("/q1 1");
  8764. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  8765. "mavis",
  8766. "question-options-only",
  8767. [
  8768. {
  8769. stepId: "channel",
  8770. selectedOptionIds: ["preview"],
  8771. selectedOther: false,
  8772. },
  8773. ],
  8774. );
  8775. });
  8776. it("shows the first AskUser answer immediately while later questions remain pending", async () => {
  8777. const terminal = new FakeTerminal();
  8778. const runtime = createRuntime();
  8779. vi.mocked(runtime.listSessions).mockResolvedValue([
  8780. {
  8781. sessionId: "session-multi-question",
  8782. title: "Multi question",
  8783. workspaceDir: "/workspace",
  8784. },
  8785. ]);
  8786. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8787. id: "question-multi-step",
  8788. title: "Preferences",
  8789. steps: [
  8790. {
  8791. id: "animal",
  8792. question: "Favorite animal?",
  8793. selectionMode: "single",
  8794. options: [
  8795. { id: "cat", label: "Cat" },
  8796. { id: "dog", label: "Dog" },
  8797. ],
  8798. },
  8799. {
  8800. id: "color",
  8801. question: "Favorite color?",
  8802. selectionMode: "single",
  8803. options: [
  8804. { id: "blue", label: "Blue" },
  8805. { id: "green", label: "Green" },
  8806. ],
  8807. },
  8808. ],
  8809. });
  8810. const app = createTuiApp({
  8811. runtime,
  8812. terminal,
  8813. version: "0.1.0",
  8814. workspaceDir: "/workspace",
  8815. });
  8816. await app.ready;
  8817. app.start();
  8818. await app.submit("/resume session-multi-question");
  8819. const picker = app.interaction.current();
  8820. expect(picker).toBeDefined();
  8821. terminal.input?.("1");
  8822. expect(runtime.replyQuestionnaire).not.toHaveBeenCalled();
  8823. expect(app.interaction.current()).toBe(picker);
  8824. expect(app.transcript.get("question:question-multi-step")).toMatchObject({
  8825. status: "blocked",
  8826. content: "Favorite animal? Cat",
  8827. detail: "1 of 2 answered",
  8828. });
  8829. const rendered = app.tui.render(80).join("\n");
  8830. expect(rendered).toContain("Answers so far");
  8831. expect(rendered).toContain("Favorite animal? Cat");
  8832. expect(rendered).toContain("Favorite color?");
  8833. terminal.input?.("\u001B[B");
  8834. expect(app.tui.render(80).join("\n")).toContain("› 2 Green");
  8835. terminal.input?.("\r");
  8836. await vi.waitFor(() => {
  8837. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  8838. "mavis",
  8839. "question-multi-step",
  8840. [
  8841. {
  8842. stepId: "animal",
  8843. selectedOptionIds: ["cat"],
  8844. selectedOther: false,
  8845. },
  8846. {
  8847. stepId: "color",
  8848. selectedOptionIds: ["green"],
  8849. selectedOther: false,
  8850. },
  8851. ],
  8852. );
  8853. });
  8854. await app.stop();
  8855. });
  8856. it("sends the selected answer immediately and refreshes the Agent continuation", async () => {
  8857. const terminal = new FakeTerminal();
  8858. const runtime = createRuntime();
  8859. vi.mocked(runtime.listSessions).mockResolvedValue([
  8860. {
  8861. sessionId: "session-review",
  8862. title: "Questionnaire review",
  8863. workspaceDir: "/workspace",
  8864. },
  8865. ]);
  8866. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8867. id: "question-review",
  8868. title: "Release setup",
  8869. steps: [
  8870. {
  8871. id: "channel",
  8872. question: "Choose a channel",
  8873. selectionMode: "single",
  8874. options: [
  8875. { id: "preview", label: "Preview" },
  8876. { id: "stable", label: "Stable" },
  8877. ],
  8878. },
  8879. ],
  8880. });
  8881. const previousMessages = [
  8882. {
  8883. id: "previous-question-answer",
  8884. role: "user" as const,
  8885. content: [
  8886. "<questionnaire-response>",
  8887. " <requestId>question-previous</requestId>",
  8888. " <answers />",
  8889. "</questionnaire-response>",
  8890. "",
  8891. "Q: Choose a channel",
  8892. "A: Preview",
  8893. ].join("\n"),
  8894. },
  8895. ];
  8896. vi.mocked(runtime.getMessages).mockResolvedValue(previousMessages);
  8897. const app = createTuiApp({
  8898. runtime,
  8899. terminal,
  8900. version: "0.1.0",
  8901. workspaceDir: "/workspace",
  8902. });
  8903. let releaseReply: ((result: boolean) => void) | undefined;
  8904. let releaseContinuation: (() => void) | undefined;
  8905. vi.mocked(runtime.replyQuestionnaire).mockImplementation(
  8906. async () =>
  8907. await new Promise<boolean>((resolve) => {
  8908. releaseReply = resolve;
  8909. }),
  8910. );
  8911. vi.mocked(runtime.watchEvents).mockImplementation(
  8912. async function* watchEvents(signal) {
  8913. await new Promise<void>((resolve) => {
  8914. releaseContinuation = resolve;
  8915. signal.addEventListener("abort", resolve, { once: true });
  8916. });
  8917. if (signal.aborted) return;
  8918. yield runtimeEvent({
  8919. type: "session.start",
  8920. timestamp: Date.now(),
  8921. source: "runtime",
  8922. payload: {
  8923. sessionId: "session-review",
  8924. turnId: "turn-questionnaire-continuation",
  8925. },
  8926. });
  8927. yield runtimeEvent({
  8928. type: "session.finish",
  8929. timestamp: Date.now(),
  8930. source: "runtime",
  8931. payload: {
  8932. sessionId: "session-review",
  8933. turnId: "turn-questionnaire-continuation",
  8934. },
  8935. });
  8936. },
  8937. );
  8938. app.start();
  8939. await app.ready;
  8940. await app.submit("/resume session-review");
  8941. expect(app.tui.hasOverlay()).toBe(false);
  8942. expect(app.interaction.isActive()).toBe(true);
  8943. terminal.input?.("2");
  8944. await vi.waitFor(() =>
  8945. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  8946. "mavis",
  8947. "question-review",
  8948. [
  8949. {
  8950. stepId: "channel",
  8951. selectedOptionIds: ["stable"],
  8952. selectedOther: false,
  8953. },
  8954. ],
  8955. ),
  8956. );
  8957. expect(app.tui.hasOverlay()).toBe(false);
  8958. expect(app.transcript.get("question:question-review")).toMatchObject({
  8959. status: "pending",
  8960. detail: "Sending your answer…",
  8961. });
  8962. releaseReply?.(true);
  8963. await vi.waitFor(() =>
  8964. expect(app.transcript.get("question:question-review")).toMatchObject({
  8965. status: "resolved",
  8966. detail: "Answer sent · MCode is continuing…",
  8967. }),
  8968. );
  8969. vi.mocked(runtime.getMessages).mockResolvedValue([
  8970. ...previousMessages,
  8971. {
  8972. id: "assistant-after-question",
  8973. role: "assistant",
  8974. content: "Agent continued after your answer.",
  8975. },
  8976. ]);
  8977. releaseContinuation?.();
  8978. await vi.waitFor(() =>
  8979. expect(
  8980. app.transcript
  8981. .snapshot()
  8982. .map((cell) => cell.content)
  8983. .join("\n"),
  8984. ).toContain("Agent continued after your answer."),
  8985. );
  8986. expect(app.transcript.get("question:question-review")).toMatchObject({
  8987. kind: "question",
  8988. status: "resolved",
  8989. title: "Answers sent",
  8990. content: "Choose a channel Stable",
  8991. detail: undefined,
  8992. });
  8993. expect(
  8994. app.transcript
  8995. .snapshot()
  8996. .filter((cell) => cell.kind === "question")
  8997. .map((cell) => cell.content),
  8998. ).toEqual(["Choose a channel Preview", "Choose a channel Stable"]);
  8999. expect(app.tui.render(80).join("\n")).not.toContain("Thinking · Message");
  9000. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
  9001. await app.stop();
  9002. });
  9003. it("redraws after a delayed questionnaire reply resolves", async () => {
  9004. const terminal = new FakeTerminal();
  9005. const runtime = createRuntime();
  9006. vi.mocked(runtime.listSessions).mockResolvedValue([
  9007. {
  9008. sessionId: "session-delayed-reply",
  9009. title: "Delayed questionnaire reply",
  9010. workspaceDir: "/workspace",
  9011. },
  9012. ]);
  9013. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9014. id: "question-delayed-reply",
  9015. steps: [
  9016. {
  9017. id: "channel",
  9018. question: "Choose a channel",
  9019. selectionMode: "single",
  9020. options: [{ id: "preview", label: "Preview" }],
  9021. },
  9022. ],
  9023. });
  9024. let finishReply: ((result: boolean) => void) | undefined;
  9025. vi.mocked(runtime.replyQuestionnaire).mockImplementation(
  9026. async () =>
  9027. await new Promise<boolean>((resolve) => {
  9028. finishReply = resolve;
  9029. }),
  9030. );
  9031. const app = createTuiApp({
  9032. runtime,
  9033. terminal,
  9034. version: "0.1.0",
  9035. workspaceDir: "/workspace",
  9036. });
  9037. app.start();
  9038. await app.ready;
  9039. await app.submit("/resume session-delayed-reply");
  9040. terminal.input?.("1");
  9041. await vi.waitFor(() =>
  9042. expect(runtime.replyQuestionnaire).toHaveBeenCalledTimes(1),
  9043. );
  9044. expect(app.tui.hasOverlay()).toBe(false);
  9045. const writesBeforeResolution = terminal.writes.length;
  9046. finishReply?.(true);
  9047. await vi.waitFor(() =>
  9048. expect(
  9049. app.transcript.get("question:question-delayed-reply"),
  9050. ).toMatchObject({
  9051. status: "resolved",
  9052. detail: "Answer sent · MCode is continuing…",
  9053. }),
  9054. );
  9055. await vi.waitFor(() =>
  9056. expect(terminal.writes.length).toBeGreaterThan(writesBeforeResolution),
  9057. );
  9058. await app.stop();
  9059. });
  9060. it("keeps the questionnaire interactive when the Runtime cannot start its continuation", async () => {
  9061. const terminal = new FakeTerminal();
  9062. const runtime = createRuntime();
  9063. vi.mocked(runtime.listSessions).mockResolvedValue([
  9064. {
  9065. sessionId: "session-retry-questionnaire",
  9066. title: "Retry questionnaire",
  9067. workspaceDir: "/workspace",
  9068. },
  9069. ]);
  9070. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9071. id: "question-retry",
  9072. title: "Choose a channel",
  9073. steps: [
  9074. {
  9075. id: "channel",
  9076. question: "Choose a channel",
  9077. selectionMode: "single",
  9078. options: [{ id: "preview", label: "Preview" }],
  9079. },
  9080. ],
  9081. });
  9082. vi.mocked(runtime.replyQuestionnaire).mockRejectedValue(
  9083. new Error(
  9084. "Questionnaire answer was saved, but the continuation could not start.",
  9085. ),
  9086. );
  9087. const app = createTuiApp({
  9088. runtime,
  9089. terminal,
  9090. version: "0.1.0",
  9091. workspaceDir: "/workspace",
  9092. });
  9093. app.start();
  9094. app.start();
  9095. await app.ready;
  9096. await app.submit("/resume session-retry-questionnaire");
  9097. terminal.input?.("1");
  9098. await vi.waitFor(() =>
  9099. expect(app.transcript.get("question:question-retry")).toMatchObject({
  9100. status: "blocked",
  9101. title: "Choose a channel",
  9102. detail: "Answer could not be sent · retry",
  9103. }),
  9104. );
  9105. expect(app.interaction.isActive()).toBe(true);
  9106. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  9107. kind: "error",
  9108. content:
  9109. "Couldn't send your answers: Questionnaire answer was saved, but the continuation could not start. Retry. The question remains open.",
  9110. });
  9111. await app.stop();
  9112. });
  9113. it("redraws after a delayed questionnaire dismissal resolves", async () => {
  9114. const terminal = new FakeTerminal();
  9115. const runtime = createRuntime();
  9116. vi.mocked(runtime.listSessions).mockResolvedValue([
  9117. {
  9118. sessionId: "session-delayed-dismiss",
  9119. title: "Delayed questionnaire dismissal",
  9120. workspaceDir: "/workspace",
  9121. },
  9122. ]);
  9123. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9124. id: "question-delayed-dismiss",
  9125. steps: [{ id: "confirmation", question: "Continue?" }],
  9126. });
  9127. let finishDismiss: ((result: boolean) => void) | undefined;
  9128. vi.mocked(runtime.dismissQuestionnaire).mockImplementation(
  9129. async () =>
  9130. await new Promise<boolean>((resolve) => {
  9131. finishDismiss = resolve;
  9132. }),
  9133. );
  9134. const app = createTuiApp({
  9135. runtime,
  9136. terminal,
  9137. version: "0.1.0",
  9138. workspaceDir: "/workspace",
  9139. });
  9140. app.start();
  9141. await app.ready;
  9142. await app.submit("/resume session-delayed-dismiss");
  9143. const dismissing = app.submit("/ask-cancel");
  9144. await vi.waitFor(() =>
  9145. expect(runtime.dismissQuestionnaire).toHaveBeenCalledTimes(1),
  9146. );
  9147. const writesBeforeResolution = terminal.writes.length;
  9148. finishDismiss?.(true);
  9149. await dismissing;
  9150. expect(
  9151. app.transcript.get("question:question-delayed-dismiss"),
  9152. ).toMatchObject({
  9153. status: "resolved",
  9154. title: "Question dismissed",
  9155. content: "",
  9156. detail: undefined,
  9157. });
  9158. await vi.waitFor(() =>
  9159. expect(terminal.writes.length).toBeGreaterThan(writesBeforeResolution),
  9160. );
  9161. await app.stop();
  9162. });
  9163. it.each([
  9164. { keyName: "Escape", input: "\x1b" },
  9165. { keyName: "Ctrl-C", input: "\x03" },
  9166. ])(
  9167. "keeps AskUser focused while $keyName dismisses the pending questionnaire",
  9168. async ({ input }) => {
  9169. const terminal = new FakeTerminal();
  9170. const runtime = createRuntime();
  9171. vi.mocked(runtime.listSessions).mockResolvedValue([
  9172. {
  9173. sessionId: "session-escape-dismiss",
  9174. title: "Escape questionnaire dismissal",
  9175. workspaceDir: "/workspace",
  9176. },
  9177. ]);
  9178. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9179. id: "question-escape-dismiss",
  9180. steps: [
  9181. {
  9182. id: "channel",
  9183. question: "Choose a channel",
  9184. selectionMode: "single",
  9185. options: [{ id: "preview", label: "Preview" }],
  9186. },
  9187. ],
  9188. });
  9189. let finishDismiss: ((result: boolean) => void) | undefined;
  9190. vi.mocked(runtime.dismissQuestionnaire).mockImplementation(
  9191. async () =>
  9192. await new Promise<boolean>((resolve) => {
  9193. finishDismiss = resolve;
  9194. }),
  9195. );
  9196. const app = createTuiApp({
  9197. runtime,
  9198. terminal,
  9199. version: "0.1.0",
  9200. workspaceDir: "/workspace",
  9201. });
  9202. app.start();
  9203. await app.ready;
  9204. await app.submit("/resume session-escape-dismiss");
  9205. terminal.input?.(input);
  9206. if (input === "\x1b") {
  9207. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9208. "Cancel this question?",
  9209. );
  9210. terminal.input?.("\r");
  9211. }
  9212. await vi.waitFor(() =>
  9213. expect(runtime.dismissQuestionnaire).toHaveBeenCalledWith(
  9214. "mavis",
  9215. "question-escape-dismiss",
  9216. ),
  9217. );
  9218. expect(app.interaction.isActive()).toBe(true);
  9219. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9220. "Closing question",
  9221. );
  9222. expect(
  9223. app.state.snapshot().sessions.get("session-escape-dismiss")?.attention
  9224. .question,
  9225. ).toBe(true);
  9226. finishDismiss?.(true);
  9227. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  9228. expect(
  9229. app.transcript.get("question:question-escape-dismiss"),
  9230. ).toMatchObject({
  9231. status: "resolved",
  9232. title: "Question dismissed",
  9233. });
  9234. expect(
  9235. app.state.snapshot().sessions.get("session-escape-dismiss")?.attention
  9236. .question,
  9237. ).toBe(false);
  9238. expect(app.tui.render(80).join("\n")).not.toContain("Reply required");
  9239. await app.stop();
  9240. },
  9241. );
  9242. it("denies a pending permission explicitly and releases the blocked interaction", async () => {
  9243. const terminal = new FakeTerminal();
  9244. const runtime = createRuntime();
  9245. vi.mocked(runtime.listSessions).mockResolvedValue([
  9246. {
  9247. sessionId: "session-pending",
  9248. title: "Pending permission",
  9249. workspaceDir: "/workspace",
  9250. },
  9251. ]);
  9252. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  9253. {
  9254. requestId: "permission-pending",
  9255. sessionId: "session-pending",
  9256. agentName: "mavis",
  9257. toolName: "bash",
  9258. toolInput: "pnpm test",
  9259. ruleContents: ["Bash(pnpm test:*)"],
  9260. allowAlwaysSupported: true,
  9261. },
  9262. ]);
  9263. const app = createTuiApp({
  9264. runtime,
  9265. terminal,
  9266. version: "0.1.0",
  9267. workspaceDir: "/workspace",
  9268. });
  9269. app.start();
  9270. await app.ready;
  9271. await app.submit("/resume session-pending");
  9272. expect(app.tui.hasOverlay()).toBe(false);
  9273. expect(app.interaction.isActive()).toBe(true);
  9274. terminal.input?.("3");
  9275. terminal.input?.("\r");
  9276. await vi.waitFor(() =>
  9277. expect(runtime.replyPermission).toHaveBeenCalledWith(
  9278. "mavis",
  9279. "permission-pending",
  9280. "deny",
  9281. ),
  9282. );
  9283. expect(app.tui.hasOverlay()).toBe(false);
  9284. expect(app.interaction.isActive()).toBe(false);
  9285. expect(app.transcript.get("permission:permission-pending")).toMatchObject({
  9286. status: "resolved",
  9287. detail: "Denied · bash",
  9288. });
  9289. expect(app.tui.render(80).join("\n")).not.toContain("Approval required");
  9290. await app.stop();
  9291. });
  9292. it("resolves a regular inline permission without clearing the terminal viewport", async () => {
  9293. const terminal = new FakeTerminal();
  9294. terminal.rows = 8;
  9295. const runtime = createRuntime();
  9296. vi.mocked(runtime.listSessions).mockResolvedValue([
  9297. {
  9298. sessionId: "session-permission-render",
  9299. title: "Permission render",
  9300. workspaceDir: "/workspace",
  9301. },
  9302. ]);
  9303. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  9304. {
  9305. requestId: "permission-render",
  9306. sessionId: "session-permission-render",
  9307. agentName: "mavis",
  9308. toolName: "bash",
  9309. toolInput: "pnpm test",
  9310. reason: "Run focused tests",
  9311. allowAlwaysSupported: true,
  9312. },
  9313. ]);
  9314. const app = createTuiApp({
  9315. runtime,
  9316. terminal,
  9317. version: "0.2.6",
  9318. workspaceDir: "/workspace",
  9319. tuiMode: "regular",
  9320. });
  9321. app.start();
  9322. await app.ready;
  9323. await app.submit("/resume session-permission-render");
  9324. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  9325. app.tui.renderNow();
  9326. terminal.writes.length = 0;
  9327. terminal.input?.("\r");
  9328. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  9329. await vi.waitFor(() => expect(terminal.writes.length).toBeGreaterThan(0));
  9330. expect(runtime.replyPermission).toHaveBeenCalledWith(
  9331. "mavis",
  9332. "permission-render",
  9333. "allowOnce",
  9334. );
  9335. expect(app.transcript.get("permission:permission-render")).toMatchObject({
  9336. status: "resolved",
  9337. detail: "Allowed for this conversation · bash",
  9338. });
  9339. expect(terminal.writes.join("")).not.toContain("\x1b[2J");
  9340. expect(terminal.writes.join("")).not.toContain("\x1b[3J");
  9341. await app.stop();
  9342. });
  9343. it("keeps a submission retryable when a pending decision blocks admission", async () => {
  9344. const terminal = new FakeTerminal();
  9345. const runtime = createRuntime();
  9346. vi.mocked(runtime.listSessions).mockResolvedValue([
  9347. {
  9348. sessionId: "session-draft-blocked",
  9349. title: "Pending decision",
  9350. workspaceDir: "/workspace",
  9351. },
  9352. ]);
  9353. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  9354. {
  9355. requestId: "permission-draft-blocked",
  9356. sessionId: "session-draft-blocked",
  9357. agentName: "mavis",
  9358. toolName: "bash",
  9359. allowAlwaysSupported: true,
  9360. },
  9361. ]);
  9362. const app = createTuiApp({
  9363. runtime,
  9364. terminal,
  9365. version: "0.1.0",
  9366. workspaceDir: "/workspace",
  9367. });
  9368. app.start();
  9369. await app.ready;
  9370. await app.submit("/resume session-draft-blocked");
  9371. app.editor.setText("Keep this draft for later");
  9372. app.editor.handleInput("\r");
  9373. await vi.waitFor(() => expect(app.editor.getText()).toBe(""));
  9374. expect(runtime.sendMessage).not.toHaveBeenCalled();
  9375. expect(app.tui.render(80).join("\n")).toContain("Approval required");
  9376. expect(app.tui.render(80).join("\n")).not.toContain("Message · Enter");
  9377. await app.stop();
  9378. });
  9379. it("keeps a pending questionnaire when Runtime rejects dismissal", async () => {
  9380. const terminal = new FakeTerminal();
  9381. const runtime = createRuntime();
  9382. vi.mocked(runtime.listSessions).mockResolvedValue([
  9383. {
  9384. sessionId: "session-existing",
  9385. title: "Existing session",
  9386. workspaceDir: "/workspace",
  9387. },
  9388. ]);
  9389. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9390. id: "question-rejected",
  9391. steps: [{ id: "step-1", question: "Proceed?" }],
  9392. });
  9393. vi.mocked(runtime.dismissQuestionnaire).mockResolvedValue(false);
  9394. const app = createTuiApp({
  9395. runtime,
  9396. terminal,
  9397. version: "0.1.0",
  9398. workspaceDir: "/workspace",
  9399. });
  9400. await app.ready;
  9401. await app.submit("/resume session-existing");
  9402. await app.submit("/ask-cancel");
  9403. expect(app.transcript.get("question:question-rejected")).toMatchObject({
  9404. status: "blocked",
  9405. });
  9406. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  9407. kind: "error",
  9408. content: "Couldn't dismiss this question. It remains open; retry.",
  9409. });
  9410. });
  9411. it("restores the questionnaire panel when an Escape dismissal request fails", async () => {
  9412. const runtime = createRuntime();
  9413. vi.mocked(runtime.listSessions).mockResolvedValue([
  9414. {
  9415. sessionId: "session-dismiss-retry",
  9416. title: "Dismiss retry",
  9417. workspaceDir: "/workspace",
  9418. },
  9419. ]);
  9420. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9421. id: "question-dismiss-retry",
  9422. steps: [
  9423. {
  9424. id: "step-1",
  9425. question: "Proceed?",
  9426. selectionMode: "single",
  9427. options: [{ id: "yes", label: "Yes" }],
  9428. },
  9429. ],
  9430. });
  9431. vi.mocked(runtime.dismissQuestionnaire).mockRejectedValue(
  9432. new Error("connection lost"),
  9433. );
  9434. const app = createTuiApp({
  9435. runtime,
  9436. terminal: new FakeTerminal(),
  9437. version: "0.1.0",
  9438. workspaceDir: "/workspace",
  9439. });
  9440. await app.ready;
  9441. await app.submit("/resume session-dismiss-retry");
  9442. app.interaction.current()?.handleInput("\u001b");
  9443. app.interaction.current()?.handleInput("\r");
  9444. await vi.waitFor(() =>
  9445. expect(runtime.dismissQuestionnaire).toHaveBeenCalledOnce(),
  9446. );
  9447. await vi.waitFor(() => {
  9448. const panel = app.interaction.current();
  9449. expect(panel).toBeDefined();
  9450. expect(panel?.render(80).join("\n")).toContain("Ask");
  9451. });
  9452. expect(app.transcript.get("question:question-dismiss-retry")).toMatchObject(
  9453. {
  9454. status: "blocked",
  9455. },
  9456. );
  9457. });
  9458. it("settles a questionnaire dismissal that already reached a terminal Runtime state", async () => {
  9459. const terminal = new FakeTerminal();
  9460. const runtime = createRuntime();
  9461. vi.mocked(runtime.listSessions).mockResolvedValue([
  9462. {
  9463. sessionId: "session-terminal-dismiss",
  9464. title: "Terminal dismissal",
  9465. workspaceDir: "/workspace",
  9466. },
  9467. ]);
  9468. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9469. id: "question-terminal-dismiss",
  9470. steps: [{ id: "step-1", question: "Proceed?" }],
  9471. });
  9472. vi.mocked(runtime.dismissQuestionnaire).mockRejectedValue(
  9473. Object.assign(new Error("already superseded"), {
  9474. status: 410,
  9475. code: "QUESTIONNAIRE_NOT_PENDING",
  9476. }),
  9477. );
  9478. const app = createTuiApp({
  9479. runtime,
  9480. terminal,
  9481. version: "0.1.0",
  9482. workspaceDir: "/workspace",
  9483. });
  9484. await app.ready;
  9485. await app.submit("/resume session-terminal-dismiss");
  9486. await app.submit("/ask-cancel");
  9487. expect(
  9488. app.transcript.get("question:question-terminal-dismiss"),
  9489. ).toMatchObject({
  9490. status: "resolved",
  9491. title: "Question closed",
  9492. detail: "Question is no longer pending.",
  9493. });
  9494. expect(app.interaction.isActive()).toBe(false);
  9495. });
  9496. it("projects live Desktop permission events into the transcript", async () => {
  9497. const terminal = new FakeTerminal();
  9498. const runtime = createRuntime();
  9499. vi.mocked(runtime.watchEvents).mockImplementation(
  9500. async function* watchEvents() {
  9501. yield runtimeEvent({
  9502. type: "permission.ask",
  9503. timestamp: 100,
  9504. source: "runtime",
  9505. payload: {
  9506. requestId: "permission-live",
  9507. sessionId: "session-1",
  9508. agentName: "mavis",
  9509. toolName: "bash",
  9510. toolDescription: "Run a shell command",
  9511. reason: "Run checks",
  9512. ruleContents: ["Bash(pnpm test:*)"],
  9513. allowAlwaysSupported: true,
  9514. },
  9515. });
  9516. },
  9517. );
  9518. const app = createTuiApp({
  9519. runtime,
  9520. terminal,
  9521. version: "0.1.0",
  9522. workspaceDir: "/workspace",
  9523. });
  9524. await app.ready;
  9525. await app.submit("Start the current session");
  9526. await app.submit("/transcript");
  9527. expect(app.surfaceHost.getActiveSurface()).toEqual({
  9528. kind: "feature",
  9529. id: "transcript",
  9530. });
  9531. app.start();
  9532. await vi.waitFor(() =>
  9533. expect(app.transcript.get("permission:permission-live")).toMatchObject({
  9534. kind: "permission",
  9535. status: "blocked",
  9536. content: expect.stringContaining("Run checks"),
  9537. }),
  9538. );
  9539. expect(app.transcript.get("permission:permission-live")).toMatchObject({
  9540. title: "bash",
  9541. content: "Run checks",
  9542. });
  9543. expect(
  9544. app.transcript.get("permission:permission-live")?.content,
  9545. ).not.toContain("Rules:");
  9546. expect(app.surfaceHost.getActiveSurface()).toEqual({
  9547. kind: "chat",
  9548. id: "chat",
  9549. });
  9550. await app.submit("/allow");
  9551. expect(app.surfaceHost.getActiveSurface()).toEqual({
  9552. kind: "feature",
  9553. id: "transcript",
  9554. });
  9555. await app.stop();
  9556. });
  9557. it("ignores Desktop interaction events until their session is active", async () => {
  9558. const terminal = new FakeTerminal();
  9559. const runtime = createRuntime();
  9560. let resolveEventsDelivered: (() => void) | undefined;
  9561. const eventsDelivered = new Promise<void>((resolve) => {
  9562. resolveEventsDelivered = resolve;
  9563. });
  9564. vi.mocked(runtime.watchEvents).mockImplementation(
  9565. async function* watchEvents(signal) {
  9566. yield runtimeEvent({
  9567. type: "permission.ask",
  9568. timestamp: 100,
  9569. source: "runtime",
  9570. payload: {
  9571. requestId: "permission-other-session",
  9572. sessionId: "session-other",
  9573. agentName: "mavis",
  9574. toolName: "bash",
  9575. },
  9576. });
  9577. yield runtimeEvent({
  9578. type: "questionnaire.ask",
  9579. timestamp: 101,
  9580. source: "runtime",
  9581. payload: {
  9582. sessionId: "session-other",
  9583. agentName: "mavis",
  9584. request: {
  9585. id: "question-other-session",
  9586. steps: [
  9587. { id: "step-1", question: "Proceed?", selectionMode: "single" },
  9588. ],
  9589. },
  9590. },
  9591. });
  9592. resolveEventsDelivered?.();
  9593. await new Promise<void>((resolve) => {
  9594. signal.addEventListener("abort", () => resolve(), { once: true });
  9595. });
  9596. },
  9597. );
  9598. const app = createTuiApp({
  9599. runtime,
  9600. terminal,
  9601. version: "0.1.0",
  9602. workspaceDir: "/workspace",
  9603. });
  9604. app.start();
  9605. await app.ready;
  9606. await eventsDelivered;
  9607. expect(
  9608. app.transcript.get("permission:permission-other-session"),
  9609. ).toBeUndefined();
  9610. expect(
  9611. app.transcript.get("question:question-other-session"),
  9612. ).toBeUndefined();
  9613. expect(
  9614. app.state.snapshot().sessions.get("session-other")?.interactions
  9615. .permission?.requestId,
  9616. ).toBe("permission-other-session");
  9617. expect(
  9618. app.state.snapshot().sessions.get("session-other")?.interactions
  9619. .questionnaire?.request.id,
  9620. ).toBe("question-other-session");
  9621. await app.stop();
  9622. });
  9623. it("surfaces only descendant permissions while keeping explicit Deny separate from Stop", async () => {
  9624. const terminal = new FakeTerminal();
  9625. const runtime = createRuntime();
  9626. const rootSession = {
  9627. sessionId: "session-root",
  9628. title: "Root session",
  9629. workspaceDir: "/workspace",
  9630. status: "started",
  9631. };
  9632. vi.mocked(runtime.listSessions).mockResolvedValue([rootSession]);
  9633. vi.mocked(runtime.getSession).mockResolvedValue(rootSession);
  9634. vi.mocked(runtime.getDelegationSnapshot).mockResolvedValue({
  9635. schemaVersion: 1,
  9636. rootSessionId: "session-root",
  9637. members: [
  9638. {
  9639. sessionId: "session-child",
  9640. parentSessionId: "session-root",
  9641. agentName: "worker",
  9642. task: "Delegate nested work",
  9643. status: "running",
  9644. },
  9645. {
  9646. sessionId: "session-grandchild",
  9647. parentSessionId: "session-child",
  9648. agentName: "verifier",
  9649. task: "Verify the result",
  9650. status: "running",
  9651. },
  9652. ],
  9653. });
  9654. vi.mocked(runtime.getActiveRun).mockImplementation(
  9655. async (sessionId: string) => ({
  9656. schemaVersion: 1,
  9657. sessionId,
  9658. state:
  9659. sessionId === rootSession.sessionId ? "decision-blocked" : "running",
  9660. turnId:
  9661. sessionId === rootSession.sessionId
  9662. ? "turn-root"
  9663. : `turn-${sessionId}`,
  9664. actions: { steer: false },
  9665. }),
  9666. );
  9667. const deniedPermissionIds = new Set<string>();
  9668. vi.mocked(runtime.replyPermission).mockImplementation(
  9669. async (_agentName, requestId) => {
  9670. deniedPermissionIds.add(requestId);
  9671. return true;
  9672. },
  9673. );
  9674. vi.mocked(runtime.listPendingPermissions).mockImplementation(async () =>
  9675. deniedPermissionIds.has("permission-grandchild")
  9676. ? [
  9677. {
  9678. requestId: "permission-unrelated-next",
  9679. sessionId: "session-unrelated",
  9680. agentName: "worker",
  9681. toolName: "bash",
  9682. reason: "Must remain hidden",
  9683. },
  9684. {
  9685. requestId: deniedPermissionIds.has("permission-child-next")
  9686. ? "permission-child-stop"
  9687. : "permission-child-next",
  9688. sessionId: "session-child",
  9689. agentName: "worker",
  9690. toolName: "read",
  9691. reason: deniedPermissionIds.has("permission-child-next")
  9692. ? "Wait for an explicit Stop"
  9693. : "Inspect the delegated output",
  9694. },
  9695. ]
  9696. : [],
  9697. );
  9698. vi.mocked(runtime.watchEvents).mockImplementation(
  9699. async function* watchEvents(signal) {
  9700. yield runtimeEvent({
  9701. type: "permission.ask",
  9702. timestamp: 100,
  9703. source: "runtime",
  9704. payload: {
  9705. requestId: "permission-unrelated",
  9706. sessionId: "session-unrelated",
  9707. agentName: "worker",
  9708. toolName: "bash",
  9709. reason: "Must stay hidden",
  9710. },
  9711. });
  9712. yield runtimeEvent({
  9713. type: "permission.ask",
  9714. timestamp: 101,
  9715. source: "runtime",
  9716. payload: {
  9717. requestId: "permission-grandchild",
  9718. sessionId: "session-grandchild",
  9719. agentName: "verifier",
  9720. toolName: "write",
  9721. reason: "Update the verification report",
  9722. allowAlwaysSupported: true,
  9723. },
  9724. });
  9725. await new Promise<void>((resolve) => {
  9726. signal.addEventListener("abort", resolve, { once: true });
  9727. });
  9728. },
  9729. );
  9730. const app = createTuiApp({
  9731. runtime,
  9732. terminal,
  9733. version: "0.1.0",
  9734. workspaceDir: "/workspace",
  9735. });
  9736. await app.ready;
  9737. await app.submit("/resume session-root");
  9738. vi.mocked(runtime.abortSession).mockClear();
  9739. vi.mocked(runtime.stopDelegation).mockClear();
  9740. app.start();
  9741. await vi.waitFor(() =>
  9742. expect(
  9743. app.transcript.get("permission:permission-grandchild"),
  9744. ).toMatchObject({
  9745. kind: "permission",
  9746. status: "blocked",
  9747. }),
  9748. );
  9749. expect(
  9750. app.transcript.get("permission:permission-unrelated"),
  9751. ).toBeUndefined();
  9752. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9753. "Update the verification report",
  9754. );
  9755. app.interaction.current()?.handleInput?.("3");
  9756. app.interaction.current()?.handleInput?.("\r");
  9757. await vi.waitFor(() =>
  9758. expect(runtime.replyPermission).toHaveBeenCalledWith(
  9759. "verifier",
  9760. "permission-grandchild",
  9761. "deny",
  9762. ),
  9763. );
  9764. expect(runtime.stopDelegation).not.toHaveBeenCalled();
  9765. expect(runtime.abortSession).not.toHaveBeenCalled();
  9766. await vi.waitFor(() =>
  9767. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9768. "Inspect the delegated output",
  9769. ),
  9770. );
  9771. expect(
  9772. app.transcript.get("permission:permission-unrelated-next"),
  9773. ).toBeUndefined();
  9774. terminal.input?.("\x1b");
  9775. await vi.waitFor(() =>
  9776. expect(runtime.replyPermission).toHaveBeenCalledWith(
  9777. "worker",
  9778. "permission-child-next",
  9779. "deny",
  9780. ),
  9781. );
  9782. expect(runtime.abortSession).not.toHaveBeenCalled();
  9783. expect(runtime.stopDelegation).not.toHaveBeenCalled();
  9784. await vi.waitFor(() =>
  9785. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9786. "Wait for an explicit Stop",
  9787. ),
  9788. );
  9789. terminal.input?.("\x03");
  9790. await vi.waitFor(() =>
  9791. expect(runtime.abortSession).toHaveBeenCalledWith({
  9792. id: rootSession.sessionId,
  9793. turnId: "turn-root",
  9794. reason: "user_stop",
  9795. }),
  9796. );
  9797. expect(runtime.stopDelegation).toHaveBeenCalledOnce();
  9798. expect(runtime.stopDelegation).toHaveBeenCalledWith(rootSession.sessionId);
  9799. expect(runtime.replyPermission).not.toHaveBeenCalledWith(
  9800. "worker",
  9801. "permission-child-stop",
  9802. "deny",
  9803. );
  9804. await app.stop();
  9805. });
  9806. it("recovers a descendant permission from the Runtime pending list without leaking unrelated requests", async () => {
  9807. const runtime = createRuntime();
  9808. const rootSession = {
  9809. sessionId: "session-recovery-root",
  9810. title: "Recovery root",
  9811. workspaceDir: "/workspace",
  9812. };
  9813. vi.mocked(runtime.listSessions).mockResolvedValue([rootSession]);
  9814. vi.mocked(runtime.getSession).mockResolvedValue(rootSession);
  9815. vi.mocked(runtime.getDelegationSnapshot).mockResolvedValue({
  9816. schemaVersion: 1,
  9817. rootSessionId: rootSession.sessionId,
  9818. members: [
  9819. {
  9820. sessionId: "session-recovery-child",
  9821. parentSessionId: rootSession.sessionId,
  9822. agentName: "worker",
  9823. task: "Resume delegated work",
  9824. status: "running",
  9825. },
  9826. ],
  9827. });
  9828. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  9829. {
  9830. requestId: "permission-recovery-unrelated",
  9831. sessionId: "session-other-root",
  9832. agentName: "worker",
  9833. toolName: "bash",
  9834. reason: "Do not show this request",
  9835. },
  9836. {
  9837. requestId: "permission-recovery-child",
  9838. sessionId: "session-recovery-child",
  9839. agentName: "worker",
  9840. toolName: "write",
  9841. reason: "Resume the child request",
  9842. },
  9843. ]);
  9844. const app = createTuiApp({
  9845. runtime,
  9846. terminal: new FakeTerminal(),
  9847. version: "0.1.0",
  9848. workspaceDir: "/workspace",
  9849. });
  9850. await app.ready;
  9851. await app.submit("/resume session-recovery-root");
  9852. expect(
  9853. app.transcript.get("permission:permission-recovery-child"),
  9854. ).toMatchObject({
  9855. kind: "permission",
  9856. status: "blocked",
  9857. });
  9858. expect(
  9859. app.transcript.get("permission:permission-recovery-unrelated"),
  9860. ).toBeUndefined();
  9861. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9862. "Resume the child request",
  9863. );
  9864. await app.stop();
  9865. });
  9866. it("reconnects the Runtime event stream after a transient disconnect", async () => {
  9867. const terminal = new FakeTerminal();
  9868. const runtime = createRuntime();
  9869. const observability = createObservability();
  9870. let attempt = 0;
  9871. vi.mocked(runtime.watchEvents).mockImplementation(
  9872. async function* watchEvents() {
  9873. attempt += 1;
  9874. if (attempt === 1) throw new Error("connection reset");
  9875. yield runtimeEvent({
  9876. type: "permission.ask",
  9877. timestamp: 101,
  9878. source: "runtime",
  9879. payload: {
  9880. requestId: "permission-after-reconnect",
  9881. sessionId: "session-1",
  9882. toolName: "read",
  9883. },
  9884. });
  9885. },
  9886. );
  9887. const app = createTuiApp({
  9888. runtime,
  9889. terminal,
  9890. version: "0.1.0",
  9891. workspaceDir: "/workspace",
  9892. observability,
  9893. });
  9894. await app.ready;
  9895. await app.submit("Start the current session");
  9896. app.start();
  9897. await vi.waitFor(
  9898. () =>
  9899. expect(
  9900. app.transcript.get("permission:permission-after-reconnect"),
  9901. ).toMatchObject({
  9902. status: "blocked",
  9903. }),
  9904. { timeout: 1500 },
  9905. );
  9906. expect(runtime.watchEvents).toHaveBeenCalledTimes(2);
  9907. expect(observability.recordEventStream).toHaveBeenCalledWith(
  9908. expect.objectContaining({
  9909. state: "retry-scheduled",
  9910. attempt: 1,
  9911. retryDelayMs: 250,
  9912. errorKind: "Error",
  9913. }),
  9914. );
  9915. expect(observability.recordEventStream).toHaveBeenCalledWith(
  9916. expect.objectContaining({
  9917. state: "reconnected",
  9918. attempt: 1,
  9919. downtimeMs: expect.any(Number),
  9920. }),
  9921. );
  9922. expect(app.transcript.snapshot()).not.toEqual(
  9923. expect.arrayContaining([
  9924. expect.objectContaining({
  9925. kind: "warning",
  9926. content: expect.stringContaining("Runtime event stream"),
  9927. }),
  9928. ]),
  9929. );
  9930. await app.stop();
  9931. });
  9932. it("sends pasted local attachments and restores failed sends to the Composer", async () => {
  9933. const terminal = new FakeTerminal();
  9934. const runtime = createRuntime();
  9935. const readClipboardImage = vi.fn(async () => ({
  9936. attachment: {
  9937. type: "image" as const,
  9938. filePath: "/tmp/minimax-code-clipboard/diagram.png",
  9939. fileName: "diagram.png",
  9940. mimeType: "image/png",
  9941. sizeBytes: 2048,
  9942. },
  9943. dispose: vi.fn(async () => undefined),
  9944. }));
  9945. const app = createTuiApp({
  9946. runtime,
  9947. terminal,
  9948. version: "0.1.0",
  9949. workspaceDir: "/workspace",
  9950. readClipboardImage,
  9951. readClipboardText: async () => null,
  9952. });
  9953. app.start();
  9954. await app.ready;
  9955. terminal.input?.("\u001bv");
  9956. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(1));
  9957. await app.submit("Inspect the diagram");
  9958. expect(runtime.sendMessage).toHaveBeenCalledWith(
  9959. expect.objectContaining({
  9960. id: "session-1",
  9961. content: "Inspect the diagram",
  9962. attachments: [
  9963. expect.objectContaining({
  9964. local: { filePath: "/tmp/minimax-code-clipboard/diagram.png" },
  9965. meta: expect.objectContaining({ mimeType: "image/png" }),
  9966. }),
  9967. ],
  9968. }),
  9969. expect.any(AbortSignal),
  9970. );
  9971. expect(app.tui.render(80).join("\n")).not.toContain("[Image #1]");
  9972. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  9973. async function* sendMessage() {
  9974. yield { type: "error", message: "provider unavailable" };
  9975. },
  9976. );
  9977. terminal.input?.("\x16");
  9978. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(2));
  9979. app.editor.setText("Try again");
  9980. app.editor.handleInput("\r");
  9981. await vi.waitFor(() => expect(app.editor.getText()).toContain("Try again"));
  9982. expect(app.tui.render(80).join("\n")).toContain(
  9983. "Error The model provider is temporarily unavailable.",
  9984. );
  9985. expect(app.tui.render(80).join("\n")).not.toContain("Request failed");
  9986. expect(app.editor.getText()).toContain("[Image #1]");
  9987. expect(app.tui.render(80).join("\n")).not.toContain(
  9988. "Message kept under Failed",
  9989. );
  9990. await app.submit("/retry");
  9991. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  9992. expect.objectContaining({
  9993. content: "Try again",
  9994. attachments: [
  9995. expect.objectContaining({
  9996. local: { filePath: "/tmp/minimax-code-clipboard/diagram.png" },
  9997. }),
  9998. ],
  9999. }),
  10000. expect.any(AbortSignal),
  10001. );
  10002. await app.submit("A fresh turn");
  10003. expect(app.tui.render(80).join("\n")).not.toContain("Couldn't send");
  10004. await app.stop();
  10005. });
  10006. it.each([
  10007. ['content', 'Content review withdrew this response. Rephrase your request, then retry.'],
  10008. ['network', 'Content review did not return a usable result, so this response stopped.'],
  10009. ] as const)("presents a %s review stop without a failed Queue item", async (variant, notice) => {
  10010. const terminal = new FakeTerminal();
  10011. const runtime = createRuntime();
  10012. const busEvents: TuiRuntimeEvent[] = [];
  10013. let wakeBus: (() => void) | undefined;
  10014. vi.mocked(runtime.watchEvents).mockImplementation(
  10015. async function* watchEvents(signal) {
  10016. while (!signal.aborted) {
  10017. if (busEvents.length === 0) {
  10018. await new Promise<void>((resolve) => {
  10019. wakeBus = resolve;
  10020. signal.addEventListener("abort", resolve, { once: true });
  10021. });
  10022. }
  10023. const event = busEvents.shift();
  10024. if (event) yield event;
  10025. }
  10026. },
  10027. );
  10028. let releaseTurn: (() => void) | undefined;
  10029. vi.mocked(runtime.sendMessage).mockImplementation(
  10030. async function* sendMessage() {
  10031. await new Promise<void>((resolve) => {
  10032. releaseTurn = resolve;
  10033. });
  10034. yield { type: "done" };
  10035. },
  10036. );
  10037. const app = createTuiApp({
  10038. runtime,
  10039. terminal,
  10040. version: "0.1.0",
  10041. workspaceDir: "/workspace",
  10042. });
  10043. app.start();
  10044. await app.ready;
  10045. terminal.input?.("review this response");
  10046. terminal.input?.("\r");
  10047. await vi.waitFor(() =>
  10048. expect(app.controller.snapshot().activeTurnId).toBeTruthy(),
  10049. );
  10050. busEvents.push(
  10051. runtimeEvent({
  10052. type: "content.retry.exceeded",
  10053. timestamp: 100,
  10054. source: "runtime-v2",
  10055. payload: { sessionId: "session-1", variant },
  10056. }),
  10057. runtimeEvent({
  10058. type: "message.rewind",
  10059. timestamp: 101,
  10060. source: "runtime-v2",
  10061. payload: { sessionId: "session-1", contextReset: true },
  10062. }),
  10063. );
  10064. wakeBus?.();
  10065. releaseTurn?.();
  10066. await vi.waitFor(() =>
  10067. expect(app.editor.getText()).toBe("review this response"),
  10068. );
  10069. const rendered = app.tui.render(100).join("\n");
  10070. expect(rendered).toContain(notice);
  10071. expect(rendered).not.toContain('Check your network');
  10072. expect(rendered).not.toContain("Message kept under Failed");
  10073. await app.submit("/queue");
  10074. expect(app.interaction.current()).toBeUndefined();
  10075. await app.stop();
  10076. });
  10077. it("sends editable @directory/ input as ordinary text", async () => {
  10078. const terminal = new FakeTerminal();
  10079. const runtime = createRuntime();
  10080. const app = createTuiApp({
  10081. runtime,
  10082. terminal,
  10083. version: "0.1.0",
  10084. workspaceDir: "/workspace",
  10085. });
  10086. await app.submit("Review @src/");
  10087. expect(runtime.sendMessage).toHaveBeenCalledWith(
  10088. { id: "session-1", content: "Review @src/", turnId: expect.any(String) },
  10089. expect.any(AbortSignal),
  10090. );
  10091. await expect(app.submit("Review @generated/")).resolves.toBeUndefined();
  10092. expect(runtime.sendMessage).toHaveBeenCalledTimes(2);
  10093. });
  10094. it("pastes a clipboard image without replacing the text draft and cleans it after send", async () => {
  10095. const terminal = new FakeTerminal();
  10096. const runtime = createRuntime();
  10097. const dispose = vi.fn(async () => undefined);
  10098. const readClipboardImage = vi.fn(async () => ({
  10099. attachment: {
  10100. type: "image" as const,
  10101. filePath: "/tmp/minimax-code-clipboard/clipboard-1.png",
  10102. fileName: "clipboard-1.png",
  10103. mimeType: "image/png",
  10104. sizeBytes: 4096,
  10105. },
  10106. dispose,
  10107. }));
  10108. const app = createTuiApp({
  10109. runtime,
  10110. terminal,
  10111. version: "0.1.0",
  10112. workspaceDir: "/workspace",
  10113. readClipboardImage,
  10114. readClipboardText: async () => null,
  10115. });
  10116. app.start();
  10117. await app.ready;
  10118. app.editor.setText("Keep this draft");
  10119. terminal.input?.("\u001B[118;9u");
  10120. terminal.input?.("\u001B[118;9:3u");
  10121. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledOnce());
  10122. await vi.waitFor(() =>
  10123. expect(app.editor.getText()).toContain("[Image #1]"),
  10124. );
  10125. expect(app.editor.getText()).toBe("Keep this draft [Image #1] ");
  10126. expect(app.tui.render(100).join("\n")).not.toContain(
  10127. "A clipboard media paste is already in progress.",
  10128. );
  10129. await app.submit("Keep this draft");
  10130. expect(runtime.sendMessage).toHaveBeenCalledWith(
  10131. expect.objectContaining({
  10132. id: "session-1",
  10133. content: "Keep this draft",
  10134. attachments: [
  10135. expect.objectContaining({
  10136. local: { filePath: "/tmp/minimax-code-clipboard/clipboard-1.png" },
  10137. meta: expect.objectContaining({ mimeType: "image/png" }),
  10138. }),
  10139. ],
  10140. }),
  10141. expect.any(AbortSignal),
  10142. );
  10143. expect(dispose).toHaveBeenCalledOnce();
  10144. await app.stop();
  10145. });
  10146. it("retains existing draft state when clipboard read or send fails", async () => {
  10147. const terminal = new FakeTerminal();
  10148. const runtime = createRuntime();
  10149. const dispose = vi.fn(async () => undefined);
  10150. const readClipboardImage = vi
  10151. .fn()
  10152. .mockResolvedValueOnce({
  10153. attachment: {
  10154. type: "image" as const,
  10155. filePath: "/tmp/minimax-code-clipboard/clipboard-2.png",
  10156. fileName: "clipboard-2.png",
  10157. mimeType: "image/png",
  10158. sizeBytes: 1024,
  10159. },
  10160. dispose,
  10161. })
  10162. .mockRejectedValueOnce(new Error("clipboard has no image"));
  10163. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  10164. async function* sendMessage() {
  10165. yield { type: "error", message: "provider unavailable" };
  10166. },
  10167. );
  10168. const app = createTuiApp({
  10169. runtime,
  10170. terminal,
  10171. version: "0.1.0",
  10172. workspaceDir: "/workspace",
  10173. readClipboardImage,
  10174. readClipboardText: async () => null,
  10175. });
  10176. app.start();
  10177. await app.ready;
  10178. app.editor.setText("Do not clear me");
  10179. terminal.input?.("\x16");
  10180. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(1));
  10181. terminal.input?.("\x16");
  10182. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(2));
  10183. expect(app.editor.getText()).toBe("Do not clear me [Image #1] ");
  10184. await app.submit("Try the image");
  10185. expect(dispose).not.toHaveBeenCalled();
  10186. expect(app.tui.render(80).join("\n")).toContain("[Image #1]");
  10187. terminal.input?.("\x7f");
  10188. expect(app.tui.render(80).join("\n")).not.toContain("[Image #1]");
  10189. expect(dispose).not.toHaveBeenCalled();
  10190. await app.stop();
  10191. expect(dispose).toHaveBeenCalledOnce();
  10192. });
  10193. it("cancels an in-flight clipboard read with Ctrl+C and keeps the draft", async () => {
  10194. const terminal = new FakeTerminal();
  10195. const runtime = createRuntime();
  10196. let observedSignal: AbortSignal | undefined;
  10197. const readClipboardImage = vi.fn(
  10198. async (signal?: AbortSignal) =>
  10199. await new Promise<never>((_resolve, reject) => {
  10200. observedSignal = signal;
  10201. signal?.addEventListener(
  10202. "abort",
  10203. () => reject(new Error("cancelled")),
  10204. { once: true },
  10205. );
  10206. }),
  10207. );
  10208. const app = createTuiApp({
  10209. runtime,
  10210. terminal,
  10211. version: "0.1.0",
  10212. workspaceDir: "/workspace",
  10213. readClipboardImage,
  10214. readClipboardText: async () => null,
  10215. });
  10216. app.start();
  10217. await app.ready;
  10218. app.editor.setText("Draft survives");
  10219. terminal.input?.("\x16");
  10220. await vi.waitFor(() => expect(observedSignal).toBeDefined());
  10221. terminal.input?.("\x03");
  10222. await vi.waitFor(() => expect(observedSignal?.aborted).toBe(true));
  10223. expect(app.editor.getText()).toBe("Draft survives");
  10224. await app.stop();
  10225. });
  10226. it("keeps queued clipboard files alive until the Runtime reports a terminal queue state", async () => {
  10227. const terminal = new FakeTerminal();
  10228. const runtime = createRuntime();
  10229. const dispose = vi.fn(async () => undefined);
  10230. let finishTurn: (() => void) | undefined;
  10231. let deliverQueueEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  10232. vi.mocked(runtime.sendMessage).mockImplementation(
  10233. async function* sendMessage() {
  10234. await new Promise<void>((resolve) => {
  10235. finishTurn = resolve;
  10236. });
  10237. yield { type: "done" };
  10238. },
  10239. );
  10240. vi.mocked(runtime.watchEvents).mockImplementation(
  10241. async function* watchEvents() {
  10242. const event = await new Promise<TuiRuntimeEvent>((resolve) => {
  10243. deliverQueueEvent = resolve;
  10244. });
  10245. yield event;
  10246. },
  10247. );
  10248. const readClipboardImage = vi.fn(async () => ({
  10249. attachment: {
  10250. type: "image" as const,
  10251. filePath: "/tmp/minimax-code-clipboard/clipboard-queue.png",
  10252. fileName: "clipboard-queue.png",
  10253. mimeType: "image/png",
  10254. sizeBytes: 2048,
  10255. },
  10256. dispose,
  10257. }));
  10258. const app = createTuiApp({
  10259. runtime,
  10260. terminal,
  10261. version: "0.1.0",
  10262. workspaceDir: "/workspace",
  10263. productFeatures: { queue: true },
  10264. readClipboardImage,
  10265. });
  10266. app.start();
  10267. await app.ready;
  10268. const first = app.submit("First turn");
  10269. await vi.waitFor(() =>
  10270. expect(app.controller.snapshot().status).toBe("running"),
  10271. );
  10272. terminal.input?.("\x16");
  10273. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledOnce());
  10274. await app.submit("Queued with image");
  10275. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  10276. "session-1",
  10277. "Queued with image",
  10278. expect.objectContaining({
  10279. attachments: [
  10280. expect.objectContaining({ fileName: "clipboard-queue.png" }),
  10281. ],
  10282. }),
  10283. );
  10284. expect(dispose).not.toHaveBeenCalled();
  10285. deliverQueueEvent?.(
  10286. runtimeEvent({
  10287. type: "session.queue.updated",
  10288. timestamp: Date.now(),
  10289. source: "runtime",
  10290. payload: {
  10291. sessionId: "session-1",
  10292. itemId: "queue-1",
  10293. status: "completed",
  10294. queuedCount: 0,
  10295. },
  10296. }),
  10297. );
  10298. await vi.waitFor(() => expect(dispose).toHaveBeenCalledOnce());
  10299. finishTurn?.();
  10300. await first;
  10301. await app.stop();
  10302. });
  10303. it("opens the Desktop model picker and applies the selected session model", async () => {
  10304. const terminal = new FakeTerminal();
  10305. const runtime = createRuntime();
  10306. vi.mocked(runtime.listModels).mockResolvedValue([
  10307. {
  10308. providerId: "minimax",
  10309. modelId: "MiniMax-M3",
  10310. displayName: "MiniMax M3",
  10311. variant: "thinking",
  10312. thinkingConfig: { mode: "switchable", defaultValue: "true" },
  10313. providerKind: "minimax-managed",
  10314. selected: true,
  10315. },
  10316. ]);
  10317. const app = createTuiApp({
  10318. runtime,
  10319. terminal,
  10320. version: "0.1.0",
  10321. workspaceDir: "/workspace",
  10322. });
  10323. app.start();
  10324. await app.ready;
  10325. await app.submit("Create a session");
  10326. await app.submit("/model");
  10327. expect(app.tui.hasOverlay()).toBe(false);
  10328. expect(app.interaction.isActive()).toBe(true);
  10329. terminal.input?.("\x1b");
  10330. expect(app.tui.hasOverlay()).toBe(false);
  10331. await app.submit("/model");
  10332. terminal.input?.("\r");
  10333. await vi.waitFor(() =>
  10334. expect(runtime.selectModel).toHaveBeenCalledWith(
  10335. expect.objectContaining({
  10336. providerId: "minimax",
  10337. modelId: "MiniMax-M3",
  10338. variant: "thinking",
  10339. }),
  10340. "session-1",
  10341. ),
  10342. );
  10343. await vi.waitFor(() => {
  10344. const rendered = app.tui.render(120).join("\n");
  10345. expect(rendered).toContain("✦ MiniMax M3");
  10346. expect(rendered).toContain("Thinking On");
  10347. expect(rendered).not.toContain("MiniMax M3#thinking");
  10348. });
  10349. await app.stop();
  10350. });
  10351. it("queues a thinking-on model with the configured effort even when the Session stored none", async () => {
  10352. const terminal = new FakeTerminal();
  10353. const runtime = createRuntime();
  10354. let finishTurn: (() => void) | undefined;
  10355. vi.mocked(runtime.listModels).mockResolvedValue([
  10356. {
  10357. providerId: "minimax",
  10358. modelId: "deep-reasoner-1",
  10359. displayName: "deep-reasoner-1",
  10360. selected: true,
  10361. variant: "thinking",
  10362. thinkingConfig: { mode: "switchable", defaultValue: "true" },
  10363. effortOptions: ["xhigh"],
  10364. },
  10365. ]);
  10366. vi.mocked(runtime.sendMessage).mockImplementation(
  10367. async function* sendMessage() {
  10368. await new Promise<void>((resolve) => {
  10369. finishTurn = resolve;
  10370. });
  10371. yield { type: "done" };
  10372. },
  10373. );
  10374. const app = createTuiApp({
  10375. runtime,
  10376. terminal,
  10377. version: "0.1.0",
  10378. workspaceDir: "/workspace",
  10379. productFeatures: { queue: true },
  10380. });
  10381. app.start();
  10382. await app.ready;
  10383. const first = app.submit("First turn");
  10384. await vi.waitFor(() =>
  10385. expect(app.controller.snapshot().status).toBe("running"),
  10386. );
  10387. await app.submit("Queued turn");
  10388. // The Session echo carries no stored effort, so the per-Turn selection has to
  10389. // resolve the configured level. Sending only `variant: thinking` makes Runtime
  10390. // drop the effort and the provider apply its own default.
  10391. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  10392. "session-1",
  10393. "Queued turn",
  10394. expect.objectContaining({
  10395. model: expect.objectContaining({
  10396. providerId: "minimax",
  10397. modelId: "deep-reasoner-1",
  10398. variant: "thinking",
  10399. thinking: { effort: "xhigh" },
  10400. }),
  10401. }),
  10402. );
  10403. finishTurn?.();
  10404. await first;
  10405. await app.stop();
  10406. });
  10407. it("applies a welcome-screen effort to the new Session before sending its first message", async () => {
  10408. const terminal = new FakeTerminal();
  10409. const runtime = createRuntime();
  10410. vi.mocked(runtime.listModels).mockResolvedValue([
  10411. {
  10412. providerId: "custom_provider:byok",
  10413. modelId: "byok-large-5",
  10414. displayName: "BYOK Large 5",
  10415. selected: true,
  10416. variant: "",
  10417. thinkingConfig: { mode: "switchable", defaultValue: "false" },
  10418. effortOptions: ["low", "medium", "high"],
  10419. },
  10420. ]);
  10421. let releaseDefaultSelection: ((selected: boolean) => void) | undefined;
  10422. let releaseSessionSelection: ((selected: boolean) => void) | undefined;
  10423. vi.mocked(runtime.selectModel)
  10424. .mockImplementationOnce(
  10425. async () =>
  10426. await new Promise<boolean>((resolve) => {
  10427. releaseDefaultSelection = resolve;
  10428. }),
  10429. )
  10430. .mockImplementationOnce(
  10431. async () =>
  10432. await new Promise<boolean>((resolve) => {
  10433. releaseSessionSelection = resolve;
  10434. }),
  10435. );
  10436. const app = createTuiApp({
  10437. runtime,
  10438. terminal,
  10439. version: "0.1.0",
  10440. workspaceDir: "/workspace",
  10441. });
  10442. app.start();
  10443. await app.ready;
  10444. await app.submit("/model");
  10445. terminal.input?.("\u001b[C");
  10446. terminal.input?.("\r");
  10447. const firstTurn = app.submit("First turn");
  10448. await vi.waitFor(() =>
  10449. expect(runtime.selectModel).toHaveBeenNthCalledWith(
  10450. 1,
  10451. expect.objectContaining({ thinking: { effort: "high" }, variant: "" }),
  10452. undefined,
  10453. ),
  10454. );
  10455. expect(runtime.selectModel).toHaveBeenCalledOnce();
  10456. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10457. releaseDefaultSelection?.(true);
  10458. await vi.waitFor(() =>
  10459. expect(runtime.selectModel).toHaveBeenNthCalledWith(
  10460. 2,
  10461. expect.objectContaining({ thinking: { effort: "high" }, variant: "" }),
  10462. "session-1",
  10463. ),
  10464. );
  10465. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10466. releaseSessionSelection?.(true);
  10467. await firstTurn;
  10468. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  10469. expect(runtime.selectModel.mock.invocationCallOrder[1]).toBeLessThan(
  10470. runtime.sendMessage.mock.invocationCallOrder[0] ??
  10471. Number.POSITIVE_INFINITY,
  10472. );
  10473. await app.stop();
  10474. });
  10475. it("does not send the first message when Runtime rejects its pending effort", async () => {
  10476. const terminal = new FakeTerminal();
  10477. const runtime = createRuntime();
  10478. vi.mocked(runtime.listModels).mockResolvedValue([
  10479. {
  10480. providerId: "custom_provider:byok",
  10481. modelId: "byok-large-5",
  10482. displayName: "BYOK Large 5",
  10483. selected: true,
  10484. effortOptions: ["low", "medium", "high"],
  10485. },
  10486. ]);
  10487. vi.mocked(runtime.selectModel)
  10488. .mockResolvedValueOnce(true)
  10489. .mockResolvedValueOnce(false);
  10490. const app = createTuiApp({
  10491. runtime,
  10492. terminal,
  10493. version: "0.1.0",
  10494. workspaceDir: "/workspace",
  10495. });
  10496. app.start();
  10497. await app.ready;
  10498. await app.submit("/model");
  10499. terminal.input?.("\r");
  10500. await vi.waitFor(() => expect(runtime.selectModel).toHaveBeenCalledOnce());
  10501. await app.submit("First turn");
  10502. expect(runtime.selectModel).toHaveBeenCalledTimes(2);
  10503. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10504. await app.stop();
  10505. });
  10506. it("lets Escape cancel the first turn while Desktop is creating its session", async () => {
  10507. const terminal = new FakeTerminal();
  10508. const runtime = createRuntime();
  10509. let finishSessionCreation:
  10510. | ((session: { sessionId: string; workspaceDir: string }) => void)
  10511. | undefined;
  10512. vi.mocked(runtime.createSession).mockImplementation(
  10513. async () =>
  10514. await new Promise<{ sessionId: string; workspaceDir: string }>(
  10515. (resolve) => {
  10516. finishSessionCreation = resolve;
  10517. },
  10518. ),
  10519. );
  10520. const app = createTuiApp({
  10521. runtime,
  10522. terminal,
  10523. version: "0.1.0",
  10524. workspaceDir: "/workspace",
  10525. });
  10526. app.start();
  10527. await app.ready;
  10528. const submitting = app.submit("Wait for the session");
  10529. await vi.waitFor(() =>
  10530. expect(app.controller.snapshot()).toMatchObject({
  10531. status: "starting",
  10532. activeTurnId: expect.any(String),
  10533. }),
  10534. );
  10535. expect(app.tui.render(80).join("\n")).toContain("Loading");
  10536. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  10537. expect(app.tui.render(80).join("\n")).not.toContain("MCode ·");
  10538. terminal.input?.("\x1b");
  10539. await vi.waitFor(() =>
  10540. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  10541. );
  10542. finishSessionCreation?.({
  10543. sessionId: "session-created",
  10544. workspaceDir: "/workspace",
  10545. });
  10546. await submitting;
  10547. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10548. expect(app.transcript.snapshot()).toEqual(
  10549. expect.arrayContaining([
  10550. expect.objectContaining({ kind: "assistant", status: "cancelled" }),
  10551. ]),
  10552. );
  10553. await app.stop();
  10554. });
  10555. it("restores a submission attempted while the previous cancellation fence is active", async () => {
  10556. const terminal = new FakeTerminal();
  10557. const runtime = createRuntime();
  10558. let releaseCancelledStream: (() => void) | undefined;
  10559. let sendCount = 0;
  10560. vi.mocked(runtime.sendMessage).mockImplementation(
  10561. async function* sendMessage(_req: SendMessageReq, signal?: AbortSignal) {
  10562. sendCount += 1;
  10563. if (sendCount === 1) {
  10564. await new Promise<void>((resolve) => {
  10565. signal?.addEventListener("abort", resolve, { once: true });
  10566. });
  10567. await new Promise<void>((resolve) => {
  10568. releaseCancelledStream = resolve;
  10569. });
  10570. } else {
  10571. yield { type: "delta", content: "Second response" };
  10572. }
  10573. yield { type: "done" };
  10574. },
  10575. );
  10576. vi.mocked(runtime.abortSession).mockImplementation(async () => {
  10577. setTimeout(() => releaseCancelledStream?.(), 10);
  10578. return true;
  10579. });
  10580. const app = createTuiApp({
  10581. runtime,
  10582. terminal,
  10583. version: "0.1.0",
  10584. workspaceDir: "/workspace",
  10585. });
  10586. app.start();
  10587. await app.ready;
  10588. terminal.input?.("First request");
  10589. terminal.input?.("\r");
  10590. await vi.waitFor(() =>
  10591. expect(app.controller.snapshot().status).toBe("running"),
  10592. );
  10593. terminal.input?.("\x1b");
  10594. await vi.waitFor(() =>
  10595. expect(app.controller.snapshot().cancelling).toBe(true),
  10596. );
  10597. terminal.input?.("Second request");
  10598. terminal.input?.("\r");
  10599. await vi.waitFor(() => expect(app.editor.getText()).toBe("Second request"));
  10600. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  10601. await vi.waitFor(() =>
  10602. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  10603. );
  10604. await vi.waitFor(() =>
  10605. expect(app.controller.snapshot().retiringTurnId).toBeUndefined(),
  10606. );
  10607. expect(app.controller.snapshot().cancelling).toBe(false);
  10608. expect(app.tui.render(80).join("\n")).not.toContain(
  10609. "Stopping the current response",
  10610. );
  10611. app.editor.handleInput("\r");
  10612. await vi.waitFor(() =>
  10613. expect(runtime.sendMessage).toHaveBeenCalledTimes(2),
  10614. );
  10615. expect(runtime.sendMessage).toHaveBeenCalledTimes(2);
  10616. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  10617. expect(app.transcript.snapshot()).toEqual(
  10618. expect.arrayContaining([
  10619. expect.objectContaining({ kind: "assistant", status: "cancelled" }),
  10620. ]),
  10621. );
  10622. await app.stop();
  10623. });
  10624. it("restores a failed submission before text typed while cancellation is retiring", async () => {
  10625. const terminal = new FakeTerminal();
  10626. const runtime = createRuntime();
  10627. let releaseRuntimeOwnership: (() => void) | undefined;
  10628. const runtimeOwnershipReleased = new Promise<void>((resolve) => {
  10629. releaseRuntimeOwnership = resolve;
  10630. });
  10631. vi.mocked(runtime.sendMessage).mockImplementation(
  10632. async function* sendMessage(_req: SendMessageReq, signal?: AbortSignal) {
  10633. await new Promise<void>((resolve) => {
  10634. signal?.addEventListener("abort", resolve, { once: true });
  10635. });
  10636. await runtimeOwnershipReleased;
  10637. yield { type: "done" };
  10638. },
  10639. );
  10640. const app = createTuiApp({
  10641. runtime,
  10642. terminal,
  10643. version: "0.1.0",
  10644. workspaceDir: "/workspace",
  10645. });
  10646. app.start();
  10647. await app.ready;
  10648. terminal.input?.("First request");
  10649. terminal.input?.("\r");
  10650. await vi.waitFor(() =>
  10651. expect(app.controller.snapshot().status).toBe("running"),
  10652. );
  10653. terminal.input?.("\x1b");
  10654. await vi.waitFor(
  10655. () => expect(app.controller.snapshot().retiringTurnId).toBeTruthy(),
  10656. {
  10657. timeout: 2_000,
  10658. },
  10659. );
  10660. expect(app.controller.snapshot()).toMatchObject({
  10661. status: "idle",
  10662. activeTurnId: undefined,
  10663. cancelling: false,
  10664. });
  10665. terminal.input?.("Second request");
  10666. terminal.input?.("\r");
  10667. terminal.input?.("extra detail");
  10668. await vi.waitFor(() => expect(app.editor.getText()).toBe("extra detail"));
  10669. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  10670. await vi.waitFor(() =>
  10671. expect(app.tui.render(160).join("\n")).toContain("Second request"),
  10672. );
  10673. expect(app.editor.getText()).toBe("Second request\nextra detail");
  10674. releaseRuntimeOwnership?.();
  10675. await vi.waitFor(() =>
  10676. expect(app.controller.snapshot().retiringTurnId).toBeUndefined(),
  10677. );
  10678. expect(app.tui.render(160).join("\n")).not.toContain(
  10679. "Runtime is still stopping; your draft is preserved",
  10680. );
  10681. await app.stop();
  10682. });
  10683. it("aborts session creation when the TUI stops during its first turn", async () => {
  10684. const terminal = new FakeTerminal();
  10685. const runtime = createRuntime();
  10686. let finishSessionCreation:
  10687. | ((session: { sessionId: string; workspaceDir: string }) => void)
  10688. | undefined;
  10689. vi.mocked(runtime.createSession).mockImplementation(
  10690. async () =>
  10691. await new Promise<{ sessionId: string; workspaceDir: string }>(
  10692. (resolve) => {
  10693. finishSessionCreation = resolve;
  10694. },
  10695. ),
  10696. );
  10697. const app = createTuiApp({
  10698. runtime,
  10699. terminal,
  10700. version: "0.1.0",
  10701. workspaceDir: "/workspace",
  10702. });
  10703. app.start();
  10704. await app.ready;
  10705. const submitting = app.submit("Wait for the session");
  10706. await vi.waitFor(() =>
  10707. expect(app.controller.snapshot().activeTurnId).toEqual(
  10708. expect.any(String),
  10709. ),
  10710. );
  10711. const stopping = app.stop();
  10712. finishSessionCreation?.({
  10713. sessionId: "session-created",
  10714. workspaceDir: "/workspace",
  10715. });
  10716. await Promise.all([submitting, stopping]);
  10717. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10718. expect(app.transcript.snapshot()).toEqual(
  10719. expect.arrayContaining([
  10720. expect.objectContaining({ kind: "assistant", status: "cancelled" }),
  10721. ]),
  10722. );
  10723. expect(terminal.stopped).toBe(true);
  10724. });
  10725. it.each(["minimax", "custom_provider:work"])(
  10726. "hydrates the Runtime-selected startup model for %s",
  10727. async (providerId) => {
  10728. const runtime = createRuntime();
  10729. vi.mocked(runtime.listModels).mockResolvedValue([
  10730. { providerId, modelId: "MiniMax-M3", selected: true },
  10731. ]);
  10732. const app = createTuiApp({
  10733. runtime,
  10734. terminal: new FakeTerminal(),
  10735. version: "0.1.0",
  10736. workspaceDir: "/workspace",
  10737. });
  10738. try {
  10739. await app.ready;
  10740. expect(runtime.listModels).toHaveBeenCalled();
  10741. expect(runtime.selectModel).not.toHaveBeenCalled();
  10742. await app.submit("/model");
  10743. expect(runtime.selectModel).not.toHaveBeenCalled();
  10744. } finally {
  10745. await app.stop();
  10746. }
  10747. },
  10748. );
  10749. it("offers provider onboarding when Desktop has no models", async () => {
  10750. const terminal = new FakeTerminal();
  10751. const runtime = createRuntime();
  10752. vi.mocked(runtime.listModels).mockResolvedValue([]);
  10753. const app = createTuiApp({
  10754. runtime,
  10755. terminal,
  10756. version: "0.1.0",
  10757. workspaceDir: "/workspace",
  10758. });
  10759. await app.ready;
  10760. await app.submit("/model unavailable");
  10761. expect(app.tui.hasOverlay()).toBe(false);
  10762. expect(app.interaction.isActive()).toBe(true);
  10763. const rendered = app.tui.render(120).join("\n");
  10764. expect(rendered).toContain("No matching models");
  10765. expect(rendered).toContain("Add 3rd-party provider");
  10766. terminal.input?.("\x1b");
  10767. await app.stop();
  10768. });
  10769. it("keeps the TUI usable when the Runtime model catalog fails to load", async () => {
  10770. const terminal = new FakeTerminal();
  10771. const runtime = createRuntime();
  10772. vi.mocked(runtime.listModels).mockRejectedValue(
  10773. new Error("catalog unavailable"),
  10774. );
  10775. const app = createTuiApp({
  10776. runtime,
  10777. terminal,
  10778. version: "0.1.0",
  10779. workspaceDir: "/workspace",
  10780. });
  10781. await app.ready;
  10782. await expect(app.submit("/model")).resolves.toBeUndefined();
  10783. expect(app.tui.hasOverlay()).toBe(false);
  10784. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  10785. kind: "warning",
  10786. content: "Couldn't load models: catalog unavailable. Retry /model.",
  10787. });
  10788. });
  10789. it("shows a follow-up as queued while Runtime admission is pending", async () => {
  10790. const terminal = new FakeTerminal();
  10791. const runtime = createRuntime();
  10792. let finishFirstTurn: (() => void) | undefined;
  10793. let finishEnqueue: (() => void) | undefined;
  10794. let admitted = false;
  10795. vi.mocked(runtime.sendMessage).mockImplementation(
  10796. async function* sendMessage() {
  10797. await new Promise<void>((resolve) => {
  10798. finishFirstTurn = resolve;
  10799. });
  10800. yield { type: "done" };
  10801. },
  10802. );
  10803. vi.mocked(runtime.enqueueMessage).mockImplementation(async () => {
  10804. await new Promise<void>((resolve) => {
  10805. finishEnqueue = resolve;
  10806. });
  10807. admitted = true;
  10808. return { itemId: "queue-pending-1", status: "queued", position: 1 };
  10809. });
  10810. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () =>
  10811. admitted
  10812. ? [
  10813. {
  10814. itemId: "queue-pending-1",
  10815. sessionId: "session-1",
  10816. status: "queued",
  10817. content: "Second turn",
  10818. },
  10819. ]
  10820. : [],
  10821. );
  10822. const app = createTuiApp({
  10823. runtime,
  10824. terminal,
  10825. version: "0.1.0",
  10826. workspaceDir: "/workspace",
  10827. });
  10828. app.start();
  10829. await app.ready;
  10830. const first = app.submit("First turn");
  10831. await vi.waitFor(() =>
  10832. expect(app.controller.snapshot().activeTurnId).toEqual(
  10833. expect.any(String),
  10834. ),
  10835. );
  10836. terminal.input?.("Second turn");
  10837. terminal.input?.("\x1b\r");
  10838. await vi.waitFor(() =>
  10839. expect(runtime.enqueueMessage).toHaveBeenCalledOnce(),
  10840. );
  10841. try {
  10842. expect(
  10843. app.transcript
  10844. .snapshot()
  10845. .find((cell) => cell.content.includes("Second turn")),
  10846. ).toBeUndefined();
  10847. const rendered = app.tui.render(100).join("\n");
  10848. expect(rendered).not.toContain("Adding to Queue");
  10849. expect(rendered).toContain("Next · after current response");
  10850. expect(rendered).toContain("Second turn");
  10851. finishEnqueue?.();
  10852. await vi.waitFor(() => {
  10853. const confirmed = app.tui.render(100).join("\n");
  10854. expect(confirmed).not.toContain("Adding to Queue");
  10855. expect(confirmed).toContain("Next · after current response");
  10856. expect(confirmed).toContain("Second turn");
  10857. });
  10858. } finally {
  10859. finishEnqueue?.();
  10860. finishFirstTurn?.();
  10861. await first;
  10862. await app.stop();
  10863. }
  10864. });
  10865. it("removes the local Queue admission and restores the Draft when Runtime rejects it", async () => {
  10866. const terminal = new FakeTerminal();
  10867. const runtime = createRuntime();
  10868. let finishFirstTurn: (() => void) | undefined;
  10869. let rejectEnqueue: ((error: Error) => void) | undefined;
  10870. vi.mocked(runtime.sendMessage).mockImplementation(
  10871. async function* sendMessage() {
  10872. await new Promise<void>((resolve) => {
  10873. finishFirstTurn = resolve;
  10874. });
  10875. yield { type: "done" };
  10876. },
  10877. );
  10878. vi.mocked(runtime.enqueueMessage).mockImplementation(
  10879. async () =>
  10880. await new Promise<never>((_resolve, reject) => {
  10881. rejectEnqueue = reject;
  10882. }),
  10883. );
  10884. const app = createTuiApp({
  10885. runtime,
  10886. terminal,
  10887. version: "0.1.0",
  10888. workspaceDir: "/workspace",
  10889. });
  10890. app.start();
  10891. await app.ready;
  10892. const first = app.submit("First turn");
  10893. await vi.waitFor(() =>
  10894. expect(app.controller.snapshot().activeTurnId).toEqual(
  10895. expect.any(String),
  10896. ),
  10897. );
  10898. terminal.input?.("Keep this Draft");
  10899. terminal.input?.("\x1b\r");
  10900. await vi.waitFor(() =>
  10901. expect(app.tui.render(100).join("\n")).toContain(
  10902. "Next · after current response",
  10903. ),
  10904. );
  10905. await vi.waitFor(() =>
  10906. expect(runtime.enqueueMessage).toHaveBeenCalledOnce(),
  10907. );
  10908. rejectEnqueue?.(new Error("queue unavailable"));
  10909. await vi.waitFor(() =>
  10910. expect(app.editor.getText()).toBe("Keep this Draft"),
  10911. );
  10912. const rendered = app.tui.render(100).join("\n");
  10913. expect(rendered).not.toContain("Next · after current response");
  10914. expect(rendered).toContain("Couldn't add this message to the Queue");
  10915. finishFirstTurn?.();
  10916. await first;
  10917. await app.stop();
  10918. });
  10919. it("shows every rapid follow-up as queued while Runtime admissions are serialized", async () => {
  10920. const terminal = new FakeTerminal();
  10921. const runtime = createRuntime();
  10922. let finishFirstTurn: (() => void) | undefined;
  10923. const releaseAdmissions: Array<() => void> = [];
  10924. const queued: TuiQueuedMessage[] = [];
  10925. vi.mocked(runtime.sendMessage).mockImplementation(
  10926. async function* sendMessage() {
  10927. await new Promise<void>((resolve) => {
  10928. finishFirstTurn = resolve;
  10929. });
  10930. yield { type: "done" };
  10931. },
  10932. );
  10933. vi.mocked(runtime.enqueueMessage).mockImplementation(
  10934. async (sessionId, content) => {
  10935. await new Promise<void>((resolve) => releaseAdmissions.push(resolve));
  10936. const item = {
  10937. itemId: `queue-rapid-${String(queued.length + 1)}`,
  10938. sessionId,
  10939. status: "queued",
  10940. content,
  10941. } satisfies TuiQueuedMessage;
  10942. queued.push(item);
  10943. return {
  10944. itemId: item.itemId,
  10945. status: item.status,
  10946. position: queued.length,
  10947. };
  10948. },
  10949. );
  10950. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  10951. ...queued,
  10952. ]);
  10953. const app = createTuiApp({
  10954. runtime,
  10955. terminal,
  10956. version: "0.1.0",
  10957. workspaceDir: "/workspace",
  10958. });
  10959. app.start();
  10960. await app.ready;
  10961. const first = app.submit("First turn");
  10962. await vi.waitFor(() =>
  10963. expect(app.controller.snapshot().activeTurnId).toEqual(
  10964. expect.any(String),
  10965. ),
  10966. );
  10967. terminal.input?.("Second turn");
  10968. terminal.input?.("\x1b\r");
  10969. terminal.input?.("Third turn");
  10970. terminal.input?.("\x1b\r");
  10971. await vi.waitFor(() => {
  10972. const rendered = app.tui.render(100).join("\n");
  10973. expect(rendered).not.toContain("Adding");
  10974. expect(rendered).toContain("Queue · 2 next");
  10975. expect(rendered).toContain("Second turn");
  10976. expect(rendered).toContain("Third turn");
  10977. });
  10978. expect(
  10979. app.transcript
  10980. .snapshot()
  10981. .filter(
  10982. (cell) =>
  10983. cell.content.includes("Second turn") ||
  10984. cell.content.includes("Third turn"),
  10985. ),
  10986. ).toEqual([]);
  10987. await vi.waitFor(() =>
  10988. expect(runtime.enqueueMessage).toHaveBeenCalledOnce(),
  10989. );
  10990. releaseAdmissions[0]?.();
  10991. await vi.waitFor(() =>
  10992. expect(runtime.enqueueMessage).toHaveBeenCalledTimes(2),
  10993. );
  10994. const partiallyConfirmed = app.tui.render(100).join("\n");
  10995. expect(partiallyConfirmed).toContain("Queue · 2 next");
  10996. expect(partiallyConfirmed.indexOf("Second turn")).toBeLessThan(
  10997. partiallyConfirmed.indexOf("Third turn"),
  10998. );
  10999. releaseAdmissions[1]?.();
  11000. await vi.waitFor(() =>
  11001. expect(app.tui.render(100).join("\n")).toContain("Queue · 2 next"),
  11002. );
  11003. finishFirstTurn?.();
  11004. await first;
  11005. await app.stop();
  11006. });
  11007. it("submits follow-ups to the runtime-owned queue and never drains them in the CLI", async () => {
  11008. const terminal = new FakeTerminal();
  11009. const runtime = createRuntime();
  11010. let finishFirstTurn: (() => void) | undefined;
  11011. vi.mocked(runtime.sendMessage).mockImplementation(
  11012. async function* sendMessage(req: SendMessageReq) {
  11013. const content = req.content ?? "";
  11014. if (content === "First turn") {
  11015. await new Promise<void>((resolve) => {
  11016. finishFirstTurn = resolve;
  11017. });
  11018. }
  11019. yield { type: "delta", content: `Reply to ${content || "attachment"}` };
  11020. yield { type: "done" };
  11021. },
  11022. );
  11023. const attachment = {
  11024. type: "file" as const,
  11025. filePath: "/workspace/notes.md",
  11026. fileName: "notes.md",
  11027. mimeType: "text/markdown",
  11028. sizeBytes: 32,
  11029. };
  11030. const queued: Array<{
  11031. itemId: string;
  11032. sessionId: string;
  11033. status: string;
  11034. content: string;
  11035. }> = [];
  11036. vi.mocked(runtime.enqueueMessage).mockImplementation(
  11037. async (sessionId, content) => {
  11038. const item = {
  11039. itemId: `queue-${queued.length + 1}`,
  11040. sessionId,
  11041. status: "queued",
  11042. content,
  11043. };
  11044. queued.push(item);
  11045. return {
  11046. itemId: item.itemId,
  11047. status: item.status,
  11048. position: queued.length,
  11049. };
  11050. },
  11051. );
  11052. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  11053. ...queued,
  11054. ]);
  11055. vi.mocked(runtime.deleteQueuedMessage).mockImplementation(
  11056. async (_sessionId, itemId) => {
  11057. const index = queued.findIndex((item) => item.itemId === itemId);
  11058. if (index < 0) return undefined;
  11059. return queued.splice(index, 1)[0];
  11060. },
  11061. );
  11062. const readClipboardImage = vi.fn(async () => ({
  11063. attachment,
  11064. dispose: vi.fn(async () => undefined),
  11065. }));
  11066. const app = createTuiApp({
  11067. runtime,
  11068. terminal,
  11069. version: "0.1.0",
  11070. workspaceDir: "/workspace",
  11071. readClipboardImage,
  11072. });
  11073. app.start();
  11074. await app.ready;
  11075. const first = app.submit("First turn");
  11076. await vi.waitFor(() =>
  11077. expect(app.controller.snapshot().activeTurnId).toEqual(
  11078. expect.any(String),
  11079. ),
  11080. );
  11081. terminal.input?.("\x16");
  11082. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledOnce());
  11083. await app.submit("Second turn");
  11084. await app.submit("Third turn");
  11085. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  11086. expect(runtime.enqueueMessage).toHaveBeenNthCalledWith(
  11087. 1,
  11088. "session-1",
  11089. "Second turn",
  11090. {
  11091. attachments: [attachment],
  11092. model: { providerId: "minimax", modelId: "MiniMax-M2.7" },
  11093. },
  11094. );
  11095. expect(runtime.enqueueMessage).toHaveBeenNthCalledWith(
  11096. 2,
  11097. "session-1",
  11098. "Third turn",
  11099. {
  11100. attachments: [],
  11101. model: { providerId: "minimax", modelId: "MiniMax-M2.7" },
  11102. },
  11103. );
  11104. expect(app.transcript.get("queue:queue-1")).toBeUndefined();
  11105. expect(app.transcript.get("queue:queue-2")).toBeUndefined();
  11106. const queuedUi = app.tui.render(80).join("\n");
  11107. expect(queuedUi).toContain("Queue · 2 next");
  11108. expect(queuedUi).toContain("after current response");
  11109. expect(queuedUi).toContain("Second turn");
  11110. expect(queuedUi).toContain("Third turn");
  11111. expect(queuedUi).toContain("/queue manage");
  11112. await app.submit("/queue");
  11113. expect(app.interaction.render(80).join("\n")).toContain("Queue");
  11114. expect(app.interaction.render(80).join("\n")).toContain("2 next");
  11115. expect(app.interaction.render(80).join("\n")).toContain("› 2. Third turn");
  11116. expect(app.editor.getText()).toBe("");
  11117. terminal.input?.("d");
  11118. expect(app.interaction.render(80).join("\n")).toContain(
  11119. "Remove this next message?",
  11120. );
  11121. terminal.input?.("\r");
  11122. await vi.waitFor(() =>
  11123. expect(runtime.deleteQueuedMessage).toHaveBeenCalledWith(
  11124. "session-1",
  11125. "queue-2",
  11126. ),
  11127. );
  11128. await vi.waitFor(() =>
  11129. expect(app.tui.render(80).join("\n")).not.toContain("Third turn"),
  11130. );
  11131. expect(app.tui.render(80).join("\n")).toContain("Second turn");
  11132. terminal.input?.("\x1b");
  11133. finishFirstTurn?.();
  11134. await first;
  11135. expect(
  11136. vi.mocked(runtime.sendMessage).mock.calls.map((call) => call[0].content),
  11137. ).toEqual(["First turn"]);
  11138. expect(app.tui.render(80).join("\n")).toContain(
  11139. "Next · after current response",
  11140. );
  11141. expect(app.tui.render(80).join("\n")).toContain("Second turn");
  11142. expect(app.tui.render(80).join("\n")).not.toContain("Sending next");
  11143. await app.stop();
  11144. });
  11145. it("uses the Runtime queue when a resumed started session is active before queue/model hydration finishes", async () => {
  11146. const terminal = new FakeTerminal();
  11147. const runtime = createRuntime();
  11148. let releaseQueue: ((items: TuiQueuedMessage[]) => void) | undefined;
  11149. const slowQueue = new Promise<TuiQueuedMessage[]>((resolve) => {
  11150. releaseQueue = resolve;
  11151. });
  11152. let releaseModels: ((models: TuiModel[]) => void) | undefined;
  11153. const slowModels = new Promise<TuiModel[]>((resolve) => {
  11154. releaseModels = resolve;
  11155. });
  11156. const session = {
  11157. sessionId: "session-running",
  11158. title: "Running session",
  11159. workspaceDir: "/workspace",
  11160. status: "started",
  11161. };
  11162. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11163. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11164. vi.mocked(runtime.getActiveRun).mockResolvedValue({
  11165. schemaVersion: 1,
  11166. sessionId: "session-running",
  11167. state: "running",
  11168. turnId: "turn-running",
  11169. actions: { steer: true },
  11170. });
  11171. vi.mocked(runtime.listQueuedMessages).mockImplementation(
  11172. async () => slowQueue,
  11173. );
  11174. vi.mocked(runtime.listModels).mockImplementation(async (sessionId) =>
  11175. sessionId ? slowModels : [],
  11176. );
  11177. vi.mocked(runtime.enqueueMessage).mockResolvedValue({
  11178. itemId: "queue-running-1",
  11179. status: "queued",
  11180. position: 1,
  11181. });
  11182. const app = createTuiApp({
  11183. runtime,
  11184. terminal,
  11185. version: "0.1.0",
  11186. workspaceDir: "/workspace",
  11187. productFeatures: { queue: true },
  11188. });
  11189. await app.ready;
  11190. const resuming = app.submit("/resume session-running");
  11191. await vi.waitFor(() =>
  11192. expect(app.tui.render(80).join("\n")).toContain("Loading"),
  11193. );
  11194. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  11195. const followUp = app.submit("Send this through the Runtime queue");
  11196. await vi.waitFor(() =>
  11197. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  11198. "session-running",
  11199. "Send this through the Runtime queue",
  11200. { attachments: [] },
  11201. ),
  11202. );
  11203. expect(runtime.sendMessage).not.toHaveBeenCalled();
  11204. releaseQueue?.([]);
  11205. releaseModels?.([]);
  11206. await Promise.all([resuming, followUp]);
  11207. await app.stop();
  11208. });
  11209. it("does not recover a terminal session as an active turn", async () => {
  11210. const terminal = new FakeTerminal();
  11211. const runtime = createRuntime();
  11212. const session = {
  11213. sessionId: "session-finished",
  11214. title: "Finished session",
  11215. workspaceDir: "/workspace",
  11216. status: "finished",
  11217. };
  11218. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11219. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11220. const app = createTuiApp({
  11221. runtime,
  11222. terminal,
  11223. version: "0.1.0",
  11224. workspaceDir: "/workspace",
  11225. });
  11226. await app.ready;
  11227. await app.submit("/resume session-finished");
  11228. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
  11229. expect(app.tui.render(80).join("\n")).toContain("Message · Enter send");
  11230. await app.stop();
  11231. });
  11232. it("does not recover a stale started Session when Runtime is already idle", async () => {
  11233. const terminal = new FakeTerminal();
  11234. const runtime = createRuntime();
  11235. const session = {
  11236. sessionId: "session-stale",
  11237. title: "Stale session",
  11238. workspaceDir: "/workspace",
  11239. status: "started",
  11240. };
  11241. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11242. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11243. const app = createTuiApp({
  11244. runtime,
  11245. terminal,
  11246. version: "0.1.0",
  11247. workspaceDir: "/workspace",
  11248. });
  11249. app.start();
  11250. await app.ready;
  11251. await app.submit("/resume session-stale");
  11252. await vi.waitFor(() =>
  11253. expect(app.tui.render(80).join("\n")).not.toContain("Loading"),
  11254. );
  11255. const rendered = app.tui.render(80).join("\n");
  11256. expect(rendered).not.toContain("Thinking");
  11257. expect(rendered).not.toContain("Stopping response");
  11258. expect(rendered).not.toContain("Stopping the current response");
  11259. expect(rendered).toContain("Message · Enter send");
  11260. await app.stop();
  11261. });
  11262. it("stops a recovered Runtime turn with /stop and Escape through abortSession", async () => {
  11263. const terminal = new FakeTerminal();
  11264. const runtime = createRuntime();
  11265. const session = {
  11266. sessionId: "session-running",
  11267. title: "Running session",
  11268. workspaceDir: "/workspace",
  11269. status: "started",
  11270. };
  11271. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11272. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11273. vi.mocked(runtime.getActiveRun).mockResolvedValue({
  11274. schemaVersion: 1,
  11275. sessionId: "session-running",
  11276. state: "running",
  11277. turnId: "turn-running",
  11278. actions: { steer: true },
  11279. });
  11280. vi.mocked(runtime.abortSession).mockResolvedValue(true);
  11281. const app = createTuiApp({
  11282. runtime,
  11283. terminal,
  11284. version: "0.1.0",
  11285. workspaceDir: "/workspace",
  11286. });
  11287. app.start();
  11288. await app.ready;
  11289. await app.submit("/resume session-running");
  11290. await app.submit("/stop");
  11291. expect(runtime.abortSession).toHaveBeenCalledWith(
  11292. expect.objectContaining({ id: "session-running" }),
  11293. );
  11294. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
  11295. vi.mocked(runtime.abortSession).mockClear();
  11296. await app.submit("/resume session-running");
  11297. terminal.input?.("\x1b");
  11298. await vi.waitFor(() =>
  11299. expect(runtime.abortSession).toHaveBeenCalledWith(
  11300. expect.objectContaining({ id: "session-running" }),
  11301. ),
  11302. );
  11303. await vi.waitFor(() =>
  11304. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt"),
  11305. );
  11306. expect(app.tui.render(80).join("\n")).not.toMatch(
  11307. /Stopped after|Interrupted after/u,
  11308. );
  11309. await app.stop();
  11310. });
  11311. it.each([
  11312. [
  11313. "rejects the abort",
  11314. async () => false,
  11315. "Runtime did not confirm that the active response stopped.",
  11316. ],
  11317. [
  11318. "fails the abort request",
  11319. async () => Promise.reject(new Error("connection lost")),
  11320. "Couldn't stop the current response:",
  11321. ],
  11322. ])(
  11323. "clears the recovered foreground projection and reports when Runtime %s",
  11324. async (_label, abort, expectedError) => {
  11325. const terminal = new FakeTerminal();
  11326. const runtime = createRuntime();
  11327. const session = {
  11328. sessionId: "session-running",
  11329. title: "Running session",
  11330. workspaceDir: "/workspace",
  11331. status: "started",
  11332. };
  11333. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11334. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11335. vi.mocked(runtime.getActiveRun).mockResolvedValue({
  11336. schemaVersion: 1,
  11337. sessionId: "session-running",
  11338. state: "running",
  11339. turnId: "turn-running",
  11340. actions: { steer: false },
  11341. });
  11342. vi.mocked(runtime.abortSession).mockImplementation(abort);
  11343. const app = createTuiApp({
  11344. runtime,
  11345. terminal,
  11346. version: "0.1.0",
  11347. workspaceDir: "/workspace",
  11348. });
  11349. app.start();
  11350. await app.ready;
  11351. await app.submit("/resume session-running");
  11352. terminal.input?.("\x1b");
  11353. await vi.waitFor(() =>
  11354. expect(runtime.abortSession).toHaveBeenCalledWith(
  11355. expect.objectContaining({ id: "session-running" }),
  11356. ),
  11357. );
  11358. await vi.waitFor(() =>
  11359. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt"),
  11360. );
  11361. await vi.waitFor(() =>
  11362. expect(app.tui.render(80).join("\n")).toContain(expectedError),
  11363. );
  11364. await app.stop();
  11365. },
  11366. );
  11367. it("keeps Request failed visible when Runtime still has queued follow-ups", async () => {
  11368. const terminal = new FakeTerminal();
  11369. const runtime = createRuntime();
  11370. let finishTurn: (() => void) | undefined;
  11371. const queued = [
  11372. {
  11373. itemId: "queue-after-error",
  11374. sessionId: "session-1",
  11375. status: "queued",
  11376. content: "Continue after failure",
  11377. },
  11378. ];
  11379. vi.mocked(runtime.listQueuedMessages).mockResolvedValue(queued);
  11380. vi.mocked(runtime.enqueueMessage).mockResolvedValue({
  11381. itemId: "queue-after-error",
  11382. status: "queued",
  11383. position: 1,
  11384. });
  11385. vi.mocked(runtime.sendMessage).mockImplementation(
  11386. async function* sendMessage() {
  11387. await new Promise<void>((resolve) => {
  11388. finishTurn = resolve;
  11389. });
  11390. yield { type: "error", message: "provider unavailable" };
  11391. },
  11392. );
  11393. const app = createTuiApp({
  11394. runtime,
  11395. terminal,
  11396. version: "0.1.0",
  11397. workspaceDir: "/workspace",
  11398. productFeatures: { queue: true },
  11399. });
  11400. await app.ready;
  11401. const first = app.submit("First turn");
  11402. await vi.waitFor(() =>
  11403. expect(app.controller.snapshot().activeTurnId).toEqual(
  11404. expect.any(String),
  11405. ),
  11406. );
  11407. await app.submit("Continue after failure");
  11408. finishTurn?.();
  11409. await first;
  11410. expect(app.tui.render(80).join("\n")).toContain(
  11411. "Error The model provider is temporarily unavailable.",
  11412. );
  11413. expect(app.tui.render(80).join("\n")).not.toContain("Request failed");
  11414. await app.stop();
  11415. });
  11416. it("converges a recovered running state after the Runtime emits a terminal event", async () => {
  11417. const terminal = new FakeTerminal();
  11418. const runtime = createRuntime();
  11419. const session = {
  11420. sessionId: "session-recovered",
  11421. title: "Recovered session",
  11422. workspaceDir: "/workspace",
  11423. status: "started",
  11424. };
  11425. const busEvents: TuiRuntimeEvent[] = [];
  11426. let wakeBus: (() => void) | undefined;
  11427. const waitForNextBusEvent = (signal: AbortSignal) =>
  11428. new Promise<void>((resolve) => {
  11429. wakeBus = resolve;
  11430. signal.addEventListener("abort", resolve, { once: true });
  11431. });
  11432. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11433. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11434. let activeRecoveredTurn = true;
  11435. vi.mocked(runtime.getActiveRun).mockImplementation(async () =>
  11436. activeRecoveredTurn
  11437. ? {
  11438. schemaVersion: 1,
  11439. sessionId: "session-recovered",
  11440. state: "running",
  11441. turnId: "turn-recovered",
  11442. actions: { steer: true },
  11443. }
  11444. : {
  11445. schemaVersion: 1,
  11446. sessionId: "session-recovered",
  11447. state: "terminal",
  11448. turnId: "turn-recovered",
  11449. actions: { steer: false },
  11450. },
  11451. );
  11452. let durableMessages: Awaited<ReturnType<TuiRuntime["getMessages"]>> = [];
  11453. vi.mocked(runtime.getMessages).mockImplementation(
  11454. async () => durableMessages,
  11455. );
  11456. vi.mocked(runtime.watchEvents).mockImplementation(
  11457. async function* watchEvents(signal) {
  11458. while (!signal.aborted) {
  11459. if (busEvents.length === 0) await waitForNextBusEvent(signal);
  11460. if (signal.aborted) return;
  11461. const event = busEvents.shift();
  11462. if (event) yield event;
  11463. }
  11464. },
  11465. );
  11466. const app = createTuiApp({
  11467. runtime,
  11468. terminal,
  11469. version: "0.1.0",
  11470. workspaceDir: "/workspace",
  11471. });
  11472. app.start();
  11473. await app.ready;
  11474. await app.submit("/resume session-recovered");
  11475. expect(app.tui.render(80).join("\n")).toContain("Loading");
  11476. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  11477. await vi.waitFor(() =>
  11478. expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
  11479. "session-recovered",
  11480. "turn-recovered",
  11481. expect.any(AbortSignal),
  11482. ),
  11483. );
  11484. activeRecoveredTurn = false;
  11485. const historyCallsBeforeTerminal = vi.mocked(runtime.getMessages).mock.calls
  11486. .length;
  11487. durableMessages = [
  11488. {
  11489. id: "message-recovered-assistant",
  11490. turnId: "turn-recovered",
  11491. role: "assistant",
  11492. content: "Recovered answer",
  11493. timestamp: 101,
  11494. },
  11495. ];
  11496. busEvents.push(
  11497. runtimeEvent({
  11498. type: "session.finish",
  11499. timestamp: 101,
  11500. source: "runtime",
  11501. payload: {
  11502. sessionId: "session-recovered",
  11503. turnId: "turn-recovered",
  11504. status: "finished",
  11505. },
  11506. }),
  11507. );
  11508. wakeBus?.();
  11509. wakeBus = undefined;
  11510. await vi.waitFor(() =>
  11511. expect(vi.mocked(runtime.getMessages).mock.calls.length).toBeGreaterThan(
  11512. historyCallsBeforeTerminal,
  11513. ),
  11514. );
  11515. await vi.waitFor(() => {
  11516. const rendered = app.tui.render(80).join("\n");
  11517. expect(rendered).not.toContain("Esc to interrupt");
  11518. expect(app.transcript.snapshot()).toEqual(
  11519. expect.arrayContaining([
  11520. expect.objectContaining({
  11521. kind: "assistant",
  11522. content: "Recovered answer",
  11523. }),
  11524. ]),
  11525. );
  11526. });
  11527. await app.stop();
  11528. });
  11529. it("clears a recovered decision block when switching to a session without a pending decision", async () => {
  11530. const terminal = new FakeTerminal();
  11531. const runtime = createRuntime();
  11532. let controllerSessionId = "";
  11533. const firstSession = {
  11534. sessionId: "session-blocked",
  11535. title: "Blocked session",
  11536. workspaceDir: "/workspace",
  11537. status: "started",
  11538. };
  11539. const secondSession = {
  11540. sessionId: "session-clear",
  11541. title: "Clear session",
  11542. workspaceDir: "/workspace",
  11543. status: "finished",
  11544. };
  11545. vi.mocked(runtime.listSessions).mockResolvedValue([
  11546. firstSession,
  11547. secondSession,
  11548. ]);
  11549. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  11550. sessionId === firstSession.sessionId ? firstSession : secondSession,
  11551. );
  11552. vi.mocked(runtime.listPendingPermissions).mockImplementation(async () =>
  11553. controllerSessionId === firstSession.sessionId
  11554. ? [
  11555. {
  11556. requestId: "permission-blocked",
  11557. sessionId: firstSession.sessionId,
  11558. agentName: "mavis",
  11559. toolName: "bash",
  11560. reason: "Run checks",
  11561. allowAlwaysSupported: true,
  11562. },
  11563. ]
  11564. : [],
  11565. );
  11566. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue(undefined);
  11567. const app = createTuiApp({
  11568. runtime,
  11569. terminal,
  11570. version: "0.1.0",
  11571. workspaceDir: "/workspace",
  11572. });
  11573. await app.ready;
  11574. controllerSessionId = firstSession.sessionId;
  11575. await app.submit("/resume session-blocked");
  11576. expect(app.tui.hasOverlay()).toBe(false);
  11577. expect(app.interaction.isActive()).toBe(true);
  11578. expect(app.tui.render(80).join("\n")).toContain("Approval required");
  11579. controllerSessionId = secondSession.sessionId;
  11580. await app.submit("/resume session-clear");
  11581. expect(app.tui.hasOverlay()).toBe(false);
  11582. const rendered = app.tui.render(80).join("\n");
  11583. expect(rendered).not.toContain("Approval required");
  11584. expect(rendered).not.toContain("Reply required");
  11585. await app.stop();
  11586. });
  11587. it("moves a sending follow-up from the Composer area into the user transcript", async () => {
  11588. const terminal = new FakeTerminal();
  11589. const runtime = createRuntime();
  11590. const busEvents: TuiRuntimeEvent[] = [];
  11591. let wakeBus: (() => void) | undefined;
  11592. const waitForNextBusEvent = (signal: AbortSignal) =>
  11593. new Promise<void>((resolve) => {
  11594. wakeBus = resolve;
  11595. signal.addEventListener("abort", resolve, { once: true });
  11596. });
  11597. vi.mocked(runtime.listSessions).mockResolvedValue([
  11598. {
  11599. sessionId: "session-existing",
  11600. title: "Existing",
  11601. workspaceDir: "/workspace",
  11602. },
  11603. ]);
  11604. vi.mocked(runtime.listQueuedMessages).mockResolvedValue([
  11605. {
  11606. itemId: "queue-with-attachment",
  11607. sessionId: "session-existing",
  11608. status: "queued",
  11609. content: "Review the attached plan",
  11610. attachments: [
  11611. {
  11612. meta: {
  11613. attachmentType: "file",
  11614. fileName: "plan.md",
  11615. mimeType: "text/markdown",
  11616. sizeBytes: 42,
  11617. },
  11618. local: { filePath: "/workspace/plan.md" },
  11619. },
  11620. ],
  11621. },
  11622. {
  11623. itemId: "queue-that-fails",
  11624. sessionId: "session-existing",
  11625. status: "queued",
  11626. content: "Run the failing follow-up",
  11627. },
  11628. ]);
  11629. vi.mocked(runtime.watchEvents).mockImplementation(
  11630. async function* watchEvents(signal) {
  11631. while (!signal.aborted) {
  11632. if (busEvents.length === 0) await waitForNextBusEvent(signal);
  11633. if (signal.aborted) return;
  11634. const event = busEvents.shift();
  11635. if (event) yield event;
  11636. }
  11637. },
  11638. );
  11639. const emitQueueStatus = (
  11640. itemId: string,
  11641. status: string,
  11642. failedReason?: string,
  11643. ) => {
  11644. busEvents.push(
  11645. runtimeEvent({
  11646. type: "session.queue.updated",
  11647. timestamp: Date.now(),
  11648. source: "runtime",
  11649. payload: {
  11650. sessionId: "session-existing",
  11651. itemId,
  11652. status,
  11653. queuedCount: status === "queued" ? 1 : 0,
  11654. ...(failedReason ? { failedReason } : {}),
  11655. },
  11656. }),
  11657. );
  11658. wakeBus?.();
  11659. wakeBus = undefined;
  11660. };
  11661. const app = createTuiApp({
  11662. runtime,
  11663. terminal,
  11664. version: "0.1.0",
  11665. workspaceDir: "/workspace",
  11666. productFeatures: { queue: true },
  11667. });
  11668. app.start();
  11669. await app.ready;
  11670. await app.submit("/resume session-existing");
  11671. expect(app.tui.render(80).join("\n")).toContain("Queue · 2 next");
  11672. expect(app.tui.render(80).join("\n")).toContain("Review the attached plan");
  11673. expect(app.transcript.get("queue:queue-with-attachment")).toBeUndefined();
  11674. emitQueueStatus("queue-with-attachment", "running");
  11675. await vi.waitFor(() =>
  11676. expect(app.transcript.get("queue:queue-with-attachment")).toMatchObject({
  11677. kind: "user",
  11678. status: "succeeded",
  11679. content: expect.stringContaining("Review the attached plan"),
  11680. }),
  11681. );
  11682. expect(app.tui.render(80).join("\n")).not.toContain("SENDING");
  11683. expect(app.tui.render(80).join("\n")).toContain(
  11684. "Next · after current response",
  11685. );
  11686. expect(app.tui.render(80).join("\n")).toContain(
  11687. "Run the failing follow-up",
  11688. );
  11689. expect(
  11690. app.transcript.get("queue:queue-with-attachment")?.attachments,
  11691. ).toEqual([
  11692. expect.objectContaining({
  11693. fileName: "plan.md",
  11694. mimeType: "text/markdown",
  11695. sizeBytes: 42,
  11696. }),
  11697. ]);
  11698. emitQueueStatus("queue-with-attachment", "completed");
  11699. await vi.waitFor(() =>
  11700. expect(app.transcript.get("queue:queue-with-attachment")).toMatchObject({
  11701. kind: "user",
  11702. status: "succeeded",
  11703. content: expect.stringContaining("Review the attached plan"),
  11704. }),
  11705. );
  11706. emitQueueStatus("queue-that-fails", "running");
  11707. await vi.waitFor(() =>
  11708. expect(app.transcript.get("queue:queue-that-fails")).toMatchObject({
  11709. kind: "user",
  11710. status: "succeeded",
  11711. }),
  11712. );
  11713. emitQueueStatus(
  11714. "queue-that-fails",
  11715. "admission-rejected",
  11716. "provider unavailable",
  11717. );
  11718. await vi.waitFor(() =>
  11719. expect(app.editor.getText()).toBe("Run the failing follow-up"),
  11720. );
  11721. expect(app.tui.render(80).join("\n")).toContain(
  11722. "Error Message was not added to the Queue: provider unavailable.",
  11723. );
  11724. expect(app.transcript.get("queue:queue-that-fails")).toMatchObject({
  11725. kind: "user",
  11726. status: "succeeded",
  11727. });
  11728. expect(app.tui.render(80).join("\n")).toContain(
  11729. "Run the failing follow-up",
  11730. );
  11731. await app.stop();
  11732. });
  11733. it("refreshes history when Desktop Runtime finishes an auto-drained queued turn", async () => {
  11734. const terminal = new FakeTerminal();
  11735. const runtime = createRuntime();
  11736. const busEvents: TuiRuntimeEvent[] = [];
  11737. let wakeBus: (() => void) | undefined;
  11738. const waitForNextBusEvent = (signal: AbortSignal) =>
  11739. new Promise<void>((resolve) => {
  11740. wakeBus = resolve;
  11741. signal.addEventListener("abort", resolve, { once: true });
  11742. });
  11743. vi.mocked(runtime.listSessions).mockResolvedValue([
  11744. {
  11745. sessionId: "session-existing",
  11746. title: "Existing",
  11747. workspaceDir: "/workspace",
  11748. },
  11749. ]);
  11750. vi.mocked(runtime.getMessages)
  11751. .mockResolvedValueOnce([])
  11752. .mockResolvedValue([
  11753. {
  11754. id: "message-user-queued",
  11755. turnId: "turn-queued",
  11756. role: "user",
  11757. content: "Runtime follow-up",
  11758. timestamp: 100,
  11759. },
  11760. {
  11761. id: "message-assistant-queued",
  11762. turnId: "turn-queued",
  11763. role: "assistant",
  11764. content: "Runtime follow-up answer",
  11765. timestamp: 101,
  11766. },
  11767. ]);
  11768. vi.mocked(runtime.watchEvents).mockImplementation(
  11769. async function* watchEvents(signal) {
  11770. while (!signal.aborted) {
  11771. if (busEvents.length === 0) {
  11772. await waitForNextBusEvent(signal);
  11773. }
  11774. if (signal.aborted) return;
  11775. const event = busEvents.shift();
  11776. if (event) yield event;
  11777. }
  11778. },
  11779. );
  11780. const emit = (event: RawTuiRuntimeEvent) => {
  11781. busEvents.push(runtimeEvent(event));
  11782. wakeBus?.();
  11783. wakeBus = undefined;
  11784. };
  11785. const app = createTuiApp({
  11786. runtime,
  11787. terminal,
  11788. version: "0.1.0",
  11789. workspaceDir: "/workspace",
  11790. });
  11791. app.start();
  11792. await app.ready;
  11793. await app.submit("/resume session-existing");
  11794. emit({
  11795. type: "session.start",
  11796. timestamp: 100,
  11797. source: "runtime",
  11798. payload: {
  11799. sessionId: "session-existing",
  11800. turnId: "turn-queued",
  11801. source: "queued-drain",
  11802. queueItemIds: ["queue-1"],
  11803. },
  11804. });
  11805. await vi.waitFor(() =>
  11806. expect(app.tui.render(80).join("\n")).toContain("Loading"),
  11807. );
  11808. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  11809. expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
  11810. "session-existing",
  11811. "turn-queued",
  11812. expect.any(AbortSignal),
  11813. );
  11814. emit({
  11815. type: "session.finish",
  11816. timestamp: 101,
  11817. source: "runtime",
  11818. payload: {
  11819. sessionId: "session-existing",
  11820. turnId: "turn-queued",
  11821. status: "finished",
  11822. },
  11823. });
  11824. await vi.waitFor(() =>
  11825. expect(app.transcript.snapshot()).toEqual(
  11826. expect.arrayContaining([
  11827. expect.objectContaining({
  11828. kind: "assistant",
  11829. content: "Runtime follow-up answer",
  11830. }),
  11831. ]),
  11832. ),
  11833. );
  11834. const historyProjectionCalls = vi
  11835. .mocked(runtime.getMessages)
  11836. .mock.calls.filter(
  11837. ([sessionId, limit]) =>
  11838. sessionId === "session-existing" && limit === undefined,
  11839. );
  11840. expect(historyProjectionCalls).toHaveLength(2);
  11841. await app.stop();
  11842. });
  11843. it("writes one structured result when an auto-drained queued turn finishes", async () => {
  11844. const dataDir = await mkdtemp(join(tmpdir(), "mcode-queued-result-"));
  11845. const resultPath = join(dataDir, "results.jsonl");
  11846. const terminal = new FakeTerminal();
  11847. const runtime = createRuntime();
  11848. const busEvents: TuiRuntimeEvent[] = [];
  11849. let wakeBus: (() => void) | undefined;
  11850. let durableMessages: Awaited<ReturnType<TuiRuntime["getMessages"]>> = [];
  11851. vi.mocked(runtime.listSessions).mockResolvedValue([
  11852. {
  11853. sessionId: "session-existing",
  11854. title: "Existing",
  11855. workspaceDir: "/workspace",
  11856. },
  11857. ]);
  11858. vi.mocked(runtime.getMessages).mockImplementation(
  11859. async () => durableMessages,
  11860. );
  11861. const waitForBusEvent = (signal: AbortSignal) =>
  11862. new Promise<void>((resolve) => {
  11863. wakeBus = resolve;
  11864. signal.addEventListener("abort", resolve, { once: true });
  11865. });
  11866. vi.mocked(runtime.watchEvents).mockImplementation(
  11867. async function* watchEvents(signal) {
  11868. while (!signal.aborted) {
  11869. if (busEvents.length === 0) await waitForBusEvent(signal);
  11870. if (signal.aborted) return;
  11871. const event = busEvents.shift();
  11872. if (event) yield event;
  11873. }
  11874. },
  11875. );
  11876. const emit = (event: RawTuiRuntimeEvent) => {
  11877. busEvents.push(runtimeEvent(event));
  11878. wakeBus?.();
  11879. wakeBus = undefined;
  11880. };
  11881. const app = createTuiApp({
  11882. runtime,
  11883. terminal,
  11884. version: "0.1.0",
  11885. workspaceDir: "/workspace",
  11886. statusLineItems: ["build-mode"],
  11887. automationResultPath: resultPath,
  11888. });
  11889. try {
  11890. app.start();
  11891. await app.ready;
  11892. await app.submit("/resume session-existing");
  11893. emit({
  11894. type: "session.start",
  11895. timestamp: 100,
  11896. source: "runtime",
  11897. payload: {
  11898. sessionId: "session-existing",
  11899. turnId: "turn-queued-result",
  11900. source: "queued-drain",
  11901. queueItemIds: ["queue-result"],
  11902. },
  11903. });
  11904. await vi.waitFor(() =>
  11905. expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
  11906. "session-existing",
  11907. "turn-queued-result",
  11908. expect.any(AbortSignal),
  11909. ),
  11910. );
  11911. durableMessages = [
  11912. {
  11913. id: "message-user-result",
  11914. turnId: "turn-queued-result",
  11915. role: "user",
  11916. content: "Queued request",
  11917. timestamp: 101,
  11918. },
  11919. {
  11920. id: "message-assistant-result",
  11921. turnId: "turn-queued-result",
  11922. role: "assistant",
  11923. content: "Queued structured answer",
  11924. timestamp: 102,
  11925. },
  11926. ];
  11927. emit({
  11928. type: "session.finish",
  11929. timestamp: 103,
  11930. source: "runtime",
  11931. payload: {
  11932. sessionId: "session-existing",
  11933. turnId: "turn-queued-result",
  11934. status: "finished",
  11935. },
  11936. });
  11937. await vi.waitFor(async () => {
  11938. const records = (await readFile(resultPath, "utf8"))
  11939. .trim()
  11940. .split("\n")
  11941. .map(JSON.parse);
  11942. expect(records).toEqual([
  11943. expect.objectContaining({
  11944. type: "exec.result",
  11945. sessionId: "session-existing",
  11946. turnId: "turn-queued-result",
  11947. status: "succeeded",
  11948. answer: "Queued structured answer",
  11949. }),
  11950. ]);
  11951. });
  11952. expect(app.controller.snapshot().lastSettledTurn).toEqual({
  11953. sessionId: "session-existing",
  11954. turnId: "turn-queued-result",
  11955. status: "succeeded",
  11956. });
  11957. } finally {
  11958. await app.stop();
  11959. await rm(dataDir, { recursive: true, force: true });
  11960. }
  11961. });
  11962. it.each([1, 100])(
  11963. "settles an auto-drained follow-up of %i lines with unique terminal history",
  11964. async (lineCount) => {
  11965. const queuedText = Array.from(
  11966. { length: lineCount },
  11967. (_, i) => `Queue line ${i}: 合成测试文字`,
  11968. ).join("\n");
  11969. const terminal = new FakeTerminal();
  11970. const runtime = createRuntime();
  11971. const busEvents: TuiRuntimeEvent[] = [];
  11972. const queuedItems: TuiQueuedMessage[] = [];
  11973. let wakeBus: (() => void) | undefined;
  11974. let finishFirstTurn: (() => void) | undefined;
  11975. let finishQueuedStream: (() => void) | undefined;
  11976. const queuedStreamClosed = vi.fn();
  11977. let durableMessages: Awaited<ReturnType<TuiRuntime["getMessages"]>> = [];
  11978. const waitForNextBusEvent = (signal: AbortSignal) =>
  11979. new Promise<void>((resolve) => {
  11980. wakeBus = resolve;
  11981. signal.addEventListener("abort", resolve, { once: true });
  11982. });
  11983. vi.mocked(runtime.sendMessage).mockImplementation(
  11984. async function* sendMessage() {
  11985. await new Promise<void>((resolve) => {
  11986. finishFirstTurn = resolve;
  11987. });
  11988. yield { type: "delta", content: "First answer" };
  11989. yield { type: "done" };
  11990. },
  11991. );
  11992. vi.mocked(runtime.watchSessionTurn).mockImplementation(
  11993. async function* watchSessionTurn() {
  11994. try {
  11995. await new Promise<void>((resolve) => {
  11996. finishQueuedStream = resolve;
  11997. });
  11998. yield { type: "delta", content: "Queued answer" };
  11999. yield { type: "done" };
  12000. } finally {
  12001. queuedStreamClosed();
  12002. }
  12003. },
  12004. );
  12005. vi.mocked(runtime.enqueueMessage).mockImplementation(
  12006. async (sessionId, content) => {
  12007. const item: TuiQueuedMessage = {
  12008. itemId: "queue-b",
  12009. sessionId,
  12010. status: "queued",
  12011. content,
  12012. };
  12013. queuedItems.push(item);
  12014. return { itemId: item.itemId, status: item.status, position: 1 };
  12015. },
  12016. );
  12017. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  12018. ...queuedItems,
  12019. ]);
  12020. vi.mocked(runtime.getMessages).mockImplementation(
  12021. async () => durableMessages,
  12022. );
  12023. vi.mocked(runtime.watchEvents).mockImplementation(
  12024. async function* watchEvents(signal) {
  12025. while (!signal.aborted) {
  12026. if (busEvents.length === 0) await waitForNextBusEvent(signal);
  12027. if (signal.aborted) return;
  12028. const event = busEvents.shift();
  12029. if (event) yield event;
  12030. }
  12031. },
  12032. );
  12033. const emit = (event: RawTuiRuntimeEvent) => {
  12034. busEvents.push(runtimeEvent(event));
  12035. wakeBus?.();
  12036. wakeBus = undefined;
  12037. };
  12038. const app = createTuiApp({
  12039. runtime,
  12040. terminal,
  12041. version: "0.1.0",
  12042. workspaceDir: "/workspace",
  12043. productFeatures: { queue: true },
  12044. });
  12045. const screen = new VirtualTerminalScreen(terminal.columns, terminal.rows);
  12046. let writeIndex = 0;
  12047. const assertScreen = () => {
  12048. app.tui.renderNow();
  12049. for (; writeIndex < terminal.writes.length; writeIndex++)
  12050. screen.feed(terminal.writes[writeIndex]!);
  12051. const expected = stripAnsi(app.tui.render(terminal.columns).join("\n"))
  12052. .split("\n")
  12053. .map((line) => line.trimEnd())
  12054. .join("\n")
  12055. .trimEnd();
  12056. expect(screen.text()).toBe(expected);
  12057. };
  12058. app.start();
  12059. try {
  12060. await app.ready;
  12061. const first = app.submit("A");
  12062. await vi.waitFor(() =>
  12063. expect(app.controller.snapshot().activeTurnId).toBeDefined(),
  12064. );
  12065. terminal.input?.(`\x1b[200~${queuedText}\x1b[201~`);
  12066. assertScreen();
  12067. terminal.input?.("\x1b\r");
  12068. await vi.waitFor(() =>
  12069. expect(runtime.enqueueMessage).toHaveBeenCalledOnce(),
  12070. );
  12071. await vi.waitFor(() => expect(app.editor.getText()).toBe(""));
  12072. expect(vi.mocked(runtime.enqueueMessage).mock.calls[0]?.[1]).toBe(queuedText);
  12073. expect(app.tui.render(80).join("\n")).toContain(
  12074. "Next · after current response",
  12075. );
  12076. expect(app.tui.render(80).join("\n")).toContain("Queue line 0:");
  12077. assertScreen();
  12078. finishFirstTurn?.();
  12079. await first;
  12080. const queuedItem = queuedItems[0];
  12081. expect(queuedItem).toBeDefined();
  12082. if (!queuedItem) throw new Error("Expected B to be queued.");
  12083. queuedItems[0] = { ...queuedItem, status: "running" };
  12084. emit({
  12085. type: "session.queue.updated",
  12086. timestamp: 200,
  12087. source: "runtime",
  12088. payload: {
  12089. sessionId: "session-1",
  12090. itemId: "queue-b",
  12091. status: "running",
  12092. queuedCount: 0,
  12093. },
  12094. });
  12095. emit({
  12096. type: "session.start",
  12097. timestamp: 201,
  12098. source: "runtime",
  12099. payload: {
  12100. sessionId: "session-1",
  12101. turnId: "turn_queue_b",
  12102. source: "queued-drain",
  12103. queueItemIds: ["queue-b"],
  12104. },
  12105. });
  12106. await vi.waitFor(() =>
  12107. expect(app.tui.render(80).join("\n")).toContain("Loading"),
  12108. );
  12109. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  12110. assertScreen();
  12111. queuedItems.length = 0;
  12112. durableMessages = [
  12113. {
  12114. id: "history-user-a",
  12115. turnId: "turn_a",
  12116. role: "user",
  12117. content: "A",
  12118. timestamp: 100,
  12119. },
  12120. {
  12121. id: "history-assistant-a",
  12122. turnId: "turn_a",
  12123. role: "assistant",
  12124. content: "First answer",
  12125. timestamp: 101,
  12126. },
  12127. {
  12128. id: "history-user-b",
  12129. turnId: "turn_queue_b",
  12130. role: "user",
  12131. content: queuedText,
  12132. timestamp: 202,
  12133. },
  12134. {
  12135. id: "history-assistant-b",
  12136. turnId: "turn_queue_b",
  12137. role: "assistant",
  12138. content: "Queued answer",
  12139. timestamp: 203,
  12140. },
  12141. ];
  12142. finishQueuedStream?.();
  12143. await vi.waitFor(() =>
  12144. expect(queuedStreamClosed).toHaveBeenCalledOnce(),
  12145. );
  12146. emit({
  12147. type: "session.finish",
  12148. timestamp: 3_201,
  12149. source: "runtime",
  12150. payload: {
  12151. sessionId: "session-1",
  12152. turnId: "turn_queue_b",
  12153. status: "finished",
  12154. },
  12155. });
  12156. await vi.waitFor(() =>
  12157. expect(
  12158. app.transcript
  12159. .snapshot()
  12160. .filter((cell) => cell.content === "Queued answer"),
  12161. ).toHaveLength(1),
  12162. );
  12163. await vi.waitFor(() =>
  12164. expect(
  12165. app.transcript.get("turn-duration:turn_queue_b"),
  12166. ).toMatchObject({
  12167. status: "succeeded",
  12168. durationMs: 3_000,
  12169. }),
  12170. );
  12171. const settledUi = app.tui.render(80).join("\n");
  12172. expect(settledUi).toContain("Completed in 3s");
  12173. expect(settledUi.indexOf("Completed in 3s")).toBeGreaterThan(
  12174. settledUi.indexOf("Queued answer"),
  12175. );
  12176. expect(settledUi).not.toContain("message waiting");
  12177. expect(settledUi).not.toContain("Next · after current response");
  12178. assertScreen();
  12179. } finally {
  12180. finishFirstTurn?.();
  12181. finishQueuedStream?.();
  12182. await app.stop();
  12183. screen.dispose();
  12184. }
  12185. },
  12186. );
  12187. it("records submitted drafts in editor history", async () => {
  12188. const terminal = new FakeTerminal();
  12189. const runtime = createRuntime();
  12190. const app = createTuiApp({
  12191. runtime,
  12192. terminal,
  12193. version: "0.1.0",
  12194. workspaceDir: "/workspace",
  12195. });
  12196. await app.ready;
  12197. app.editor.setText("Remember this draft");
  12198. app.editor.handleInput("\r");
  12199. await vi.waitFor(() =>
  12200. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  12201. );
  12202. app.editor.handleInput("\u001b[A");
  12203. expect(app.editor.getText()).toBe("Remember this draft");
  12204. });
  12205. it("continues sending and switching sessions when draft cleanup fails", async () => {
  12206. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-warning-"));
  12207. const runtime = createRuntime();
  12208. const app = createTuiApp({
  12209. runtime,
  12210. terminal: new FakeTerminal(),
  12211. version: "0.1.0",
  12212. dataDir,
  12213. workspaceDir: "/workspace",
  12214. });
  12215. const flush = vi.spyOn(TuiDraftRecovery.prototype, "flush");
  12216. try {
  12217. await app.ready;
  12218. flush.mockRejectedValue(
  12219. new TuiDraftRecoveryError("cleanup", new Error("deletion denied")),
  12220. );
  12221. app.editor.setText("hello");
  12222. app.editor.handleInput("\r");
  12223. await vi.waitFor(() =>
  12224. expect(
  12225. app.transcript.snapshot().filter((cell) => cell.kind === "warning"),
  12226. ).toHaveLength(1),
  12227. );
  12228. const warnings = app.transcript
  12229. .snapshot()
  12230. .filter((cell) => cell.kind === "warning");
  12231. expect(warnings[0]?.content).toContain(
  12232. composerText("draftCleanupNextStep"),
  12233. );
  12234. expect(warnings[0]?.content).not.toContain(
  12235. composerText("draftRecoveryUnavailable"),
  12236. );
  12237. expect(warnings[0]?.content).toContain("deletion denied");
  12238. await vi.waitFor(() =>
  12239. expect(runtime.sendMessage).toHaveBeenCalledOnce(),
  12240. );
  12241. await vi.waitFor(() =>
  12242. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  12243. );
  12244. await expect(app.openSession("session-2")).resolves.toBeUndefined();
  12245. expect(app.controller.snapshot().session?.sessionId).toBe("session-2");
  12246. app.editor.setText("after switching");
  12247. app.editor.handleInput("\r");
  12248. await vi.waitFor(() =>
  12249. expect(runtime.sendMessage).toHaveBeenCalledTimes(2),
  12250. );
  12251. await expect(app.stop()).resolves.toBeUndefined();
  12252. } finally {
  12253. await app.stop();
  12254. flush.mockRestore();
  12255. await rm(dataDir, { recursive: true, force: true });
  12256. }
  12257. });
  12258. it("does not read or restore a persisted Draft during TUI startup", async () => {
  12259. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-"));
  12260. try {
  12261. const first = createTuiApp({
  12262. runtime: createRuntime(),
  12263. terminal: new FakeTerminal(),
  12264. version: "0.1.0",
  12265. dataDir,
  12266. workspaceDir: "/workspace/recovery",
  12267. });
  12268. await first.ready;
  12269. first.editor.setText("/exit");
  12270. await first.stop();
  12271. const loadDraft = vi.spyOn(TuiDraftRecovery.prototype, "load");
  12272. const restored = createTuiApp({
  12273. runtime: createRuntime(),
  12274. terminal: new FakeTerminal(),
  12275. version: "0.1.0",
  12276. dataDir,
  12277. workspaceDir: "/workspace/recovery",
  12278. });
  12279. await restored.ready;
  12280. expect(loadDraft).not.toHaveBeenCalled();
  12281. expect(restored.editor.getText()).toBe("");
  12282. expect(restored.tui.render(80).join("\n")).not.toContain(
  12283. "Draft restored",
  12284. );
  12285. loadDraft.mockRestore();
  12286. restored.editor.setText("");
  12287. await restored.stop();
  12288. } finally {
  12289. await rm(dataDir, { recursive: true, force: true });
  12290. }
  12291. });
  12292. it("does not resume a persisted Draft during startup when login recovery is enabled", async () => {
  12293. const dataDir = await mkdtemp(join(tmpdir(), "mcode-login-restart-draft-"));
  12294. try {
  12295. const first = createTuiApp({
  12296. runtime: createRuntime(),
  12297. terminal: new FakeTerminal(),
  12298. version: "0.1.0",
  12299. dataDir,
  12300. workspaceDir: "/workspace/login-recovery",
  12301. });
  12302. await first.ready;
  12303. first.editor.setText("send after Global login");
  12304. await first.stop();
  12305. const restored = createTuiApp({
  12306. runtime: createRuntime(),
  12307. terminal: new FakeTerminal(),
  12308. version: "0.1.0",
  12309. dataDir,
  12310. workspaceDir: "/workspace/login-recovery",
  12311. resumeDraftAfterLogin: true,
  12312. });
  12313. await restored.ready;
  12314. restored.start();
  12315. expect(restored.editor.getText()).toBe("");
  12316. expect(restored.getSurface()).toBe("welcome");
  12317. expect(restored.tui.render(80).join("\n")).toContain(
  12318. "Tips for getting started",
  12319. );
  12320. await restored.stop();
  12321. } finally {
  12322. await rm(dataDir, { recursive: true, force: true });
  12323. }
  12324. });
  12325. it("keeps the submitted Draft recoverable when shutdown wins before Runtime admission", async () => {
  12326. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-pending-draft-"));
  12327. try {
  12328. const runtime = createRuntime();
  12329. vi.spyOn(runtime, "sendMessage").mockImplementation(
  12330. async function* sendMessage(
  12331. _req: SendMessageReq,
  12332. signal?: AbortSignal,
  12333. ) {
  12334. yield* [];
  12335. await new Promise<void>((_resolve, reject) => {
  12336. signal?.addEventListener(
  12337. "abort",
  12338. () => reject(new Error("admission aborted")),
  12339. {
  12340. once: true,
  12341. },
  12342. );
  12343. });
  12344. throw new Error("unreachable");
  12345. },
  12346. );
  12347. const first = createTuiApp({
  12348. runtime,
  12349. terminal: new FakeTerminal(),
  12350. version: "0.1.0",
  12351. dataDir,
  12352. workspaceDir: "/workspace/pending-recovery",
  12353. });
  12354. await first.ready;
  12355. first.editor.setText("recover me until Runtime accepts");
  12356. await new Promise((resolve) => setTimeout(resolve, 300));
  12357. first.editor.handleInput("\r");
  12358. await vi.waitFor(() =>
  12359. expect(runtime.sendMessage).toHaveBeenCalledOnce(),
  12360. );
  12361. await first.stop();
  12362. const restored = createTuiApp({
  12363. runtime: createRuntime(),
  12364. terminal: new FakeTerminal(),
  12365. version: "0.1.0",
  12366. dataDir,
  12367. workspaceDir: "/workspace/pending-recovery",
  12368. });
  12369. await restored.ready;
  12370. await restored.openSession("session-1");
  12371. expect(restored.editor.getText()).toBe(
  12372. "recover me until Runtime accepts",
  12373. );
  12374. const rendered = restored.tui.render(80).join("\n");
  12375. expect(rendered).toContain("recover me until Runtime accepts");
  12376. expect(rendered).not.toContain("Message kept under Failed");
  12377. await restored.stop();
  12378. } finally {
  12379. await rm(dataDir, { recursive: true, force: true });
  12380. }
  12381. });
  12382. it("does not restore a submitted Draft after Runtime accepts the turn", async () => {
  12383. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-accepted-draft-"));
  12384. try {
  12385. const runtime = createRuntime();
  12386. vi.mocked(runtime.sendMessage).mockImplementation(
  12387. async function* sendMessage(
  12388. _req: SendMessageReq,
  12389. signal?: AbortSignal,
  12390. ) {
  12391. await new Promise<void>((resolve) => {
  12392. signal?.addEventListener("abort", resolve, { once: true });
  12393. });
  12394. yield { type: "done" };
  12395. },
  12396. );
  12397. const first = createTuiApp({
  12398. runtime,
  12399. terminal: new FakeTerminal(),
  12400. version: "0.1.0",
  12401. dataDir,
  12402. workspaceDir: "/workspace/accepted-recovery",
  12403. });
  12404. await first.ready;
  12405. first.editor.setText("already accepted by Runtime");
  12406. await new Promise((resolve) => setTimeout(resolve, 300));
  12407. first.editor.handleInput("\r");
  12408. await vi.waitFor(() =>
  12409. expect(runtime.sendMessage).toHaveBeenCalledOnce(),
  12410. );
  12411. await first.stop();
  12412. const restored = createTuiApp({
  12413. runtime: createRuntime(),
  12414. terminal: new FakeTerminal(),
  12415. version: "0.1.0",
  12416. dataDir,
  12417. workspaceDir: "/workspace/accepted-recovery",
  12418. });
  12419. await restored.ready;
  12420. expect(restored.editor.getText()).toBe("");
  12421. await restored.stop();
  12422. } finally {
  12423. await rm(dataDir, { recursive: true, force: true });
  12424. }
  12425. });
  12426. it("serializes rapid Session switches without mixing their Drafts", async () => {
  12427. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-"));
  12428. try {
  12429. const app = createTuiApp({
  12430. runtime: createRuntime(),
  12431. terminal: new FakeTerminal(),
  12432. version: "0.1.0",
  12433. dataDir,
  12434. workspaceDir: "/workspace/recovery",
  12435. });
  12436. await app.ready;
  12437. await app.openSession("session-a");
  12438. app.editor.setText("Draft for Session A");
  12439. await app.openSession("session-b");
  12440. app.editor.setText("Draft for Session B");
  12441. await Promise.all([
  12442. app.openSession("session-a"),
  12443. app.openSession("session-b"),
  12444. ]);
  12445. expect(app.controller.snapshot().session?.sessionId).toBe("session-b");
  12446. expect(app.editor.getText()).toBe("Draft for Session B");
  12447. await app.openSession("session-a");
  12448. expect(app.editor.getText()).toBe("Draft for Session A");
  12449. await app.openSession("session-b");
  12450. expect(app.editor.getText()).toBe("Draft for Session B");
  12451. await app.stop();
  12452. } finally {
  12453. await rm(dataDir, { recursive: true, force: true });
  12454. }
  12455. });
  12456. it("moves to the new-session Draft namespace after archiving the current Session", async () => {
  12457. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-"));
  12458. try {
  12459. const app = createTuiApp({
  12460. runtime: createRuntime(),
  12461. terminal: new FakeTerminal(),
  12462. version: "0.1.0",
  12463. dataDir,
  12464. workspaceDir: "/workspace/recovery",
  12465. });
  12466. await app.ready;
  12467. await app.openSession("session-a");
  12468. app.editor.setText("Archived Session Draft");
  12469. await app.submit("/archive");
  12470. app.editor.setText("Fresh Session Draft");
  12471. await app.openSession("session-a");
  12472. expect(app.editor.getText()).toBe("Archived Session Draft");
  12473. await app.submit("/new");
  12474. expect(app.editor.getText()).toBe("Fresh Session Draft");
  12475. await app.stop();
  12476. } finally {
  12477. await rm(dataDir, { recursive: true, force: true });
  12478. }
  12479. });
  12480. });
  12481. describe("interactive CLI model startup", () => {
  12482. it.each([
  12483. [
  12484. "new with prompt",
  12485. ["-m", "custom_provider:relay/vendor/model#thinking", "hello"],
  12486. "session-1",
  12487. true,
  12488. ],
  12489. [
  12490. "new without prompt",
  12491. ["--model=custom_provider:relay/vendor/model#thinking"],
  12492. "session-1",
  12493. false,
  12494. ],
  12495. [
  12496. "explicit session",
  12497. ["--session", "existing", "--model", "custom_provider:relay/vendor/model#thinking", "hello"],
  12498. "existing",
  12499. true,
  12500. ],
  12501. [
  12502. "continue",
  12503. ["--continue", "--model", "custom_provider:relay/vendor/model#thinking", "hello"],
  12504. "existing",
  12505. true,
  12506. ],
  12507. [
  12508. "missing session",
  12509. ["--session", "missing", "-m", "custom_provider:relay/vendor/model#thinking", "hello"],
  12510. "missing",
  12511. false,
  12512. ],
  12513. [
  12514. "empty continue",
  12515. ["--continue", "-m", "custom_provider:relay/vendor/model#thinking", "hello"],
  12516. "existing",
  12517. false,
  12518. ],
  12519. ["invalid provider", ["--model", "missing/model", "hello"], "session-1", false],
  12520. ["invalid model", ["--model", "custom_provider:relay/missing", "hello"], "session-1", false],
  12521. ] as const)(
  12522. "routes %s through launch, hydration and submission",
  12523. async (_name, args, sessionId, hasPrompt) => {
  12524. const dataDir = await mkdtemp(join(tmpdir(), "mcode-model-startup-"));
  12525. const terminal = new FakeTerminal();
  12526. const runtime = createRuntime();
  12527. runtime.listBackgroundTasks = vi.fn(async () => []);
  12528. const models = new Map<string, { providerId: string; modelId: string; variant?: string }>();
  12529. const requested = {
  12530. providerId: "custom_provider:relay",
  12531. modelId: "vendor/model",
  12532. variant: "thinking",
  12533. };
  12534. const existing = { sessionId: "existing", workspaceDir: "/workspace", updatedAt: 10 };
  12535. vi.mocked(runtime.listSessions).mockResolvedValue([existing]);
  12536. vi.mocked(runtime.listSessionPage).mockResolvedValue({
  12537. sessions: [existing],
  12538. hasMore: false,
  12539. });
  12540. vi.mocked(runtime.getSession).mockImplementation(async (id) => ({
  12541. sessionId: id,
  12542. workspaceDir: "/workspace",
  12543. model: models.get(id),
  12544. }));
  12545. const failedResume = _name === "missing session" || _name === "empty continue";
  12546. if (_name === "missing session")
  12547. vi.mocked(runtime.getSession).mockRejectedValue(new Error("Session not found"));
  12548. if (_name === "empty continue") vi.mocked(runtime.listSessions).mockResolvedValue([]);
  12549. runtime.selectModel = vi.fn(async () => true);
  12550. runtime.selectSessionModel = vi.fn(async (model, id) => {
  12551. if (model.providerId !== requested.providerId || model.modelId !== requested.modelId) {
  12552. throw new Error("Unknown provider or model");
  12553. }
  12554. models.set(id, model);
  12555. return true;
  12556. });
  12557. vi.mocked(runtime.listModels).mockImplementation(async (id) => [
  12558. { ...requested, name: "Startup model", selected: Boolean(id && models.has(id)) },
  12559. ]);
  12560. // A global managed default needs login; the selected BYOK Session does not.
  12561. vi.mocked(runtime.getAccountStatus).mockImplementation(async (id) => ({
  12562. status: id && models.has(id) ? "ready" : "needs-login",
  12563. modelSource: id && models.has(id) ? "byok" : "token-plan",
  12564. managedTokenPresent: false,
  12565. warnings: [],
  12566. }));
  12567. const sentModels: unknown[] = [];
  12568. vi.mocked(runtime.sendMessage).mockImplementation(async function* (request) {
  12569. sentModels.push(models.get(request.id));
  12570. yield { type: "delta", content: "offline reply" };
  12571. yield { type: "done" };
  12572. });
  12573. const invalid = _name.startsWith("invalid");
  12574. const stderr = vi.fn((_text: string, callback?: () => void) => callback?.());
  12575. const processRef = {
  12576. title: "test",
  12577. argv: ["node", "cli.js", ...args],
  12578. env: {},
  12579. versions: { node: "24.2.0" },
  12580. stdout: {
  12581. destroyed: false,
  12582. writableEnded: false,
  12583. write: vi.fn((_text: string, cb?: () => void) => cb?.()),
  12584. },
  12585. stderr: { destroyed: false, writableEnded: false, write: stderr },
  12586. exit: vi.fn(),
  12587. exitCode: 0,
  12588. };
  12589. let app: ReturnType<typeof createTuiApp> | undefined;
  12590. const running = runTuiCli({
  12591. processRef,
  12592. configureNetworkProxy: () => undefined,
  12593. launchTui: (input) =>
  12594. launchTui(
  12595. { ...input, dataDir, terminal, workspaceDir: "/workspace" },
  12596. {
  12597. createObservability,
  12598. readTelemetryEnabled: () => false,
  12599. installProcessGuards: () => () => undefined,
  12600. loadRuntimeLifecycle: async () => ({
  12601. createTuiRuntime: async () => ({ adapter: runtime }) as never,
  12602. shutdownTuiRuntime: async () => false,
  12603. }),
  12604. loadUpdateApplication: async () =>
  12605. ({ inspect: async () => ({ status: "up-to-date" }) }) as never,
  12606. createApp: (options) => {
  12607. app = createTuiApp({ ...options, productFeatures: { queue: false } });
  12608. return app;
  12609. },
  12610. writeExitMessage: () => undefined,
  12611. },
  12612. ),
  12613. });
  12614. try {
  12615. if (invalid) {
  12616. await running;
  12617. expect(processRef.exitCode).toBe(1);
  12618. expect(stderr.mock.calls.flat().join(" ")).toContain("Unknown provider or model");
  12619. expect(runtime.sendMessage).not.toHaveBeenCalled();
  12620. } else if (failedResume) {
  12621. await vi.waitFor(() => expect(app?.editor.disableSubmit).toBe(false));
  12622. expect(runtime.selectSessionModel).not.toHaveBeenCalled();
  12623. expect(runtime.createSession).not.toHaveBeenCalled();
  12624. expect(runtime.sendMessage).not.toHaveBeenCalled();
  12625. } else {
  12626. await vi.waitFor(() => {
  12627. expect(app?.editor.disableSubmit).toBe(false);
  12628. expect(app?.controller.snapshot().session?.model).toEqual(requested);
  12629. if (hasPrompt) expect(sentModels).toEqual([requested]);
  12630. });
  12631. expect(runtime.selectSessionModel).toHaveBeenCalledWith(requested, sessionId);
  12632. expect(app?.controller.snapshot().account?.modelSource).toBe("byok");
  12633. if (sessionId === "existing") expect(runtime.createSession).not.toHaveBeenCalled();
  12634. if (!hasPrompt) {
  12635. expect(runtime.sendMessage).not.toHaveBeenCalled();
  12636. await app?.submit("later prompt");
  12637. expect(sentModels).toEqual([requested]);
  12638. }
  12639. await vi.waitFor(() => expect(app?.controller.snapshot().status).toBe("idle"));
  12640. await app?.submit("/new");
  12641. expect(app?.controller.snapshot().session).toBeUndefined();
  12642. expect(runtime.selectSessionModel).toHaveBeenCalledOnce();
  12643. }
  12644. expect(runtime.selectModel).not.toHaveBeenCalled();
  12645. } finally {
  12646. await app?.stop();
  12647. await running;
  12648. await rm(dataDir, { recursive: true, force: true });
  12649. }
  12650. },
  12651. );
  12652. });
  12653. describe("interactive model argument contract", () => {
  12654. function program() {
  12655. const launch = vi.fn(async () => undefined);
  12656. const command = createTuiProgram({
  12657. version: "test",
  12658. launchTui: launch,
  12659. runExec: vi.fn(),
  12660. runLogin: vi.fn(),
  12661. runLogout: vi.fn(),
  12662. runUpdate: vi.fn(),
  12663. })
  12664. .exitOverride()
  12665. .configureOutput({ writeErr: () => undefined });
  12666. return { command, launch };
  12667. }
  12668. it.each(["-m", "--model"])("rejects missing values for %s", async (flag) => {
  12669. const { command, launch } = program();
  12670. await expect(command.parseAsync([flag], { from: "user" })).rejects.toThrow();
  12671. expect(launch).not.toHaveBeenCalled();
  12672. });
  12673. it.each(["", "bare-model", "provider/", "/model", "provider/model#"])(
  12674. "rejects malformed model %j before launch",
  12675. async (model) => {
  12676. const { command, launch } = program();
  12677. await expect(command.parseAsync(["--model", model], { from: "user" })).rejects.toThrow(
  12678. "--model must use provider/model",
  12679. );
  12680. expect(launch).not.toHaveBeenCalled();
  12681. },
  12682. );
  12683. it("rejects a model with an untargeted Session picker", async () => {
  12684. const { command, launch } = program();
  12685. await expect(
  12686. command.parseAsync(["--session", "--model", "provider/model"], { from: "user" }),
  12687. ).rejects.toThrow("requires a Session id");
  12688. expect(launch).not.toHaveBeenCalled();
  12689. });
  12690. it("retains the default launch contract without a model", async () => {
  12691. const { command, launch } = program();
  12692. await command.parseAsync(["hello"], { from: "user" });
  12693. expect(launch).toHaveBeenCalledWith({ initialPrompt: "hello" });
  12694. });
  12695. it.each(["-m", "--model"])("scans startup environment after %s values", (flag) => {
  12696. expect(
  12697. resolveTuiStartupEnvironmentOption([flag, "provider/model", "--env", "staging"], true),
  12698. ).toBe("staging");
  12699. expect(() =>
  12700. resolveTuiStartupEnvironmentOption([flag, "provider/model", "--env", "prod"], false),
  12701. ).toThrow("only available");
  12702. expect(
  12703. resolveTuiStartupEnvironmentOption(
  12704. [flag, "provider/model", "exec", "--env", "staging"],
  12705. true,
  12706. ),
  12707. ).toBeUndefined();
  12708. });
  12709. });