tui-app.test.ts 403 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176
  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 { createTuiApp } from "../../src/tui/app.js";
  12. import type {
  13. TuiModel,
  14. TuiQuestionnaireRequest,
  15. TuiQueuedMessage,
  16. TuiRuntimeEvent,
  17. TuiRuntime,
  18. TuiSessionForkPort,
  19. TuiStreamEvent,
  20. } from "../../src/runtime/port.js";
  21. import {
  22. normalizeTuiRuntimeEvent,
  23. type RawTuiRuntimeEvent,
  24. } from "../../src/runtime/event-normalizer.js";
  25. import type { SendMessageReq } from "@mavis/local-runtime-v2/cli-service";
  26. import type { TuiObservability } from "../../src/observability/local-observability.js";
  27. import type { McodeAuthProgress } from "../../src/auth/application.js";
  28. import { formatTuiShortcut } from "../../src/tui/shell/shortcut-labels.js";
  29. import { createTuiHostKeybindings } from "../../src/tui/shell/keybindings.js";
  30. import { stripAnsi } from "../../src/tui/rendering/text.js";
  31. import {
  32. TuiDraftRecovery,
  33. TuiDraftRecoveryError,
  34. } from "../../src/tui/features/composer/draft-recovery.js";
  35. import { composerText } from "../../src/tui/features/composer/copy.js";
  36. import type {
  37. McodeBusinessEvent,
  38. McodeBusinessTelemetry,
  39. } from "../../src/analytics/business-telemetry.js";
  40. import { VirtualTerminalScreen } from "../helpers/virtual-terminal.js";
  41. import { TuiFailure } from "../../src/failure.js";
  42. const runtimeEvent = (event: RawTuiRuntimeEvent): TuiRuntimeEvent =>
  43. normalizeTuiRuntimeEvent(event);
  44. function planReviewEventRequest(id: string) {
  45. return {
  46. schemaVersion: 2,
  47. id,
  48. mode: "plan",
  49. modePayload: {
  50. planReview: {
  51. markdown: "# Frozen plan\n\nImplement and verify the change.",
  52. path: "/history/session-1/artifacts/plan.md",
  53. },
  54. },
  55. presentation: {
  56. replaceComposer: true,
  57. showProgress: true,
  58. allowBackNavigation: true,
  59. },
  60. steps: [
  61. {
  62. id: "plan-review",
  63. question: "Approve?",
  64. selectionMode: "single",
  65. options: [{ id: "approve", label: "Approve" }],
  66. allowOther: true,
  67. required: true,
  68. },
  69. ],
  70. } as const;
  71. }
  72. function planEntryEventRequest(id: string) {
  73. return {
  74. schemaVersion: 2,
  75. id,
  76. mode: "plan",
  77. presentation: {
  78. replaceComposer: true,
  79. showProgress: true,
  80. allowBackNavigation: true,
  81. },
  82. steps: [
  83. {
  84. id: "plan-enter",
  85. question: "Enter Plan Mode for this task?",
  86. selectionMode: "single",
  87. options: [
  88. { id: "confirm", label: "Confirm" },
  89. { id: "decline", label: "Decline" },
  90. ],
  91. allowOther: true,
  92. otherPlaceholder: "Others...",
  93. required: true,
  94. },
  95. ],
  96. } as const;
  97. }
  98. function createObservability(): TuiObservability {
  99. return {
  100. recordStartup: vi.fn(),
  101. recordAccess: vi.fn(),
  102. recordEventStream: vi.fn(),
  103. recordTerminal: vi.fn(),
  104. recordProcessStop: vi.fn(),
  105. observeRender: vi.fn(),
  106. snapshot: vi.fn(() => ({
  107. filePath: "/tmp/mcode-observability.jsonl",
  108. eventCounts: {
  109. startup: 0,
  110. runtimeAccess: 0,
  111. eventStream: 0,
  112. terminal: 0,
  113. },
  114. accessSources: {},
  115. reconnects: 0,
  116. render: {
  117. frames: 0,
  118. averageDurationMs: 0,
  119. maxDurationMs: 0,
  120. p95DurationMs: 0,
  121. },
  122. })),
  123. flush: vi.fn(async () => undefined),
  124. };
  125. }
  126. class FakeTerminal implements Terminal {
  127. columns = 80;
  128. rows = 18;
  129. kittyProtocolActive = false;
  130. started = false;
  131. stopped = false;
  132. startCount = 0;
  133. stopCount = 0;
  134. drainCount = 0;
  135. title = "";
  136. titleUpdates: string[] = [];
  137. mouseTracking = false;
  138. mouseTrackingUpdates: boolean[] = [];
  139. writes: string[] = [];
  140. input?: (data: string) => void;
  141. start(onInput: (data: string) => void): void {
  142. this.started = true;
  143. this.stopped = false;
  144. this.startCount += 1;
  145. this.input = onInput;
  146. }
  147. stop(): void {
  148. this.stopped = true;
  149. this.stopCount += 1;
  150. }
  151. drainInput(): Promise<void> {
  152. this.drainCount += 1;
  153. return Promise.resolve();
  154. }
  155. write(data: string): void {
  156. this.writes.push(data);
  157. }
  158. moveBy(): void {}
  159. hideCursor(): void {}
  160. showCursor(): void {}
  161. clearLine(): void {}
  162. clearFromCursor(): void {}
  163. clearScreen(): void {}
  164. setProgress(): void {}
  165. setMouseTracking(enabled: boolean): void {
  166. this.mouseTracking = enabled;
  167. this.mouseTrackingUpdates.push(enabled);
  168. }
  169. setTitle(title: string): void {
  170. this.title = title;
  171. this.titleUpdates.push(title);
  172. }
  173. }
  174. function renderTerminalViewport(
  175. app: ReturnType<typeof createTuiApp>,
  176. terminal: FakeTerminal,
  177. ): string {
  178. app.tui.renderNow();
  179. const screen = new VirtualTerminalScreen(terminal.columns, terminal.rows);
  180. try {
  181. for (const write of terminal.writes) screen.feed(write);
  182. return screen.viewportText();
  183. } finally {
  184. screen.dispose();
  185. }
  186. }
  187. function createRuntime(): TuiRuntime {
  188. const abortSession = vi.fn(async () => true);
  189. let currentGoal: Awaited<ReturnType<TuiRuntime["getGoal"]>>;
  190. let createdSession:
  191. | {
  192. sessionId: string;
  193. title: string;
  194. workspaceDir: string;
  195. interactionMode?: "plan";
  196. }
  197. | undefined;
  198. const runtime: TuiRuntime = {
  199. createSession: vi.fn(async () => {
  200. createdSession = {
  201. sessionId: "session-1",
  202. title: "New session",
  203. workspaceDir: "/workspace",
  204. };
  205. return { ...createdSession };
  206. }),
  207. listSessions: vi.fn(async () => []),
  208. listSessionPage: vi.fn(async () => ({
  209. sessions: [],
  210. hasMore: false,
  211. })),
  212. getSession: vi.fn(async (sessionId: string) =>
  213. createdSession?.sessionId === sessionId
  214. ? { ...createdSession }
  215. : {
  216. sessionId,
  217. title: "Existing session",
  218. workspaceDir: "/workspace",
  219. },
  220. ),
  221. getMessages: vi.fn(async () => []),
  222. listMessagePage: vi.fn(async () => ({ messages: [], hasMore: false })),
  223. getSessionForkOptions: vi.fn(async () => ({
  224. canFork: true,
  225. worktreeVisible: false,
  226. worktreeEligible: false,
  227. })),
  228. forkSession: vi.fn(async () => ({
  229. session: {
  230. sessionId: "session-fork",
  231. parentSessionId: "session-1",
  232. title: "New session (fork 1)",
  233. workspaceDir: "/workspace",
  234. },
  235. })),
  236. getWorkspaceGitMetadata: vi.fn(async () => ({
  237. isGitRepo: false,
  238. branch: "",
  239. detached: false,
  240. isWorktree: false,
  241. })),
  242. renameSession: vi.fn(async (sessionId: string, title: string) => ({
  243. sessionId,
  244. title,
  245. workspaceDir: "/workspace",
  246. })),
  247. archiveSession: vi.fn(async () => undefined),
  248. listSessionInputSummaries: vi.fn(async () => []),
  249. getSessionRewindPreview: vi.fn(async () => ({ turns: [] })),
  250. rewindSession: vi.fn(async () => ({ rewound: true })),
  251. editSessionMessage: vi.fn(async () => ({
  252. rewound: true,
  253. turnId: "turn-edit-1",
  254. userMessageId: "msg-user-v1-edited",
  255. })),
  256. isGoalEnabled: vi.fn(() => true),
  257. getGoal: vi.fn(async () => currentGoal),
  258. createGoal: vi.fn(async ({ sessionId, objective, attachments }) => {
  259. currentGoal = {
  260. goalId: "goal-1",
  261. sessionId,
  262. objective,
  263. status: "active",
  264. createdAt: 10,
  265. updatedAt: 10,
  266. tokensUsed: 0,
  267. turnsUsed: 0,
  268. timeUsedSeconds: 0,
  269. tokenBudget: null,
  270. statusReason: null,
  271. hasKickoffAttachments: Boolean(attachments?.length),
  272. };
  273. return currentGoal;
  274. }),
  275. patchGoal: vi.fn(async (_sessionId, patch) => {
  276. if (!currentGoal) throw new Error("Goal not found");
  277. currentGoal = {
  278. ...currentGoal,
  279. ...patch,
  280. updatedAt: currentGoal.updatedAt + 1,
  281. };
  282. return currentGoal;
  283. }),
  284. clearGoal: vi.fn(async () => {
  285. const existed = Boolean(currentGoal);
  286. currentGoal = undefined;
  287. return existed;
  288. }),
  289. getInstructionSources: vi.fn(async () => []),
  290. getRuntimeDiagnostics: vi.fn(async () => ({
  291. status: "ok",
  292. surface: "cli-standalone",
  293. runtimeMode: "clean",
  294. runtimeOwnerKind: "cli",
  295. runtimeOwnerId: "minimax-code",
  296. dataDir: "/home/dev/.minimax",
  297. configPath: "/home/dev/.minimax/config.yaml",
  298. configPresent: true,
  299. authCachePresent: true,
  300. defaultModel: "minimax/MiniMax-M2.7",
  301. providerId: "minimax",
  302. modelId: "MiniMax-M2.7",
  303. authMode: "managed-login",
  304. authModeSource: "explicit",
  305. managedTokenPresent: true,
  306. apiKeyPresent: false,
  307. customProviderCount: 0,
  308. warnings: [],
  309. })),
  310. prepareFeedback: vi.fn(async ({ description, sessionId }) => ({
  311. schemaVersion: 1 as const,
  312. draftId: "feedback-draft-1",
  313. description,
  314. diagnostics: [
  315. { label: "Client", value: "mcode 0.1.0" },
  316. { label: "Runtime", value: "clean · cli" },
  317. { label: "Session", value: sessionId ?? "not included" },
  318. ],
  319. included: ["redacted feedback description"],
  320. excluded: ["credentials and tokens", "conversation prompts and messages"],
  321. expiresAtMs: Date.now() + 60_000,
  322. })),
  323. submitFeedback: vi.fn(async () => ({
  324. schemaVersion: 1 as const,
  325. ticketId: "ticket-1",
  326. status: "processing" as const,
  327. createdAtMs: Date.now(),
  328. })),
  329. cancelFeedback: vi.fn(async () => true),
  330. runDailyCheckin: vi.fn(async () => ({
  331. status: "claimed" as const,
  332. dayNo: 2,
  333. points: 20,
  334. expireAtMs: 1_800_000_000_000,
  335. panel: {
  336. scene: 2,
  337. days: Array.from({ length: 7 }, (_, index) => ({
  338. day_no: index + 1,
  339. points: (index + 1) * 10,
  340. status: index <= 1 ? 3 : 1,
  341. is_today: index === 1,
  342. })),
  343. },
  344. })),
  345. getAccountStatus: vi.fn(async () => ({
  346. status: "ready",
  347. defaultModel: "minimax/MiniMax-M2.7",
  348. providerId: "minimax",
  349. modelId: "MiniMax-M2.7",
  350. authMode: "managed-login",
  351. managedTokenPresent: true,
  352. warnings: [],
  353. })),
  354. listProviderPresets: vi.fn(async () => []),
  355. getCodexOAuthStatus: vi.fn(async () => ({
  356. state: "hidden" as const,
  357. providerId: "openai-codex" as const,
  358. })),
  359. startCodexOAuthLogin: vi.fn(async () => ({
  360. state: "hidden" as const,
  361. providerId: "openai-codex" as const,
  362. })),
  363. getPermissionMode: vi.fn(async () => "auto" as const),
  364. setPermissionMode: vi.fn(async (mode) => mode),
  365. getPlanModeCapabilities: vi.fn(async () => ({ entryEnabled: true })),
  366. getPendingQuestionnaire: vi.fn(async () => undefined),
  367. getLatestPlanReview: vi.fn(async () => undefined),
  368. replyQuestionnaire: vi.fn(async () => true),
  369. dismissQuestionnaire: vi.fn(async () => true),
  370. listPendingPermissions: vi.fn(async () => []),
  371. replyPermission: vi.fn(async () => true),
  372. listModels: vi.fn(async () => [
  373. {
  374. providerId: "minimax",
  375. modelId: "MiniMax-M2.7",
  376. displayName: "MiniMax M2.7",
  377. providerKind: "minimax-managed",
  378. selected: true,
  379. },
  380. ]),
  381. selectModel: vi.fn(async () => true),
  382. getSessionUsage: vi.fn(async () => ({
  383. summary: {
  384. inputTokens: 100,
  385. outputTokens: 20,
  386. totalTokens: 120,
  387. turns: 1,
  388. },
  389. rows: [],
  390. })),
  391. requestCompaction: vi.fn(async () => ({
  392. success: true,
  393. sessionId: "session-1",
  394. compactionId: "compact-1",
  395. messagesBefore: 12,
  396. messagesAfter: 4,
  397. tokensBefore: 4000,
  398. tokensAfter: 1200,
  399. })),
  400. getContextSnapshot: vi.fn(async () => ({ status: "empty" as const })),
  401. getActiveRun: vi.fn(async (sessionId: string) => ({
  402. schemaVersion: 1 as const,
  403. sessionId,
  404. state: "idle" as const,
  405. actions: { steer: false },
  406. })),
  407. getDelegationSnapshot: vi.fn(async (rootSessionId: string) => ({
  408. schemaVersion: 1 as const,
  409. rootSessionId,
  410. members: [],
  411. })),
  412. stopDelegation: vi.fn(async (rootSessionId: string) => ({
  413. schemaVersion: 1 as const,
  414. rootSessionId,
  415. rootStopped: await abortSession({ id: rootSessionId }),
  416. stoppedSessionIds: [],
  417. activeSessionIds: [],
  418. failedSessionIds: [],
  419. })),
  420. steer: vi.fn(async (input) => ({
  421. turnId: input.requestedTurnId ?? "turn-steer",
  422. mode: input.requestedTurnId
  423. ? ("steered" as const)
  424. : ("activated" as const),
  425. ...(input.requestedTurnId
  426. ? {}
  427. : {
  428. completion:
  429. (async function* completion(): AsyncGenerator<TuiStreamEvent> {
  430. yield { type: "done", turnId: "turn-steer" };
  431. })(),
  432. }),
  433. })),
  434. listSkills: vi.fn(async () => ({
  435. skills: [
  436. {
  437. name: "docs",
  438. displayName: "Docs",
  439. description: "Read project docs",
  440. enabled: true,
  441. sourceKind: "builtin",
  442. },
  443. ],
  444. hasMore: false,
  445. })),
  446. inspectProjectMcp: vi.fn(async () => undefined),
  447. listMcpServers: vi.fn(async () => [
  448. {
  449. name: "browser",
  450. enabled: true,
  451. transport: "stdio",
  452. description: "Browser tools",
  453. configJson: '{"env":{"TOKEN":"hidden"}}',
  454. },
  455. ]),
  456. listQueuedMessages: vi.fn(async () => []),
  457. getQueueSnapshot: vi.fn(async (sessionId: string) => {
  458. const items = await runtime.listQueuedMessages(sessionId);
  459. return {
  460. items,
  461. paused: items.some((item) => item.status === "paused"),
  462. pendingCount: items.length,
  463. };
  464. }),
  465. continueQueue: vi.fn(async () => undefined),
  466. steerQueuedMessage: vi.fn(async (_sessionId: string, itemId: string) => ({
  467. queueItemId: itemId,
  468. turnId: "turn-steered-queue",
  469. })),
  470. enqueueMessage: vi.fn(async () => ({
  471. itemId: "queue-1",
  472. status: "queued",
  473. position: 1,
  474. })),
  475. updateQueuedMessageContent: vi.fn(async () => undefined),
  476. deleteQueuedMessage: vi.fn(async () => undefined),
  477. watchEvents: vi.fn(async function* watchEvents(signal) {
  478. await new Promise<void>((resolve) => {
  479. signal.addEventListener("abort", resolve, { once: true });
  480. });
  481. for (const event of [] as TuiRuntimeEvent[]) yield event;
  482. }),
  483. watchSessionTurn: vi.fn(async function* watchSessionTurn() {}),
  484. sendMessage: vi.fn(
  485. async function* sendMessage(request): AsyncGenerator<TuiStreamEvent> {
  486. if (createdSession?.sessionId === request.id) {
  487. if (request.clientIntent === "plan-entry")
  488. createdSession.interactionMode = "plan";
  489. if (request.clientIntent === "plan-exit")
  490. delete createdSession.interactionMode;
  491. }
  492. yield { type: "delta", content: "Hello from the Agent" };
  493. yield { type: "done" };
  494. },
  495. ),
  496. abortSession,
  497. };
  498. return runtime;
  499. }
  500. describe("createTuiApp", () => {
  501. it.each(["regular", "fullscreen"] as const)(
  502. "configures /statusline from terminal input and reopens the saved selection in %s mode",
  503. async (tuiMode) => {
  504. const terminal = new FakeTerminal();
  505. const runtime = createRuntime();
  506. const persistStatusLineItems = vi.fn(async () => undefined);
  507. const app = createTuiApp({
  508. runtime,
  509. terminal,
  510. version: "test",
  511. workspaceDir: "/workspace",
  512. tuiMode,
  513. statusLineItems: ["current-dir"],
  514. persistStatusLineItems,
  515. });
  516. try {
  517. app.start();
  518. await app.ready;
  519. app.editor.setText("/statusline");
  520. terminal.input?.("\r");
  521. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  522. expect(stripAnsi(app.interaction.render(80).join("\n"))).toContain(
  523. "[x] current-dir",
  524. );
  525. terminal.input?.(" ");
  526. terminal.input?.("\r");
  527. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  528. expect(persistStatusLineItems).toHaveBeenCalledWith([]);
  529. app.editor.setText("/statusline");
  530. terminal.input?.("\r");
  531. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  532. expect(stripAnsi(app.interaction.render(80).join("\n"))).toContain(
  533. "[ ] current-dir",
  534. );
  535. terminal.input?.("\x1b");
  536. expect(app.interaction.isActive()).toBe(false);
  537. expect(persistStatusLineItems).toHaveBeenCalledOnce();
  538. expect(runtime.sendMessage).not.toHaveBeenCalled();
  539. } finally {
  540. await app.stop();
  541. }
  542. },
  543. );
  544. it.each([
  545. ["regular", false],
  546. ["regular", true],
  547. ["fullscreen", false],
  548. ["fullscreen", true],
  549. ] as const)(
  550. "runs ls unchanged in %s mode after empty-prefix Tab: %s",
  551. async (tuiMode, pressTab) => {
  552. const directory = await mkdtemp(join(tmpdir(), "tui-ls-enter-"));
  553. await mkdir(join(directory, "aaa-directory"));
  554. await writeFile(join(directory, "root-only.txt"), "root");
  555. const terminal = new FakeTerminal();
  556. const runtime = createRuntime();
  557. const app = createTuiApp({
  558. runtime,
  559. terminal,
  560. version: "0.1.0",
  561. workspaceDir: directory,
  562. tuiMode,
  563. });
  564. try {
  565. app.start();
  566. await app.ready;
  567. app.editor.setText("!ls");
  568. terminal.input?.(" ");
  569. expect(stripAnsi(app.editor.render(100).join("\n"))).not.toContain(
  570. "aaa-directory/",
  571. );
  572. if (pressTab) {
  573. terminal.input?.("\t");
  574. await vi.waitFor(() =>
  575. expect(stripAnsi(app.editor.render(100).join("\n"))).toContain(
  576. "aaa-directory/",
  577. ),
  578. );
  579. }
  580. expect(app.editor.getText()).toBe("!ls ");
  581. terminal.input?.("\r");
  582. await vi.waitFor(
  583. () =>
  584. expect(
  585. app.transcript.snapshot().find((cell) => cell.kind === "shell")
  586. ?.status,
  587. ).toBe("succeeded"),
  588. { timeout: 5000 },
  589. );
  590. expect(
  591. app.transcript.snapshot().find((cell) => cell.kind === "shell"),
  592. ).toMatchObject({
  593. title: "! ls",
  594. content: expect.stringContaining("root-only.txt"),
  595. });
  596. expect(runtime.sendMessage).not.toHaveBeenCalled();
  597. } finally {
  598. await app.stop();
  599. await rm(directory, { recursive: true, force: true });
  600. }
  601. },
  602. );
  603. it.each(["regular", "fullscreen"] as const)(
  604. "completes a shell path from terminal input in %s mode before executing",
  605. async (tuiMode) => {
  606. const directory = await mkdtemp(
  607. join(tmpdir(), "tui-shell-completion-app-"),
  608. );
  609. await writeFile(
  610. join(directory, "report file.txt"),
  611. "completed-shell-output",
  612. );
  613. const terminal = new FakeTerminal();
  614. const runtime = createRuntime();
  615. const app = createTuiApp({
  616. runtime,
  617. terminal,
  618. version: "0.1.0",
  619. workspaceDir: directory,
  620. tuiMode,
  621. });
  622. try {
  623. app.start();
  624. await app.ready;
  625. app.editor.setText(
  626. process.platform === "win32" ? "!Get-Content " : "!cat ",
  627. );
  628. for (const char of "rep") terminal.input?.(char);
  629. expect(app.editor.getText()).toBe(
  630. process.platform === "win32" ? "!Get-Content rep" : "!cat rep",
  631. );
  632. terminal.input?.("\t");
  633. await vi.waitFor(() =>
  634. expect(app.editor.getText()).toBe(
  635. process.platform === "win32"
  636. ? "!Get-Content report` file.txt "
  637. : "!cat report\\ file.txt ",
  638. ),
  639. );
  640. expect(
  641. app.transcript
  642. .snapshot()
  643. .some((cell) => cell.id.startsWith("local:bash:")),
  644. ).toBe(false);
  645. terminal.input?.("\r");
  646. await vi.waitFor(
  647. () =>
  648. expect(
  649. app.transcript
  650. .snapshot()
  651. .some(
  652. (cell) =>
  653. cell.id.startsWith("local:bash:") &&
  654. cell.status === "succeeded" &&
  655. cell.content.includes("completed-shell-output"),
  656. ),
  657. ).toBe(true),
  658. { timeout: 5000 },
  659. );
  660. expect(runtime.sendMessage).not.toHaveBeenCalled();
  661. } finally {
  662. await app.stop();
  663. await rm(directory, { recursive: true, force: true });
  664. }
  665. },
  666. );
  667. it("runs an editor ! command locally and carries its result into the next model message", async () => {
  668. const directory = await mkdtemp(join(tmpdir(), "tui-bash-app-"));
  669. const runtime = createRuntime();
  670. const app = createTuiApp({
  671. runtime,
  672. terminal: new FakeTerminal(),
  673. version: "0.1.0",
  674. workspaceDir: directory,
  675. });
  676. try {
  677. await app.ready;
  678. app.editor.setText(
  679. process.platform === "win32"
  680. ? "!Write-Output shell-result"
  681. : "!printf shell-result",
  682. );
  683. app.editor.submit();
  684. await vi.waitFor(
  685. () =>
  686. expect(
  687. app.transcript
  688. .snapshot()
  689. .some(
  690. (cell) =>
  691. cell.id.startsWith("local:bash:") &&
  692. cell.status === "succeeded",
  693. ),
  694. ).toBe(true),
  695. { timeout: 5000 },
  696. );
  697. expect(runtime.sendMessage).not.toHaveBeenCalled();
  698. expect(
  699. app.transcript
  700. .snapshot()
  701. .find((cell) => cell.id.startsWith("local:bash:"))?.content,
  702. ).toContain("shell-result");
  703. expect(stripAnsi(app.tui.render(100).join("\n"))).toContain(
  704. "shell-result",
  705. );
  706. await app.submit("Explain the output");
  707. expect(runtime.sendMessage).toHaveBeenCalledWith(
  708. expect.objectContaining({
  709. content: expect.stringContaining("shell-result"),
  710. }),
  711. expect.anything(),
  712. );
  713. } finally {
  714. await app.stop();
  715. await rm(directory, { recursive: true, force: true });
  716. }
  717. });
  718. it("shows shell output before the command exits and drains it when the app stops", async () => {
  719. const directory = await mkdtemp(join(tmpdir(), "tui-bash-stream-"));
  720. const app = createTuiApp({
  721. runtime: createRuntime(),
  722. terminal: new FakeTerminal(),
  723. version: "0.1.0",
  724. workspaceDir: directory,
  725. });
  726. try {
  727. await app.ready;
  728. const running = app.submit(
  729. process.platform === "win32"
  730. ? "!Write-Output streamed-result; Start-Sleep -Seconds 30"
  731. : "!printf streamed-result; sleep 30",
  732. );
  733. await vi.waitFor(
  734. () =>
  735. expect(
  736. app.transcript
  737. .snapshot()
  738. .some(
  739. (cell) =>
  740. cell.status === "running" &&
  741. cell.content.includes("streamed-result"),
  742. ),
  743. ).toBe(true),
  744. { timeout: 5000 },
  745. );
  746. expect(stripAnsi(app.tui.render(100).join("\n"))).toContain(
  747. "streamed-result",
  748. );
  749. await app.stop();
  750. await running;
  751. expect(
  752. app.transcript
  753. .snapshot()
  754. .find((cell) => cell.id.startsWith("local:bash:"))?.status,
  755. ).toBe("cancelled");
  756. } finally {
  757. await app.stop();
  758. await rm(directory, { recursive: true, force: true });
  759. }
  760. });
  761. it("continues a restored paused Queue from its manager without sending a new message", async () => {
  762. const terminal = new FakeTerminal();
  763. const runtime = createRuntime();
  764. let paused = true;
  765. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  766. {
  767. itemId: "paused-follow-up",
  768. sessionId: "session-1",
  769. status: paused ? "paused" : "queued",
  770. content: "Existing queued work",
  771. },
  772. ]);
  773. vi.mocked(runtime.continueQueue).mockImplementation(async () => {
  774. paused = false;
  775. });
  776. const app = createTuiApp({
  777. runtime,
  778. terminal,
  779. version: "test",
  780. workspaceDir: "/workspace",
  781. productFeatures: { queue: true },
  782. });
  783. app.start();
  784. try {
  785. await app.ready;
  786. await app.openSession("session-1");
  787. await app.submit("/queue");
  788. expect(app.tui.render(120).join("\n")).toContain("c continue queue");
  789. terminal.input?.("c");
  790. await vi.waitFor(() =>
  791. expect(runtime.continueQueue).toHaveBeenCalledWith("session-1"),
  792. );
  793. await vi.waitFor(() =>
  794. expect(app.tui.render(120).join("\n")).toContain("Queue continued."),
  795. );
  796. expect(runtime.sendMessage).not.toHaveBeenCalled();
  797. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  798. expect(runtime.deleteQueuedMessage).not.toHaveBeenCalled();
  799. } finally {
  800. await app.stop();
  801. }
  802. });
  803. it.each(["keep", "clear", "cancel-enter", "cancel-escape"] as const)(
  804. "recovers a restored paused Queue when sending a message: %s",
  805. async (decision) => {
  806. const dataDir = await mkdtemp(join(tmpdir(), "tui-paused-queue-draft-"));
  807. const terminal = new FakeTerminal();
  808. const runtime = createRuntime();
  809. let items: TuiQueuedMessage[] = [
  810. {
  811. itemId: "paused-follow-up",
  812. sessionId: "session-1",
  813. status: "paused",
  814. content: "Existing queued work",
  815. },
  816. ];
  817. let emitQueueChange:
  818. | ((event: TuiRuntimeEvent | undefined) => void)
  819. | undefined;
  820. vi.mocked(runtime.watchEvents).mockImplementation(
  821. async function* (signal) {
  822. const event = await new Promise<TuiRuntimeEvent | undefined>(
  823. (resolve) => {
  824. emitQueueChange = resolve;
  825. signal.addEventListener("abort", () => resolve(undefined), {
  826. once: true,
  827. });
  828. },
  829. );
  830. if (!event || signal.aborted) return;
  831. yield event;
  832. if (!signal.aborted) {
  833. await new Promise<void>((resolve) => {
  834. signal.addEventListener("abort", () => resolve(), { once: true });
  835. });
  836. }
  837. },
  838. );
  839. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  840. ...items,
  841. ]);
  842. vi.mocked(runtime.sendMessage).mockImplementation(
  843. async function* (request, _signal, options) {
  844. if (!options?.pausedQueueAction) {
  845. throw new TuiFailure("runtime", "Queue paused", {
  846. code: "local_session_queue_paused",
  847. });
  848. }
  849. items =
  850. options.pausedQueueAction === "clear"
  851. ? []
  852. : items.map((item) => ({ ...item, status: "queued" }));
  853. emitQueueChange?.({
  854. type: "session.queue.updated",
  855. sessionId: "session-1",
  856. source: "runtime-v2",
  857. timestampMs: Date.now(),
  858. });
  859. yield { type: "done", turnId: request.turnId };
  860. },
  861. );
  862. const appOptions = {
  863. runtime,
  864. terminal,
  865. version: "test",
  866. dataDir,
  867. workspaceDir: "/workspace",
  868. productFeatures: { queue: true },
  869. };
  870. let app = createTuiApp(appOptions);
  871. app.start();
  872. try {
  873. await app.ready;
  874. await app.openSession("session-1");
  875. await vi.waitFor(() => expect(emitQueueChange).toBeTypeOf("function"));
  876. await vi.waitFor(() =>
  877. expect(app.tui.render(120).join("\n")).toContain(
  878. "Existing queued work",
  879. ),
  880. );
  881. terminal.input?.("Resume safely");
  882. terminal.input?.("\r");
  883. await vi.waitFor(() =>
  884. expect(app.tui.render(120).join("\n")).toContain("Keep my draft"),
  885. );
  886. const cancelled = decision.startsWith("cancel");
  887. if (decision === "cancel-escape") terminal.input?.("\u001b");
  888. else {
  889. if (decision === "clear") terminal.input?.("\u001b[B");
  890. if (decision === "cancel-enter") {
  891. terminal.input?.("\u001b[B");
  892. terminal.input?.("\u001b[B");
  893. }
  894. terminal.input?.("\r");
  895. }
  896. await vi.waitFor(() =>
  897. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  898. );
  899. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  900. if (cancelled) {
  901. await vi.waitFor(() =>
  902. expect(app.editor.getText()).toBe("Resume safely"),
  903. );
  904. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  905. expect(runtime.continueQueue).not.toHaveBeenCalled();
  906. expect(runtime.deleteQueuedMessage).not.toHaveBeenCalled();
  907. expect(
  908. app.transcript.snapshot().filter((cell) => cell.kind === "user"),
  909. ).toEqual([]);
  910. expect(
  911. app.transcript.snapshot().filter((cell) => cell.kind === "error"),
  912. ).toEqual([]);
  913. expect(app.tui.render(120).join("\n")).toContain("Queue paused");
  914. expect(app.tui.render(120).join("\n")).not.toContain("Keep my draft");
  915. await vi.waitFor(async () => {
  916. const recovered = await new TuiDraftRecovery({
  917. dataDir,
  918. workspaceDir: "/workspace",
  919. sessionKey: "session-1",
  920. }).load();
  921. expect(recovered?.editor.text).toBe("Resume safely");
  922. expect(recovered?.retrySubmissions ?? []).toEqual([]);
  923. });
  924. app.editor.setText("Edited draft");
  925. await app.stop();
  926. app = createTuiApp(appOptions);
  927. app.start();
  928. await app.ready;
  929. await app.openSession("session-1");
  930. await vi.waitFor(() =>
  931. expect(app.editor.getText()).toBe("Edited draft"),
  932. );
  933. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  934. terminal.input?.("\r");
  935. await vi.waitFor(() =>
  936. expect(app.tui.render(120).join("\n")).toContain("Keep my draft"),
  937. );
  938. terminal.input?.("\r");
  939. await vi.waitFor(() =>
  940. expect(runtime.sendMessage).toHaveBeenCalledTimes(3),
  941. );
  942. await vi.waitFor(() =>
  943. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  944. );
  945. expect(
  946. vi.mocked(runtime.sendMessage).mock.calls[2]?.[0],
  947. ).toMatchObject({
  948. content: "Edited draft",
  949. });
  950. expect(vi.mocked(runtime.sendMessage).mock.calls[2]?.[2]).toEqual({
  951. pausedQueueAction: "keep",
  952. });
  953. await vi.waitFor(() =>
  954. expect(app.tui.render(120).join("\n")).not.toContain(
  955. "Queue paused",
  956. ),
  957. );
  958. expect(app.editor.getText()).toBe("");
  959. expect(app.tui.render(120).join("\n")).toContain(
  960. "Existing queued work",
  961. );
  962. } else {
  963. expect(runtime.sendMessage).toHaveBeenCalledTimes(2);
  964. expect(
  965. vi.mocked(runtime.sendMessage).mock.calls[1]?.[0],
  966. ).toMatchObject({
  967. content: "Resume safely",
  968. });
  969. expect(vi.mocked(runtime.sendMessage).mock.calls[1]?.[2]).toEqual({
  970. pausedQueueAction: decision,
  971. });
  972. await vi.waitFor(() =>
  973. expect(app.tui.render(120).join("\n")).not.toContain(
  974. "Queue paused",
  975. ),
  976. );
  977. const rendered = app.tui.render(120).join("\n");
  978. if (decision === "clear")
  979. expect(rendered).not.toContain("Existing queued work");
  980. else expect(rendered).toContain("Existing queued work");
  981. }
  982. } finally {
  983. await app.stop();
  984. await rm(dataDir, { recursive: true, force: true });
  985. }
  986. },
  987. );
  988. it.each([
  989. ["plan-entry", "keep"],
  990. ["plan-entry", "clear"],
  991. ["plan-entry", "cancel"],
  992. ["plan-entry", "busy"],
  993. ["plan-exit", "keep"],
  994. ["plan-exit", "clear"],
  995. ["plan-exit", "cancel"],
  996. ["plan-exit", "busy"],
  997. ] as const)(
  998. "recovers a paused Queue with %s and decision %s",
  999. async (clientIntent, decision) => {
  1000. const terminal = new FakeTerminal();
  1001. const runtime = createRuntime();
  1002. let interactionMode: "plan" | undefined =
  1003. clientIntent === "plan-exit" ? "plan" : undefined;
  1004. let rejectRecovery = decision === "busy";
  1005. vi.mocked(runtime.getSession).mockImplementation(async () => ({
  1006. sessionId: "session-1",
  1007. interactionMode,
  1008. }));
  1009. vi.mocked(runtime.listQueuedMessages).mockResolvedValue([
  1010. {
  1011. itemId: "paused-work",
  1012. sessionId: "session-1",
  1013. status: "paused",
  1014. content: "Existing work",
  1015. },
  1016. ]);
  1017. vi.mocked(runtime.sendMessage).mockImplementation(
  1018. async function* (request, _signal, options) {
  1019. if (!options?.pausedQueueAction || rejectRecovery) {
  1020. throw new TuiFailure("runtime", "Admission rejected", {
  1021. code: options?.pausedQueueAction
  1022. ? "local_session_busy"
  1023. : "local_session_queue_paused",
  1024. });
  1025. }
  1026. interactionMode =
  1027. request.clientIntent === "plan-entry" ? "plan" : undefined;
  1028. yield { type: "done", turnId: request.turnId };
  1029. },
  1030. );
  1031. const app = createTuiApp({
  1032. runtime,
  1033. terminal,
  1034. version: "test",
  1035. workspaceDir: "/workspace",
  1036. productFeatures: { queue: true },
  1037. });
  1038. app.start();
  1039. try {
  1040. await app.ready;
  1041. await app.openSession("session-1");
  1042. await app.submit(
  1043. clientIntent === "plan-entry" ? "/plan on" : "/plan off",
  1044. );
  1045. terminal.input?.("Change mode and continue");
  1046. terminal.input?.("\r");
  1047. await vi.waitFor(() =>
  1048. expect(app.tui.render(120).join("\n")).toContain("Keep my draft"),
  1049. );
  1050. if (decision === "clear" || decision === "cancel")
  1051. terminal.input?.("\u001b[B");
  1052. if (decision === "cancel") terminal.input?.("\u001b[B");
  1053. terminal.input?.("\r");
  1054. await vi.waitFor(() =>
  1055. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  1056. );
  1057. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  1058. if (decision === "cancel" || decision === "busy") {
  1059. await vi.waitFor(() =>
  1060. expect(app.editor.getText()).toBe("Change mode and continue"),
  1061. );
  1062. expect(interactionMode === "plan").toBe(clientIntent === "plan-exit");
  1063. rejectRecovery = false;
  1064. app.editor.setText("Edited mode instruction");
  1065. terminal.input?.("\r");
  1066. await vi.waitFor(() =>
  1067. expect(app.tui.render(120).join("\n")).toContain("Keep my draft"),
  1068. );
  1069. terminal.input?.("\r");
  1070. await vi.waitFor(() =>
  1071. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  1072. );
  1073. }
  1074. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  1075. expect.objectContaining({ clientIntent }),
  1076. expect.any(AbortSignal),
  1077. { pausedQueueAction: decision === "clear" ? "clear" : "keep" },
  1078. );
  1079. expect(interactionMode === "plan").toBe(clientIntent === "plan-entry");
  1080. expect(app.editor.getText()).toBe("");
  1081. } finally {
  1082. await app.stop();
  1083. }
  1084. },
  1085. );
  1086. it("shows the MCode prompt in an empty Composer and hides it after input", async () => {
  1087. const app = createTuiApp({
  1088. runtime: createRuntime(),
  1089. terminal: new FakeTerminal(),
  1090. version: "0.1.0",
  1091. workspaceDir: "/workspace",
  1092. });
  1093. try {
  1094. app.start();
  1095. await app.ready;
  1096. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  1097. "Ask Mcode to do anything",
  1098. );
  1099. app.editor.handleInput("R");
  1100. expect(stripAnsi(app.tui.render(80).join("\n"))).not.toContain(
  1101. "Ask Mcode to do anything",
  1102. );
  1103. expect(app.editor.getText()).toBe("R");
  1104. } finally {
  1105. await app.stop();
  1106. }
  1107. });
  1108. it("copies the last Assistant reply to the client clipboard over SSH", async () => {
  1109. vi.stubEnv("SSH_CONNECTION", "10.0.0.1 50100 10.0.0.2 22");
  1110. vi.stubEnv("SSH_TTY", "/dev/pts/1");
  1111. Object.defineProperty(process.stdin, "isTTY", {
  1112. configurable: true,
  1113. value: true,
  1114. });
  1115. Object.defineProperty(process.stdout, "isTTY", {
  1116. configurable: true,
  1117. value: true,
  1118. });
  1119. const terminal = new FakeTerminal();
  1120. let app: ReturnType<typeof createTuiApp> | undefined;
  1121. try {
  1122. app = createTuiApp({
  1123. runtime: createRuntime(),
  1124. terminal,
  1125. version: "0.1.0",
  1126. workspaceDir: "/workspace",
  1127. });
  1128. app.start();
  1129. await app.ready;
  1130. await app.submit("Say hello");
  1131. await app.submit("/copy");
  1132. expect(terminal.writes).toContain(
  1133. "\u001B]52;c;SGVsbG8gZnJvbSB0aGUgQWdlbnQ=\u0007",
  1134. );
  1135. } finally {
  1136. await app?.stop();
  1137. Reflect.deleteProperty(process.stdin, "isTTY");
  1138. Reflect.deleteProperty(process.stdout, "isTTY");
  1139. vi.unstubAllEnvs();
  1140. }
  1141. });
  1142. it("runs /goal through Runtime ownership and renders the active Goal above the Composer", async () => {
  1143. const runtime = createRuntime();
  1144. const app = createTuiApp({
  1145. runtime,
  1146. terminal: new FakeTerminal(),
  1147. version: "0.1.0",
  1148. workspaceDir: "/workspace",
  1149. });
  1150. app.start();
  1151. await app.ready;
  1152. await app.submit("/goal Ship TUI Goal support");
  1153. expect(runtime.createSession).toHaveBeenCalledOnce();
  1154. expect(runtime.createGoal).toHaveBeenCalledWith({
  1155. sessionId: "session-1",
  1156. objective: "Ship TUI Goal support",
  1157. });
  1158. expect(runtime.sendMessage).not.toHaveBeenCalled();
  1159. expect(app.surfaceHost.render(100).join("\n")).toContain("Goal · Active");
  1160. expect(app.surfaceHost.render(100).join("\n")).toContain(
  1161. "Ship TUI Goal support",
  1162. );
  1163. await app.submit("/goal pause");
  1164. expect(runtime.patchGoal).toHaveBeenCalledWith("session-1", {
  1165. status: "paused",
  1166. });
  1167. expect(app.surfaceHost.render(100).join("\n")).toContain("Goal · Paused");
  1168. await app.stop();
  1169. });
  1170. it("wires complete chat and autocomplete business events into the TUI surface", async () => {
  1171. const events: McodeBusinessEvent[] = [];
  1172. const businessTelemetry: McodeBusinessTelemetry = {
  1173. track: (event, properties) =>
  1174. events.push({ event, properties } as McodeBusinessEvent),
  1175. flush: async () => undefined,
  1176. };
  1177. const app = createTuiApp({
  1178. runtime: createRuntime(),
  1179. terminal: new FakeTerminal(),
  1180. version: "0.1.0",
  1181. workspaceDir: "/workspace/agent-archon",
  1182. businessTelemetry,
  1183. });
  1184. await app.ready;
  1185. await app.submit("First prompt");
  1186. await app.submit("Second prompt");
  1187. for (const character of "/he") app.editor.handleInput(character);
  1188. await vi.waitFor(() =>
  1189. expect(
  1190. events.some((item) => item.event === "slash_command_menu_view"),
  1191. ).toBe(true),
  1192. );
  1193. app.editor.handleInput("\r");
  1194. expect(events.filter((item) => item.event === "chat_send")).toEqual([
  1195. {
  1196. event: "chat_send",
  1197. properties: {
  1198. chat_type: "chat",
  1199. is_first_message: 1,
  1200. is_attachment: "text",
  1201. },
  1202. },
  1203. {
  1204. event: "chat_send",
  1205. properties: {
  1206. chat_type: "chat",
  1207. is_first_message: 0,
  1208. is_attachment: "text",
  1209. },
  1210. },
  1211. ]);
  1212. expect(events).toContainEqual({
  1213. event: "slash_command_click",
  1214. properties: {
  1215. chat_type: "chat",
  1216. command_type: "other",
  1217. },
  1218. });
  1219. await app.stop();
  1220. });
  1221. it("releases the terminal on suspend and reconciles Runtime state after resume", async () => {
  1222. const terminal = new FakeTerminal();
  1223. const runtime = createRuntime();
  1224. const requestProcessSuspend = vi.fn();
  1225. vi.mocked(runtime.watchEvents).mockImplementation(
  1226. async function* watchEvents(signal) {
  1227. await new Promise<void>((resolve) => {
  1228. signal.addEventListener("abort", resolve, { once: true });
  1229. });
  1230. yield* [];
  1231. },
  1232. );
  1233. const app = createTuiApp({
  1234. runtime,
  1235. terminal,
  1236. version: "0.1.0",
  1237. workspaceDir: "/workspace",
  1238. requestProcessSuspend,
  1239. });
  1240. app.start();
  1241. await app.ready;
  1242. await app.openSession("session-1");
  1243. await vi.waitFor(() => expect(runtime.watchEvents).toHaveBeenCalledOnce());
  1244. terminal.input?.("\x1a");
  1245. expect(requestProcessSuspend).toHaveBeenCalledOnce();
  1246. await app.suspend();
  1247. expect(terminal.stopCount).toBe(1);
  1248. expect(app.controller.snapshot().status).not.toBe("error");
  1249. await app.resume();
  1250. expect(terminal.startCount).toBe(2);
  1251. await vi.waitFor(() =>
  1252. expect(runtime.watchEvents).toHaveBeenCalledTimes(2),
  1253. );
  1254. expect(runtime.getActiveRun).toHaveBeenCalled();
  1255. await app.stop();
  1256. });
  1257. it.each(["regular", "fullscreen"] as const)(
  1258. "restores %s Composer input after Ctrl+G returns from the external editor",
  1259. async (tuiMode) => {
  1260. const terminal = new FakeTerminal();
  1261. const stopTerminal = vi.spyOn(terminal, "stop");
  1262. const startTerminal = vi.spyOn(terminal, "start");
  1263. const editDraftInExternalEditor = vi.fn(
  1264. async () => "edited in the external editor",
  1265. );
  1266. const app = createTuiApp({
  1267. runtime: createRuntime(),
  1268. terminal,
  1269. version: "0.1.0",
  1270. workspaceDir: "/workspace",
  1271. tuiMode,
  1272. externalEditorCommand: "code --wait",
  1273. editDraftInExternalEditor,
  1274. });
  1275. app.start();
  1276. await app.ready;
  1277. const longPaste = Array.from(
  1278. { length: 12 },
  1279. (_, index) => `line ${String(index + 1)}`,
  1280. ).join("\n");
  1281. terminal.input?.(`\x1b[200~${longPaste}\x1b[201~`);
  1282. expect(app.editor.getText()).toBe("[paste #1 +12 lines]");
  1283. terminal.input?.("\x07");
  1284. await vi.waitFor(() =>
  1285. expect(editDraftInExternalEditor).toHaveBeenCalledOnce(),
  1286. );
  1287. expect(editDraftInExternalEditor).toHaveBeenCalledWith({
  1288. command: "code --wait",
  1289. draft: longPaste,
  1290. cwd: "/workspace",
  1291. });
  1292. await vi.waitFor(() =>
  1293. expect(app.editor.getText()).toBe("edited in the external editor"),
  1294. );
  1295. expect(stopTerminal).toHaveBeenCalledOnce();
  1296. expect(startTerminal).toHaveBeenCalledTimes(2);
  1297. terminal.input?.("!");
  1298. expect(app.editor.getText()).toBe("edited in the external editor!");
  1299. await app.stop();
  1300. },
  1301. );
  1302. it("loads Runtime-owned Git context into the status rail without blocking startup", async () => {
  1303. const runtime = createRuntime();
  1304. vi.mocked(runtime.getWorkspaceGitMetadata).mockResolvedValue({
  1305. isGitRepo: true,
  1306. branch: "feat/status-context",
  1307. detached: false,
  1308. isWorktree: true,
  1309. });
  1310. const app = createTuiApp({
  1311. runtime,
  1312. terminal: new FakeTerminal(),
  1313. version: "0.1.0",
  1314. workspaceDir: "/Users/dev/github/agent-archon",
  1315. homeDir: "/Users/dev",
  1316. });
  1317. await app.ready;
  1318. await vi.waitFor(() => {
  1319. expect(runtime.getWorkspaceGitMetadata).toHaveBeenCalledWith(
  1320. "/Users/dev/github/agent-archon",
  1321. );
  1322. const rendered = app.tui.render(120).join("\n");
  1323. expect(rendered).toContain("~/github/agent-archon");
  1324. expect(rendered).toContain("⎇ feat/status-context · worktree");
  1325. });
  1326. await app.stop();
  1327. });
  1328. it("keeps Pi clear-on-shrink disabled for the inline product by default", async () => {
  1329. const app = createTuiApp({
  1330. runtime: createRuntime(),
  1331. terminal: new FakeTerminal(),
  1332. version: "0.1.0",
  1333. workspaceDir: "/workspace",
  1334. });
  1335. expect(app.tui.getClearOnShrink()).toBe(false);
  1336. await app.ready;
  1337. await app.stop();
  1338. });
  1339. it("drains Pi terminal input before restoring the terminal on shutdown", async () => {
  1340. const terminal = new FakeTerminal();
  1341. const drainInput = vi.spyOn(terminal, "drainInput");
  1342. const stopTerminal = vi.spyOn(terminal, "stop");
  1343. const app = createTuiApp({
  1344. runtime: createRuntime(),
  1345. terminal,
  1346. version: "0.1.0",
  1347. workspaceDir: "/workspace",
  1348. });
  1349. app.start();
  1350. await app.ready;
  1351. await app.stop();
  1352. expect(drainInput).toHaveBeenCalledWith(1000);
  1353. expect(stopTerminal).toHaveBeenCalledOnce();
  1354. expect(drainInput.mock.invocationCallOrder[0]).toBeLessThan(
  1355. stopTerminal.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
  1356. );
  1357. });
  1358. it("shows the Runtime initialization error text when the Session catalog is unavailable", async () => {
  1359. const runtime = createRuntime();
  1360. vi.mocked(runtime.listSessions).mockRejectedValue(
  1361. new Error("Unable to connect to the Runtime on port 1234"),
  1362. );
  1363. const app = createTuiApp({
  1364. runtime,
  1365. terminal: new FakeTerminal(),
  1366. version: "0.1.0",
  1367. workspaceDir: "/workspace",
  1368. });
  1369. await app.ready;
  1370. expect(app.controller.snapshot()).toMatchObject({
  1371. status: "error",
  1372. error:
  1373. "Couldn't load sessions: Unable to connect to the Runtime on port 1234. Retry.",
  1374. sessions: [],
  1375. });
  1376. expect(app.tui.render(80).join("\n")).toContain(
  1377. "Error · Couldn't load sessions:",
  1378. );
  1379. await app.stop();
  1380. });
  1381. it("shows an available update as a dedicated startup notice", async () => {
  1382. const terminal = new FakeTerminal();
  1383. const checkForUpdate = vi.fn(async () => ({ latestVersion: "1.2.4" }));
  1384. const app = createTuiApp({
  1385. runtime: createRuntime(),
  1386. terminal,
  1387. version: "1.2.3",
  1388. workspaceDir: "/workspace",
  1389. checkForUpdate,
  1390. });
  1391. app.start();
  1392. await app.ready;
  1393. await vi.waitFor(() => {
  1394. expect(terminal.writes.join("")).toContain(
  1395. "A new version of MCode is available",
  1396. );
  1397. });
  1398. const rendered = terminal.writes.join("");
  1399. expect(checkForUpdate).toHaveBeenCalledTimes(1);
  1400. expect(rendered).toContain("Run '/update' to install MCode 1.2.4");
  1401. await app.submit("Start working");
  1402. expect(app.getSurface()).toBe("conversation");
  1403. expect(app.tui.render(80).join("\n")).not.toContain(
  1404. "A new version of MCode is available",
  1405. );
  1406. await app.submit("/new");
  1407. expect(app.getSurface()).toBe("welcome");
  1408. expect(app.tui.render(80).join("\n")).toContain(
  1409. "A new version of MCode is available",
  1410. );
  1411. await app.stop();
  1412. });
  1413. it("keeps the Welcome handoff out of the primary hint and submits it on Ctrl+U", async () => {
  1414. const terminal = new FakeTerminal();
  1415. const runtime = createRuntime();
  1416. vi.mocked(runtime.listSkills).mockResolvedValue({
  1417. skills: [
  1418. {
  1419. name: "resume-codex",
  1420. displayName: "Resume Codex",
  1421. description: "Continue a Codex session",
  1422. enabled: true,
  1423. sourceKind: "builtin",
  1424. },
  1425. ],
  1426. hasMore: false,
  1427. });
  1428. const sessionId = "01a02373-25ae-76a1-880c-9253ba939cdc";
  1429. const findRecentCodexSession = vi.fn(async () => ({
  1430. sessionId,
  1431. updatedAtMs: Date.now() - 60_000,
  1432. source: "cli" as const,
  1433. }));
  1434. const app = createTuiApp({
  1435. runtime,
  1436. terminal,
  1437. version: "0.1.0",
  1438. workspaceDir: "/workspace",
  1439. findRecentCodexSession,
  1440. });
  1441. app.start();
  1442. await app.ready;
  1443. await vi.waitFor(() =>
  1444. expect(findRecentCodexSession).toHaveBeenCalledOnce(),
  1445. );
  1446. const welcome = app.tui.render(100).join("\n");
  1447. expect(welcome).toContain("Start");
  1448. expect(welcome).not.toContain("Coming from Codex?");
  1449. terminal.input?.("\x15");
  1450. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
  1451. expect(runtime.sendMessage).toHaveBeenCalledWith(
  1452. expect.objectContaining({
  1453. id: "session-1",
  1454. content: `/resume-codex ${sessionId}`,
  1455. }),
  1456. expect.any(AbortSignal),
  1457. );
  1458. expect(app.tui.render(100).join("\n")).not.toContain("Coming from Codex?");
  1459. await app.stop();
  1460. });
  1461. it("invalidates an in-flight Codex handoff scan after the user starts typing", async () => {
  1462. const terminal = new FakeTerminal();
  1463. const runtime = createRuntime();
  1464. vi.mocked(runtime.listSkills).mockResolvedValue({
  1465. skills: [
  1466. {
  1467. name: "resume-codex",
  1468. displayName: "Resume Codex",
  1469. description: "Continue a Codex session",
  1470. enabled: true,
  1471. sourceKind: "builtin",
  1472. },
  1473. ],
  1474. hasMore: false,
  1475. });
  1476. let resolveRecent:
  1477. | ((session: {
  1478. sessionId: string;
  1479. updatedAtMs: number;
  1480. source: "cli";
  1481. }) => void)
  1482. | undefined;
  1483. const findRecentCodexSession = vi.fn(
  1484. async () =>
  1485. await new Promise<{
  1486. sessionId: string;
  1487. updatedAtMs: number;
  1488. source: "cli";
  1489. }>((resolve) => {
  1490. resolveRecent = resolve;
  1491. }),
  1492. );
  1493. const app = createTuiApp({
  1494. runtime,
  1495. terminal,
  1496. version: "0.1.0",
  1497. workspaceDir: "/workspace",
  1498. findRecentCodexSession,
  1499. });
  1500. app.start();
  1501. terminal.input?.("x");
  1502. await vi.waitFor(() =>
  1503. expect(findRecentCodexSession).toHaveBeenCalledOnce(),
  1504. );
  1505. resolveRecent?.({
  1506. sessionId: "01a02373-25ae-76a1-880c-9253ba939cdc",
  1507. updatedAtMs: Date.now(),
  1508. source: "cli",
  1509. });
  1510. await Promise.resolve();
  1511. await Promise.resolve();
  1512. expect(app.editor.getText()).toBe("x");
  1513. expect(app.tui.render(100).join("\n")).not.toContain("Coming from Codex?");
  1514. await app.stop();
  1515. });
  1516. it("does not inspect Codex storage when the resume Skill is unavailable", async () => {
  1517. const runtime = createRuntime();
  1518. const findRecentCodexSession = vi.fn(async () => ({
  1519. sessionId: "01a02373-25ae-76a1-880c-9253ba939cdc",
  1520. updatedAtMs: Date.now(),
  1521. source: "cli" as const,
  1522. }));
  1523. const app = createTuiApp({
  1524. runtime,
  1525. terminal: new FakeTerminal(),
  1526. version: "0.1.0",
  1527. workspaceDir: "/workspace",
  1528. findRecentCodexSession,
  1529. });
  1530. app.start();
  1531. await app.ready;
  1532. await vi.waitFor(() => expect(runtime.listSkills).toHaveBeenCalledOnce());
  1533. await Promise.resolve();
  1534. expect(findRecentCodexSession).not.toHaveBeenCalled();
  1535. expect(app.tui.render(100).join("\n")).not.toContain("Coming from Codex?");
  1536. await app.stop();
  1537. });
  1538. it.each(["unsupported result", "blank version", "rejected check"] as const)(
  1539. "keeps a %s startup update result out of the notice and transcript",
  1540. async (scenario) => {
  1541. const terminal = new FakeTerminal();
  1542. const checkForUpdate = vi.fn(async () => {
  1543. if (scenario === "rejected check")
  1544. throw new Error("registry unavailable");
  1545. if (scenario === "unsupported result") return undefined;
  1546. return { latestVersion: " " };
  1547. });
  1548. const app = createTuiApp({
  1549. runtime: createRuntime(),
  1550. terminal,
  1551. version: "1.2.3",
  1552. workspaceDir: "/workspace",
  1553. checkForUpdate,
  1554. });
  1555. app.start();
  1556. await app.ready;
  1557. await vi.waitFor(() => expect(checkForUpdate).toHaveBeenCalledOnce());
  1558. await app.stop();
  1559. expect(terminal.writes.join("")).not.toContain(
  1560. "A new version of MCode is available",
  1561. );
  1562. expect(
  1563. app.transcript.snapshot().filter((cell) => cell.kind === "error"),
  1564. ).toEqual([]);
  1565. },
  1566. );
  1567. it("routes /update through the in-process update confirmation flow", async () => {
  1568. const plan = {
  1569. kind: "available" as const,
  1570. source: "managed-installer" as const,
  1571. currentVersion: "1.2.3",
  1572. latestVersion: "1.2.4",
  1573. channel: "stable" as const,
  1574. };
  1575. const inspectUpdate = vi.fn(async () => plan);
  1576. const applyUpdate = vi.fn(async () => ({
  1577. applied: true,
  1578. message:
  1579. "MCode 1.2.4 is installed. Restart running MCode sessions to use it.",
  1580. }));
  1581. const app = createTuiApp({
  1582. runtime: createRuntime(),
  1583. terminal: new FakeTerminal(),
  1584. version: "1.2.3",
  1585. workspaceDir: "/workspace",
  1586. inspectUpdate,
  1587. applyUpdate,
  1588. });
  1589. await app.ready;
  1590. await app.submit("/update");
  1591. expect(inspectUpdate).toHaveBeenCalledOnce();
  1592. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  1593. "MCode update",
  1594. );
  1595. app.interaction.current()?.handleInput?.("\r");
  1596. await vi.waitFor(() =>
  1597. expect(applyUpdate).toHaveBeenCalledWith(
  1598. plan,
  1599. expect.objectContaining({
  1600. onOutput: expect.any(Function),
  1601. }),
  1602. ),
  1603. );
  1604. await vi.waitFor(() =>
  1605. expect(
  1606. app.transcript
  1607. .snapshot()
  1608. .some((cell) => cell.content.includes("MCode update completed")),
  1609. ).toBe(true),
  1610. );
  1611. await app.stop();
  1612. });
  1613. it("leaves the current TUI after /update stages an npm-prefix replacement", async () => {
  1614. const plan = {
  1615. kind: "package-manager" as const,
  1616. source: "npm-prefix" as const,
  1617. currentVersion: "1.2.3",
  1618. latestVersion: "1.2.4",
  1619. packageTag: "latest" as const,
  1620. command: {
  1621. executable: "npm",
  1622. args: ["install"],
  1623. display: "npm install",
  1624. },
  1625. };
  1626. const requestRestart = vi.fn();
  1627. const app = createTuiApp({
  1628. runtime: createRuntime(),
  1629. terminal: new FakeTerminal(),
  1630. version: "1.2.3",
  1631. workspaceDir: "/workspace",
  1632. inspectUpdate: async () => plan,
  1633. applyUpdate: async () => ({
  1634. applied: true,
  1635. restartRequired: true,
  1636. message: "MCode 1.2.4 is staged safely.",
  1637. }),
  1638. requestRestart,
  1639. });
  1640. app.start();
  1641. await app.ready;
  1642. await app.submit("/update");
  1643. app.interaction.current()?.handleInput?.("\r");
  1644. await vi.waitFor(() => expect(requestRestart).toHaveBeenCalledOnce());
  1645. await app.stopped;
  1646. });
  1647. it("rechecks local and Runtime work before applying an update", async () => {
  1648. const runtime = createRuntime();
  1649. const applyUpdate = vi.fn(async () => ({
  1650. applied: true,
  1651. message: "updated",
  1652. }));
  1653. const app = createTuiApp({
  1654. runtime,
  1655. terminal: new FakeTerminal(),
  1656. version: "1.2.3",
  1657. workspaceDir: "/workspace",
  1658. inspectUpdate: async () => ({
  1659. kind: "available",
  1660. source: "managed-installer",
  1661. currentVersion: "1.2.3",
  1662. latestVersion: "1.2.4",
  1663. channel: "stable",
  1664. }),
  1665. applyUpdate,
  1666. });
  1667. await app.ready;
  1668. await app.openSession("session-1");
  1669. vi.mocked(runtime.getActiveRun).mockResolvedValue({
  1670. schemaVersion: 1,
  1671. sessionId: "session-1",
  1672. state: "running",
  1673. turnId: "turn-active",
  1674. actions: { steer: true },
  1675. });
  1676. await app.submit("/update");
  1677. app.interaction.current()?.handleInput?.("\r");
  1678. await vi.waitFor(() =>
  1679. expect(
  1680. app.transcript
  1681. .snapshot()
  1682. .some((cell) =>
  1683. cell.content.includes(
  1684. "MCode update failed: Finish or stop the active response before updating.",
  1685. ),
  1686. ),
  1687. ).toBe(true),
  1688. );
  1689. expect(applyUpdate).not.toHaveBeenCalled();
  1690. await app.stop();
  1691. });
  1692. it("fails the update gate closed when Runtime state cannot be verified", async () => {
  1693. const runtime = createRuntime();
  1694. const applyUpdate = vi.fn(async () => ({
  1695. applied: true,
  1696. message: "updated",
  1697. }));
  1698. const app = createTuiApp({
  1699. runtime,
  1700. terminal: new FakeTerminal(),
  1701. version: "1.2.3",
  1702. workspaceDir: "/workspace",
  1703. inspectUpdate: async () => ({
  1704. kind: "available",
  1705. source: "managed-installer",
  1706. currentVersion: "1.2.3",
  1707. latestVersion: "1.2.4",
  1708. channel: "stable",
  1709. }),
  1710. applyUpdate,
  1711. });
  1712. await app.ready;
  1713. await app.openSession("session-1");
  1714. vi.mocked(runtime.getActiveRun).mockRejectedValue(
  1715. new Error("Runtime unavailable"),
  1716. );
  1717. await app.submit("/update");
  1718. app.interaction.current()?.handleInput?.("\r");
  1719. await vi.waitFor(() =>
  1720. expect(
  1721. app.transcript
  1722. .snapshot()
  1723. .some((cell) =>
  1724. cell.content.includes("Unable to verify that this Session is idle"),
  1725. ),
  1726. ).toBe(true),
  1727. );
  1728. expect(applyUpdate).not.toHaveBeenCalled();
  1729. await app.stop();
  1730. });
  1731. it("does not expose the TUI before base hydration has settled", async () => {
  1732. const terminal = new FakeTerminal();
  1733. const runtime = createRuntime();
  1734. let releaseSessions: (() => void) | undefined;
  1735. vi.mocked(runtime.listSessions).mockImplementation(
  1736. async () =>
  1737. await new Promise((resolve) => {
  1738. releaseSessions = () => resolve([]);
  1739. }),
  1740. );
  1741. const app = createTuiApp({
  1742. runtime,
  1743. terminal,
  1744. version: "0.1.0",
  1745. workspaceDir: "/workspace",
  1746. });
  1747. let settled = false;
  1748. void app.ready.then(() => {
  1749. settled = true;
  1750. });
  1751. await Promise.resolve();
  1752. expect(settled).toBe(false);
  1753. releaseSessions?.();
  1754. await app.ready;
  1755. app.start();
  1756. const rendered = app.tui.render(80).join("\n");
  1757. expect(rendered).not.toContain("Starting MiniMax Code");
  1758. expect(rendered).not.toContain("Loading session");
  1759. await app.stop();
  1760. });
  1761. it("renders server startup in the welcome composer header until hydration settles", async () => {
  1762. const runtime = createRuntime();
  1763. let releaseSessions: (() => void) | undefined;
  1764. vi.mocked(runtime.listSessions).mockImplementation(
  1765. async () =>
  1766. await new Promise((resolve) => {
  1767. releaseSessions = () => resolve([]);
  1768. }),
  1769. );
  1770. const app = createTuiApp({
  1771. runtime,
  1772. terminal: new FakeTerminal(),
  1773. version: "0.1.0",
  1774. workspaceDir: "/workspace",
  1775. });
  1776. try {
  1777. app.setStartupStatus("⠋ Starting server...");
  1778. app.start();
  1779. const starting = app.tui.render(80).join("\n");
  1780. expect(starting).toContain("⠋ Starting server...");
  1781. expect(starting).not.toContain("Start · @ file · / autocomplete");
  1782. expect(starting).not.toContain("Loading session");
  1783. releaseSessions?.();
  1784. await app.ready;
  1785. app.setStartupStatus(undefined);
  1786. expect(app.tui.render(80).join("\n")).toContain(
  1787. "Start · @ file · / autocomplete",
  1788. );
  1789. } finally {
  1790. releaseSessions?.();
  1791. await app.stop();
  1792. }
  1793. });
  1794. it("waits for account hydration before allowing the first message", async () => {
  1795. const runtime = createRuntime();
  1796. let resolveAccount!: (
  1797. account: Awaited<ReturnType<typeof runtime.getAccountStatus>>,
  1798. ) => void;
  1799. vi.mocked(runtime.getAccountStatus).mockReturnValue(
  1800. new Promise((resolve) => {
  1801. resolveAccount = resolve;
  1802. }),
  1803. );
  1804. const app = createTuiApp({
  1805. runtime,
  1806. terminal: new FakeTerminal(),
  1807. version: "0.1.0",
  1808. workspaceDir: "/workspace",
  1809. });
  1810. try {
  1811. const readiness = await Promise.race([
  1812. app.ready.then(() => "ready" as const),
  1813. new Promise<"blocked">((resolve) =>
  1814. setTimeout(() => resolve("blocked"), 100),
  1815. ),
  1816. ]);
  1817. expect(readiness).toBe("blocked");
  1818. expect(runtime.createSession).not.toHaveBeenCalled();
  1819. resolveAccount({
  1820. status: "ready",
  1821. defaultModel: "minimax/MiniMax-M2.7",
  1822. managedTokenPresent: true,
  1823. warnings: [],
  1824. });
  1825. await app.ready;
  1826. const submission = app.submit("Send after account hydration");
  1827. await submission;
  1828. expect(runtime.createSession).toHaveBeenCalledWith({
  1829. workspaceDir: "/workspace",
  1830. });
  1831. expect(app.transcript.snapshot()).toEqual(
  1832. expect.arrayContaining([
  1833. expect.objectContaining({
  1834. kind: "user",
  1835. content: "Send after account hydration",
  1836. }),
  1837. expect.objectContaining({
  1838. kind: "assistant",
  1839. content: "Hello from the Agent",
  1840. }),
  1841. ]),
  1842. );
  1843. } finally {
  1844. resolveAccount({
  1845. status: "ready",
  1846. defaultModel: "minimax/MiniMax-M2.7",
  1847. managedTokenPresent: true,
  1848. warnings: [],
  1849. });
  1850. await app.ready;
  1851. await app.stop();
  1852. }
  1853. });
  1854. it("does not wait for Token Plan membership hydration before App readiness", async () => {
  1855. const runtime = createRuntime();
  1856. const baseAccount = {
  1857. status: "ready" as const,
  1858. defaultModel: "minimax/MiniMax-M2.7",
  1859. providerId: "minimax",
  1860. modelId: "MiniMax-M2.7",
  1861. authMode: "managed-login",
  1862. managedTokenPresent: true,
  1863. modelSource: "token-plan" as const,
  1864. warnings: [],
  1865. };
  1866. const hydratedAccount = {
  1867. ...baseAccount,
  1868. tokenPlanQuotaState: "available" as const,
  1869. tokenPlanQuota: {
  1870. fiveHour: { remainingPercent: 90, unlimited: false },
  1871. weekly: { remainingPercent: 80, unlimited: false },
  1872. },
  1873. };
  1874. let resolveMembership!: (account: typeof hydratedAccount) => void;
  1875. vi.mocked(runtime.getAccountStatus).mockImplementation(
  1876. async (_sessionId, options) => {
  1877. if (options?.includeMembership === true) {
  1878. return await new Promise((resolve) => {
  1879. resolveMembership = resolve;
  1880. });
  1881. }
  1882. return baseAccount;
  1883. },
  1884. );
  1885. const app = createTuiApp({
  1886. runtime,
  1887. terminal: new FakeTerminal(),
  1888. version: "0.1.0",
  1889. workspaceDir: "/workspace",
  1890. });
  1891. try {
  1892. await app.ready;
  1893. expect(runtime.getAccountStatus).toHaveBeenCalledWith(undefined, {
  1894. includeMembership: false,
  1895. });
  1896. expect(runtime.getAccountStatus).toHaveBeenCalledWith(undefined, {
  1897. includeMembership: true,
  1898. });
  1899. expect(app.controller.snapshot().account).toMatchObject(baseAccount);
  1900. resolveMembership(hydratedAccount);
  1901. await vi.waitFor(() =>
  1902. expect(app.controller.snapshot().account).toMatchObject({
  1903. tokenPlanQuotaState: "available",
  1904. }),
  1905. );
  1906. } finally {
  1907. resolveMembership(hydratedAccount);
  1908. await app.stop();
  1909. }
  1910. });
  1911. it("waits for permission mode hydration before reporting App readiness", async () => {
  1912. const runtime = createRuntime();
  1913. let resolvePermissionMode!: (mode: "auto") => void;
  1914. vi.mocked(runtime.getPermissionMode).mockReturnValue(
  1915. new Promise((resolve) => {
  1916. resolvePermissionMode = resolve;
  1917. }),
  1918. );
  1919. const app = createTuiApp({
  1920. runtime,
  1921. terminal: new FakeTerminal(),
  1922. version: "0.1.0",
  1923. workspaceDir: "/workspace",
  1924. });
  1925. const readiness = Promise.race([
  1926. app.ready.then(() => "ready" as const),
  1927. new Promise<"blocked">((resolve) =>
  1928. setTimeout(() => resolve("blocked"), 100),
  1929. ),
  1930. ]);
  1931. await expect(readiness).resolves.toBe("blocked");
  1932. resolvePermissionMode("auto");
  1933. await app.ready;
  1934. await app.stop();
  1935. });
  1936. it("accepts modeled account and optional permission degradation at the ready boundary", async () => {
  1937. const runtime = createRuntime();
  1938. vi.mocked(runtime.getAccountStatus).mockRejectedValue(
  1939. new Error("account offline"),
  1940. );
  1941. vi.mocked(runtime.getPermissionMode).mockRejectedValue(
  1942. new Error("config unavailable"),
  1943. );
  1944. const app = createTuiApp({
  1945. runtime,
  1946. terminal: new FakeTerminal(),
  1947. version: "0.1.0",
  1948. workspaceDir: "/workspace",
  1949. });
  1950. await expect(app.ready).resolves.toBeUndefined();
  1951. expect(app.controller.snapshot().account).toEqual({
  1952. status: "unknown",
  1953. warnings: [],
  1954. });
  1955. await app.stop();
  1956. });
  1957. it("hydrates the selected model display name into the status rail on startup", async () => {
  1958. const terminal = new FakeTerminal();
  1959. const runtime = createRuntime();
  1960. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  1961. status: "ready",
  1962. defaultModel: "custom_provider:innerTest/MiniMax-M3",
  1963. providerId: "custom_provider:innerTest",
  1964. modelId: "MiniMax-M3",
  1965. authMode: "byok",
  1966. managedTokenPresent: true,
  1967. warnings: [],
  1968. });
  1969. vi.mocked(runtime.listModels).mockResolvedValue([
  1970. {
  1971. providerId: "custom_provider:innerTest",
  1972. modelId: "MiniMax-M3",
  1973. displayName: "m3.05",
  1974. selected: true,
  1975. },
  1976. ]);
  1977. const app = createTuiApp({
  1978. runtime,
  1979. terminal,
  1980. version: "0.1.0",
  1981. workspaceDir: "/workspace",
  1982. });
  1983. app.start();
  1984. await app.ready;
  1985. await vi.waitFor(() =>
  1986. expect(app.tui.render(120).join("\n")).toContain("✦ m3.05"),
  1987. );
  1988. await app.stop();
  1989. });
  1990. it("restores a managed-login failure to the Composer", async () => {
  1991. const terminal = new FakeTerminal();
  1992. const runtime = createRuntime();
  1993. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  1994. status: "ready",
  1995. defaultModel: "minimax/MiniMax-M2.7",
  1996. authMode: "managed-login",
  1997. modelSource: "token-plan",
  1998. managedTokenPresent: false,
  1999. warnings: [],
  2000. });
  2001. const app = createTuiApp({
  2002. runtime,
  2003. terminal,
  2004. version: "0.1.0",
  2005. workspaceDir: "/workspace",
  2006. });
  2007. app.start();
  2008. await app.ready;
  2009. await vi.waitFor(() =>
  2010. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login"),
  2011. );
  2012. terminal.input?.("Keep this until login");
  2013. terminal.input?.("\r");
  2014. await vi.waitFor(() =>
  2015. expect(app.editor.getText()).toBe("Keep this until login"),
  2016. );
  2017. expect(app.tui.render(80).join("\n")).toContain("Keep this until login");
  2018. expect(app.transcript.snapshot()).toEqual(
  2019. expect.arrayContaining([
  2020. expect.objectContaining({
  2021. kind: "warning",
  2022. content:
  2023. "Sign in to MiniMax to use Agent features. Run /login, then retry.",
  2024. }),
  2025. ]),
  2026. );
  2027. expect(runtime.createSession).not.toHaveBeenCalled();
  2028. expect(runtime.sendMessage).not.toHaveBeenCalled();
  2029. await app.stop();
  2030. });
  2031. it("renders an Enter submission before the asynchronous login preflight settles", async () => {
  2032. const terminal = new FakeTerminal();
  2033. const runtime = createRuntime();
  2034. const app = createTuiApp({
  2035. runtime,
  2036. terminal,
  2037. version: "0.1.0",
  2038. workspaceDir: "/workspace",
  2039. });
  2040. app.start();
  2041. await app.ready;
  2042. let resolveAccount:
  2043. | ((
  2044. account: Awaited<ReturnType<typeof runtime.getAccountStatus>>,
  2045. ) => void)
  2046. | undefined;
  2047. vi.mocked(runtime.getAccountStatus).mockImplementationOnce(
  2048. () =>
  2049. new Promise((resolve) => {
  2050. resolveAccount = resolve;
  2051. }),
  2052. );
  2053. const writesBeforeSubmission = terminal.writes.length;
  2054. terminal.input?.("Show this immediately");
  2055. terminal.input?.("\r");
  2056. expect(app.editor.getText()).toBe("");
  2057. expect(
  2058. app.transcript.snapshot().filter((cell) => cell.kind === "user"),
  2059. ).toEqual([
  2060. expect.objectContaining({
  2061. status: "pending",
  2062. content: "Show this immediately",
  2063. }),
  2064. ]);
  2065. await vi.waitFor(() =>
  2066. expect(terminal.writes.length).toBeGreaterThan(writesBeforeSubmission),
  2067. );
  2068. expect(runtime.createSession).not.toHaveBeenCalled();
  2069. expect(runtime.sendMessage).not.toHaveBeenCalled();
  2070. await vi.waitFor(() => expect(resolveAccount).toBeTypeOf("function"));
  2071. resolveAccount?.({
  2072. status: "ready",
  2073. defaultModel: "minimax/MiniMax-M2.7",
  2074. providerId: "minimax",
  2075. modelId: "MiniMax-M2.7",
  2076. authMode: "managed-login",
  2077. managedTokenPresent: true,
  2078. warnings: [],
  2079. });
  2080. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
  2081. await app.stop();
  2082. });
  2083. it("keeps a login-blocked submission editable after current-region sign-in", async () => {
  2084. const terminal = new FakeTerminal();
  2085. const runtime = createRuntime();
  2086. let authenticated = false;
  2087. vi.mocked(runtime.getAccountStatus).mockImplementation(async () =>
  2088. authenticated
  2089. ? {
  2090. status: "ready",
  2091. defaultModel: "minimax/MiniMax-M2.7",
  2092. providerId: "minimax",
  2093. modelId: "MiniMax-M2.7",
  2094. authMode: "managed-login",
  2095. modelSource: "token-plan",
  2096. managedTokenPresent: true,
  2097. warnings: [],
  2098. }
  2099. : {
  2100. status: "needs-login",
  2101. authMode: "managed-login",
  2102. modelSource: "token-plan",
  2103. managedTokenPresent: false,
  2104. warnings: [],
  2105. },
  2106. );
  2107. const auth = {
  2108. login: vi.fn(async () => {
  2109. authenticated = true;
  2110. return {
  2111. state: "authenticated" as const,
  2112. message: "Signed in with MiniMax.",
  2113. };
  2114. }),
  2115. logout: vi.fn(async () => ({
  2116. state: "signed-out" as const,
  2117. message: "Signed out of MiniMax.",
  2118. })),
  2119. };
  2120. const app = createTuiApp({
  2121. runtime,
  2122. auth,
  2123. terminal,
  2124. version: "0.1.0",
  2125. workspaceDir: "/workspace",
  2126. });
  2127. app.start();
  2128. await app.ready;
  2129. terminal.input?.("Send this after login");
  2130. terminal.input?.("\r");
  2131. await vi.waitFor(() =>
  2132. expect(app.editor.getText()).toBe("Send this after login"),
  2133. );
  2134. await app.submit("/login");
  2135. app.interaction.current()?.handleInput("\r");
  2136. expect(runtime.sendMessage).not.toHaveBeenCalled();
  2137. app.editor.handleInput("\r");
  2138. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
  2139. expect(runtime.sendMessage).toHaveBeenCalledWith(
  2140. expect.objectContaining({
  2141. id: "session-1",
  2142. content: "Send this after login",
  2143. turnId: expect.any(String),
  2144. }),
  2145. expect.any(AbortSignal),
  2146. );
  2147. expect(app.transcript.snapshot()).toEqual(
  2148. expect.arrayContaining([
  2149. expect.objectContaining({
  2150. kind: "user",
  2151. content: "Send this after login",
  2152. }),
  2153. ]),
  2154. );
  2155. await app.stop();
  2156. });
  2157. it("runs /checkin immediately for a signed-in MiniMax account", async () => {
  2158. const runtime = createRuntime();
  2159. const app = createTuiApp({
  2160. runtime,
  2161. terminal: new FakeTerminal(),
  2162. version: "0.1.0",
  2163. workspaceDir: "/workspace",
  2164. });
  2165. app.start();
  2166. await app.ready;
  2167. await app.submit("/checkin");
  2168. expect(runtime.runDailyCheckin).toHaveBeenCalledOnce();
  2169. expect(app.transcript.snapshot()).toEqual(
  2170. expect.arrayContaining([
  2171. expect.objectContaining({
  2172. kind: "final-summary",
  2173. content: expect.stringContaining(
  2174. "Checked in: Cycle day 2, +20 Credits",
  2175. ),
  2176. }),
  2177. ]),
  2178. );
  2179. await app.stop();
  2180. });
  2181. it("shows a generic /checkin failure without backend details", async () => {
  2182. const runtime = createRuntime();
  2183. vi.mocked(runtime.runDailyCheckin).mockRejectedValue(
  2184. new Error("internal signin shard rejected request"),
  2185. );
  2186. const app = createTuiApp({
  2187. runtime,
  2188. terminal: new FakeTerminal(),
  2189. version: "0.1.0",
  2190. workspaceDir: "/workspace",
  2191. });
  2192. app.start();
  2193. await app.ready;
  2194. await app.submit("/checkin");
  2195. const transcript = app.transcript
  2196. .snapshot()
  2197. .map((cell) => cell.content)
  2198. .join("\n");
  2199. expect(transcript).toContain("Couldn't complete daily check-in.");
  2200. expect(transcript).not.toContain("internal signin shard");
  2201. await app.stop();
  2202. });
  2203. it("does not open login when /checkin cannot verify account status", async () => {
  2204. const runtime = createRuntime();
  2205. const auth = {
  2206. login: vi.fn(),
  2207. logout: vi.fn(async () => ({
  2208. state: "signed-out" as const,
  2209. message: "Signed out of MiniMax.",
  2210. })),
  2211. };
  2212. const app = createTuiApp({
  2213. runtime,
  2214. auth,
  2215. terminal: new FakeTerminal(),
  2216. version: "0.1.0",
  2217. workspaceDir: "/workspace",
  2218. });
  2219. app.start();
  2220. await app.ready;
  2221. vi.mocked(runtime.getAccountStatus).mockRejectedValue(
  2222. new Error("status unavailable"),
  2223. );
  2224. await app.submit("/checkin");
  2225. expect(app.interaction.current()).toBeUndefined();
  2226. expect(auth.login).not.toHaveBeenCalled();
  2227. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2228. await app.stop();
  2229. });
  2230. it("starts MiniMax login and resumes /checkin once after authentication", async () => {
  2231. const runtime = createRuntime();
  2232. let authenticated = false;
  2233. vi.mocked(runtime.getAccountStatus).mockImplementation(async () => ({
  2234. status: authenticated ? "ready" : "needs-login",
  2235. authMode: "managed-login",
  2236. modelSource: "byok",
  2237. managedTokenPresent: authenticated,
  2238. warnings: [],
  2239. }));
  2240. const auth = {
  2241. login: vi.fn(async () => {
  2242. authenticated = true;
  2243. return {
  2244. state: "authenticated" as const,
  2245. message: "Signed in with MiniMax.",
  2246. };
  2247. }),
  2248. logout: vi.fn(async () => ({
  2249. state: "signed-out" as const,
  2250. message: "Signed out of MiniMax.",
  2251. })),
  2252. };
  2253. const app = createTuiApp({
  2254. runtime,
  2255. auth,
  2256. terminal: new FakeTerminal(),
  2257. version: "0.1.0",
  2258. workspaceDir: "/workspace",
  2259. });
  2260. app.start();
  2261. await app.ready;
  2262. await app.submit("/checkin");
  2263. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2264. app.interaction.current()?.handleInput("\r");
  2265. await vi.waitFor(() =>
  2266. expect(runtime.runDailyCheckin).toHaveBeenCalledOnce(),
  2267. );
  2268. expect(auth.login).toHaveBeenCalledWith(expect.any(Function), "cn");
  2269. await app.stop();
  2270. });
  2271. it("does not resume /checkin when the login picker is cancelled", async () => {
  2272. const runtime = createRuntime();
  2273. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2274. status: "needs-login",
  2275. authMode: "managed-login",
  2276. modelSource: "byok",
  2277. managedTokenPresent: false,
  2278. warnings: [],
  2279. });
  2280. const auth = {
  2281. login: vi.fn(),
  2282. logout: vi.fn(async () => ({
  2283. state: "signed-out" as const,
  2284. message: "Signed out of MiniMax.",
  2285. })),
  2286. };
  2287. const app = createTuiApp({
  2288. runtime,
  2289. auth,
  2290. terminal: new FakeTerminal(),
  2291. version: "0.1.0",
  2292. workspaceDir: "/workspace",
  2293. });
  2294. app.start();
  2295. await app.ready;
  2296. await app.submit("/checkin");
  2297. app.interaction.current()?.handleInput("\u001b");
  2298. expect(auth.login).not.toHaveBeenCalled();
  2299. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2300. await app.stop();
  2301. });
  2302. it("does not resume /checkin when browser login fails", async () => {
  2303. const runtime = createRuntime();
  2304. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2305. status: "needs-login",
  2306. managedTokenPresent: false,
  2307. warnings: [],
  2308. });
  2309. const auth = {
  2310. login: vi.fn(async () => {
  2311. throw new Error("browser login failed");
  2312. }),
  2313. logout: vi.fn(async () => ({
  2314. state: "signed-out" as const,
  2315. message: "Signed out of MiniMax.",
  2316. })),
  2317. };
  2318. const app = createTuiApp({
  2319. runtime,
  2320. auth,
  2321. terminal: new FakeTerminal(),
  2322. version: "0.1.0",
  2323. workspaceDir: "/workspace",
  2324. });
  2325. app.start();
  2326. await app.ready;
  2327. await app.submit("/checkin");
  2328. app.interaction.current()?.handleInput("\r");
  2329. await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
  2330. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2331. await app.stop();
  2332. });
  2333. it("carries /checkin through a cross-region login restart", async () => {
  2334. const runtime = createRuntime();
  2335. const requestRestart = vi.fn();
  2336. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2337. status: "needs-login",
  2338. managedTokenPresent: false,
  2339. warnings: [],
  2340. });
  2341. const auth = {
  2342. login: vi.fn(async () => ({
  2343. state: "authenticated" as const,
  2344. restartRequired: true,
  2345. message: "Signed in with MiniMax Global.",
  2346. })),
  2347. logout: vi.fn(async () => ({
  2348. state: "signed-out" as const,
  2349. message: "Signed out of MiniMax.",
  2350. })),
  2351. };
  2352. const app = createTuiApp({
  2353. runtime,
  2354. auth,
  2355. terminal: new FakeTerminal(),
  2356. version: "0.1.0",
  2357. workspaceDir: "/workspace",
  2358. requestRestart,
  2359. });
  2360. app.start();
  2361. await app.ready;
  2362. await app.submit("/checkin");
  2363. app.interaction.current()?.handleInput("\u001b[B");
  2364. app.interaction.current()?.handleInput("\r");
  2365. await vi.waitFor(() =>
  2366. expect(requestRestart).toHaveBeenCalledWith("en", "/checkin"),
  2367. );
  2368. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2369. await app.stopped;
  2370. });
  2371. it("restarts after cross-region login while keeping the blocked submission", async () => {
  2372. const terminal = new FakeTerminal();
  2373. const runtime = createRuntime();
  2374. const requestRestart = vi.fn();
  2375. const notifyAuthContextChanged = vi.fn(async () => undefined);
  2376. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2377. status: "needs-login",
  2378. authMode: "managed-login",
  2379. modelSource: "token-plan",
  2380. managedTokenPresent: false,
  2381. warnings: [],
  2382. });
  2383. const auth = {
  2384. login: vi.fn(async () => ({
  2385. state: "authenticated" as const,
  2386. restartRequired: true,
  2387. message: "Signed in with MiniMax Global.",
  2388. })),
  2389. logout: vi.fn(async () => ({
  2390. state: "signed-out" as const,
  2391. message: "Signed out of MiniMax.",
  2392. })),
  2393. };
  2394. const app = createTuiApp({
  2395. runtime,
  2396. auth,
  2397. terminal,
  2398. version: "0.1.0",
  2399. workspaceDir: "/workspace",
  2400. requestRestart,
  2401. notifyAuthContextChanged,
  2402. });
  2403. app.start();
  2404. await app.ready;
  2405. terminal.input?.("Keep this through restart");
  2406. terminal.input?.("\r");
  2407. await vi.waitFor(() =>
  2408. expect(app.editor.getText()).toBe("Keep this through restart"),
  2409. );
  2410. await app.submit("/login");
  2411. app.interaction.current()?.handleInput("\u001b[B");
  2412. app.interaction.current()?.handleInput("\r");
  2413. await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
  2414. expect(auth.login).toHaveBeenCalledWith(expect.any(Function), "en");
  2415. expect(runtime.sendMessage).not.toHaveBeenCalled();
  2416. await vi.waitFor(() => expect(requestRestart).toHaveBeenCalledOnce());
  2417. expect(requestRestart).toHaveBeenCalledWith("en");
  2418. expect(notifyAuthContextChanged).not.toHaveBeenCalled();
  2419. await app.stopped;
  2420. expect(app.editor.getText()).toBe("Keep this through restart");
  2421. });
  2422. it("offers MiniMax login without blocking an unauthenticated builtin BYOK Turn", async () => {
  2423. const runtime = createRuntime();
  2424. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2425. status: "ready",
  2426. defaultModel: "minimax/MiniMax-M3",
  2427. providerId: "minimax",
  2428. authMode: "managed-login",
  2429. modelSource: "byok",
  2430. managedTokenPresent: false,
  2431. warnings: [],
  2432. });
  2433. const app = createTuiApp({
  2434. runtime,
  2435. terminal: new FakeTerminal(),
  2436. version: "0.1.0",
  2437. workspaceDir: "/workspace",
  2438. });
  2439. app.start();
  2440. await app.ready;
  2441. await vi.waitFor(() =>
  2442. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login"),
  2443. );
  2444. await app.submit("BYOK still runs");
  2445. expect(runtime.createSession).toHaveBeenCalledWith({
  2446. workspaceDir: "/workspace",
  2447. });
  2448. expect(app.transcript.snapshot()).toEqual(
  2449. expect.arrayContaining([
  2450. expect.objectContaining({ kind: "user", content: "BYOK still runs" }),
  2451. expect.objectContaining({
  2452. kind: "assistant",
  2453. content: "Hello from the Agent",
  2454. }),
  2455. ]),
  2456. );
  2457. await app.stop();
  2458. });
  2459. it("starts a terminal-native workbench and submits messages through the Agent runtime", async () => {
  2460. const terminal = new FakeTerminal();
  2461. const runtime = createRuntime();
  2462. const app = createTuiApp({
  2463. runtime,
  2464. terminal,
  2465. version: "0.1.0",
  2466. workspaceDir: "/workspace",
  2467. homeDir: "/home/dev",
  2468. });
  2469. app.start();
  2470. await app.ready;
  2471. expect(app.getSurface()).toBe("welcome");
  2472. await app.submit("Say hello");
  2473. expect(app.getSurface()).toBe("conversation");
  2474. const conversation = app.tui.render(80).join("\n");
  2475. expect(conversation).toContain("Tips for getting started");
  2476. expect(conversation).toContain("Say hello");
  2477. expect(conversation).toContain("Hello from the Agent");
  2478. expect(terminal.started).toBe(true);
  2479. expect(terminal.title).toBe("Minimax Code");
  2480. expect(runtime.createSession).toHaveBeenCalledWith({
  2481. workspaceDir: "/workspace",
  2482. });
  2483. expect(app.transcript.snapshot()).toEqual([
  2484. expect.objectContaining({ kind: "user", content: "Say hello" }),
  2485. expect.objectContaining({
  2486. kind: "assistant",
  2487. status: "succeeded",
  2488. content: "Hello from the Agent",
  2489. }),
  2490. expect.objectContaining({ kind: "turn-duration", status: "succeeded" }),
  2491. ]);
  2492. await app.stop();
  2493. expect(terminal.stopped).toBe(true);
  2494. });
  2495. it("syncs the generated Session title to the terminal without duplicate writes", async () => {
  2496. const terminal = new FakeTerminal();
  2497. const runtime = createRuntime();
  2498. let sessionTitle = "New session";
  2499. let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  2500. vi.mocked(runtime.listSessions).mockImplementation(async () => [
  2501. {
  2502. sessionId: "session-1",
  2503. title: sessionTitle,
  2504. workspaceDir: "/workspace",
  2505. },
  2506. ]);
  2507. vi.mocked(runtime.watchEvents).mockImplementation(
  2508. async function* watchEvents(signal) {
  2509. const event = await new Promise<TuiRuntimeEvent | undefined>(
  2510. (resolve) => {
  2511. emitEvent = resolve;
  2512. signal.addEventListener("abort", () => resolve(undefined), {
  2513. once: true,
  2514. });
  2515. },
  2516. );
  2517. if (event) yield event;
  2518. await new Promise<void>((resolve) => {
  2519. signal.addEventListener("abort", resolve, { once: true });
  2520. });
  2521. },
  2522. );
  2523. const app = createTuiApp({
  2524. runtime,
  2525. terminal,
  2526. version: "0.1.0",
  2527. workspaceDir: "/workspace",
  2528. });
  2529. app.start();
  2530. await app.ready;
  2531. await app.submit("Review uncommitted work");
  2532. await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
  2533. sessionTitle = "Review uncommitted work";
  2534. emitEvent?.(
  2535. runtimeEvent({
  2536. type: "session.title_updated",
  2537. timestamp: Date.now(),
  2538. source: "runtime",
  2539. payload: {
  2540. sessionId: "session-1",
  2541. title: sessionTitle,
  2542. },
  2543. }),
  2544. );
  2545. await vi.waitFor(() => expect(terminal.title).toBe(sessionTitle));
  2546. await app.submit("/status");
  2547. expect(terminal.titleUpdates).toEqual(["Minimax Code", sessionTitle]);
  2548. await app.stop();
  2549. });
  2550. it("keeps chat state alive while a regular feature overlay owns the viewport", async () => {
  2551. const terminal = new FakeTerminal();
  2552. terminal.rows = 6;
  2553. const runtime = createRuntime();
  2554. const app = createTuiApp({
  2555. runtime,
  2556. terminal,
  2557. version: "0.1.0",
  2558. workspaceDir: "/workspace",
  2559. });
  2560. const featureInput = vi.fn();
  2561. const featureContent = {
  2562. render: () => ["feature-header", "feature-body"],
  2563. invalidate: () => undefined,
  2564. };
  2565. const feature = {
  2566. id: "sessions",
  2567. layoutRoot: new VStack([{ component: featureContent }]),
  2568. render: featureContent.render,
  2569. invalidate: () => undefined,
  2570. handleInput: featureInput,
  2571. };
  2572. app.start();
  2573. await app.ready;
  2574. const screen = new VirtualTerminalScreen(terminal.columns, terminal.rows);
  2575. let writeIndex = 0;
  2576. const flushWrites = (): void => {
  2577. for (; writeIndex < terminal.writes.length; writeIndex += 1) {
  2578. screen.feed(terminal.writes[writeIndex] ?? "");
  2579. }
  2580. };
  2581. flushWrites();
  2582. app.editor.setText("preserved draft");
  2583. const handle = app.surfaceHost.pushFeature({ screen: feature });
  2584. app.tui.renderNow();
  2585. flushWrites();
  2586. expect(app.surfaceHost.getActiveSurface()).toEqual({
  2587. kind: "feature",
  2588. id: "sessions",
  2589. });
  2590. expect(app.surfaceHost.render(80).join("\n")).toContain("preserved draft");
  2591. expect(screen.viewportText()).toContain("feature-header");
  2592. expect(screen.viewportText()).toContain("feature-body");
  2593. expect(app.tui.mode).toBe("regular");
  2594. expect(terminal.startCount).toBe(1);
  2595. expect(terminal.stopCount).toBe(0);
  2596. terminal.input?.("j");
  2597. expect(featureInput).toHaveBeenCalledWith("j");
  2598. expect(handle.close()).toBe(true);
  2599. app.tui.renderNow();
  2600. flushWrites();
  2601. expect(app.surfaceHost.getActiveSurface()).toEqual({
  2602. kind: "chat",
  2603. id: "chat",
  2604. });
  2605. expect(app.editor.getText()).toBe("preserved draft");
  2606. expect(app.surfaceHost.render(80).join("\n")).toContain("preserved draft");
  2607. expect(screen.viewportText()).toContain("preserved draft");
  2608. expect(screen.viewportText()).not.toContain("feature-header");
  2609. await app.stop();
  2610. screen.dispose();
  2611. });
  2612. it("switches /settings through explicit choices and closes after applying", async () => {
  2613. const terminal = new FakeTerminal();
  2614. const persistTuiMode = vi.fn();
  2615. const app = createTuiApp({
  2616. runtime: createRuntime(),
  2617. terminal,
  2618. version: "0.2.0",
  2619. workspaceDir: "/workspace",
  2620. tuiMode: "regular",
  2621. persistTuiMode,
  2622. });
  2623. app.start();
  2624. await app.ready;
  2625. expect(app.surfaceHost.getChatMode()).toBe("regular");
  2626. expect(app.tui.mode).toBe("regular");
  2627. await app.submit("/settings");
  2628. const fullscreenSettings = app.interaction.current();
  2629. expect(app.tui.getFocusedComponent()).toBe(fullscreenSettings);
  2630. expect(app.surfaceHost.render(80).join("\n")).toContain(
  2631. "TUI mode · Regular",
  2632. );
  2633. terminal.input?.("\u001b[B");
  2634. terminal.input?.("\r");
  2635. expect(app.surfaceHost.getChatMode()).toBe("fullscreen");
  2636. expect(app.tui.mode).toBe("fullscreen");
  2637. expect(app.interaction.isActive()).toBe(false);
  2638. expect(app.tui.getFocusedComponent()).toBe(app.editor);
  2639. expect(persistTuiMode).toHaveBeenLastCalledWith("fullscreen");
  2640. expect(app.editor.focused).toBe(true);
  2641. terminal.input?.("/");
  2642. await vi.waitFor(() =>
  2643. expect(app.editor.render(60).join("\n")).toContain(
  2644. "Show available commands",
  2645. ),
  2646. );
  2647. terminal.input?.("\u001b");
  2648. app.editor.setText("");
  2649. await app.submit("/settings");
  2650. const regularSettings = app.interaction.current();
  2651. expect(app.tui.getFocusedComponent()).toBe(regularSettings);
  2652. expect(app.surfaceHost.render(80).join("\n")).toContain(
  2653. "TUI mode · Fullscreen",
  2654. );
  2655. terminal.input?.("\u001b[A");
  2656. terminal.input?.("\r");
  2657. expect(app.surfaceHost.getChatMode()).toBe("regular");
  2658. expect(app.tui.mode).toBe("regular");
  2659. expect(app.interaction.isActive()).toBe(false);
  2660. expect(app.tui.getFocusedComponent()).toBe(app.editor);
  2661. expect(persistTuiMode).toHaveBeenLastCalledWith("regular");
  2662. await app.stop();
  2663. });
  2664. it("keeps the Pi Editor and Slash Command autocomplete active in fullscreen chat", async () => {
  2665. const terminal = new FakeTerminal();
  2666. terminal.rows = 8;
  2667. const app = createTuiApp({
  2668. runtime: createRuntime(),
  2669. terminal,
  2670. version: "0.2.0",
  2671. workspaceDir: "/workspace",
  2672. tuiMode: "fullscreen",
  2673. });
  2674. app.start();
  2675. await app.ready;
  2676. terminal.input?.("/");
  2677. await vi.waitFor(() =>
  2678. expect(app.editor.render(60).join("\n")).toContain(
  2679. "Show available commands",
  2680. ),
  2681. );
  2682. expect(app.editor.getText()).toBe("/");
  2683. terminal.input?.("\u001B[B");
  2684. expect(app.editor.getText()).toBe("/");
  2685. terminal.input?.("\u001B");
  2686. expect(app.editor.getText()).toBe("/");
  2687. expect(app.editor.focused).toBe(true);
  2688. await app.stop();
  2689. });
  2690. it("renders regular-mode Slash Command autocomplete on the first keypress and every update", async () => {
  2691. const terminal = new FakeTerminal();
  2692. const app = createTuiApp({
  2693. runtime: createRuntime(),
  2694. terminal,
  2695. version: "0.2.0",
  2696. workspaceDir: "/workspace",
  2697. tuiMode: "regular",
  2698. });
  2699. app.start();
  2700. await app.ready;
  2701. const screen = new VirtualTerminalScreen(terminal.columns, terminal.rows);
  2702. let writeIndex = 0;
  2703. const flushWrites = (): void => {
  2704. for (; writeIndex < terminal.writes.length; writeIndex += 1) {
  2705. screen.feed(terminal.writes[writeIndex] ?? "");
  2706. }
  2707. };
  2708. flushWrites();
  2709. terminal.input?.("/");
  2710. await vi.waitFor(() => {
  2711. flushWrites();
  2712. expect(screen.viewportText()).toContain("Show available commands");
  2713. });
  2714. expect(screen.viewportText()).toContain("/");
  2715. terminal.input?.("m");
  2716. await vi.waitFor(() => {
  2717. flushWrites();
  2718. expect(screen.viewportText()).toContain("Choose a model");
  2719. });
  2720. expect(screen.viewportText()).toContain("/m");
  2721. screen.dispose();
  2722. await app.stop();
  2723. });
  2724. it("resumes fullscreen tail following when submitting from scrolled history", async () => {
  2725. const terminal = new FakeTerminal();
  2726. terminal.rows = 6;
  2727. const app = createTuiApp({
  2728. runtime: createRuntime(),
  2729. terminal,
  2730. version: "0.2.0",
  2731. workspaceDir: "/workspace",
  2732. tuiMode: "fullscreen",
  2733. });
  2734. app.start();
  2735. await app.ready;
  2736. for (let index = 1; index <= 4; index += 1) {
  2737. await app.submit(`Prompt ${String(index)}`);
  2738. }
  2739. app.tui.renderNow();
  2740. terminal.input?.("\u001B[5~");
  2741. expect((app.tui as TuiAltScreen).isFollowingOutput).toBe(false);
  2742. await app.submit("Latest prompt");
  2743. expect((app.tui as TuiAltScreen).isFollowingOutput).toBe(true);
  2744. await app.stop();
  2745. });
  2746. it("stops the terminal without waiting for a stalled Desktop event stream", async () => {
  2747. const terminal = new FakeTerminal();
  2748. const runtime = createRuntime();
  2749. vi.mocked(runtime.watchEvents).mockImplementation(
  2750. async function* watchEvents() {
  2751. await new Promise<void>(() => undefined);
  2752. yield runtimeEvent({
  2753. type: "unreachable",
  2754. timestamp: 0,
  2755. source: "test",
  2756. payload: {},
  2757. });
  2758. },
  2759. );
  2760. const app = createTuiApp({
  2761. runtime,
  2762. terminal,
  2763. version: "0.1.0",
  2764. workspaceDir: "/workspace",
  2765. });
  2766. app.start();
  2767. await app.ready;
  2768. const stopping = app.stop();
  2769. await vi.waitFor(() => expect(terminal.stopped).toBe(true));
  2770. await stopping;
  2771. });
  2772. it("restores the terminal before a stalled remote turn abort finishes", async () => {
  2773. const terminal = new FakeTerminal();
  2774. const runtime = createRuntime();
  2775. let finishRemoteAbort: ((value: boolean) => void) | undefined;
  2776. vi.mocked(runtime.sendMessage).mockImplementation(
  2777. async function* sendMessage(_req: SendMessageReq, signal?: AbortSignal) {
  2778. await new Promise<void>((resolve) => {
  2779. signal?.addEventListener("abort", () => resolve(), { once: true });
  2780. });
  2781. yield { type: "done" };
  2782. },
  2783. );
  2784. vi.mocked(runtime.abortSession).mockImplementation(
  2785. async () =>
  2786. await new Promise<boolean>((resolve) => {
  2787. finishRemoteAbort = resolve;
  2788. }),
  2789. );
  2790. const app = createTuiApp({
  2791. runtime,
  2792. terminal,
  2793. version: "0.1.0",
  2794. workspaceDir: "/workspace",
  2795. });
  2796. app.start();
  2797. await app.ready;
  2798. const submitting = app.submit("Keep running");
  2799. await vi.waitFor(() =>
  2800. expect(app.controller.snapshot().status).toBe("running"),
  2801. );
  2802. const stopping = app.stop();
  2803. await vi.waitFor(() => expect(terminal.stopped).toBe(true));
  2804. finishRemoteAbort?.(true);
  2805. await Promise.all([submitting, stopping]);
  2806. });
  2807. it("stops the active turn before leaving the UI", async () => {
  2808. const terminal = new FakeTerminal();
  2809. const runtime = createRuntime();
  2810. let finishTurn: (() => void) | undefined;
  2811. vi.mocked(runtime.sendMessage).mockImplementation(
  2812. async function* sendMessage() {
  2813. yield {
  2814. type: "delta",
  2815. turnId: "turn-detached",
  2816. role: "assistant",
  2817. content: "Still running",
  2818. };
  2819. await new Promise<void>((resolve) => {
  2820. finishTurn = resolve;
  2821. });
  2822. yield { type: "done", turnId: "turn-detached" };
  2823. },
  2824. );
  2825. const app = createTuiApp({
  2826. runtime,
  2827. terminal,
  2828. version: "0.1.0",
  2829. workspaceDir: "/workspace",
  2830. });
  2831. app.start();
  2832. await app.ready;
  2833. const submitting = app.submit("Keep running after the UI leaves");
  2834. await vi.waitFor(() =>
  2835. expect(app.controller.snapshot().status).toBe("running"),
  2836. );
  2837. await app.leaveUi();
  2838. expect(terminal.stopped).toBe(true);
  2839. expect(runtime.abortSession).toHaveBeenCalledWith(
  2840. expect.objectContaining({ id: "session-1" }),
  2841. );
  2842. finishTurn?.();
  2843. await submitting;
  2844. });
  2845. it("resumes a launcher-selected Session and exposes its ID for the exit hint", async () => {
  2846. const terminal = new FakeTerminal();
  2847. const runtime = createRuntime();
  2848. const app = createTuiApp({
  2849. runtime,
  2850. terminal,
  2851. version: "0.1.0",
  2852. workspaceDir: "/workspace",
  2853. });
  2854. app.start();
  2855. await app.ready;
  2856. expect(app.controller.snapshot().session?.sessionId).toBeUndefined();
  2857. await app.openSession("session-existing");
  2858. expect(runtime.getSession).toHaveBeenCalledWith("session-existing");
  2859. expect(runtime.getMessages).toHaveBeenCalledWith("session-existing");
  2860. expect(app.controller.snapshot().session?.sessionId).toBe(
  2861. "session-existing",
  2862. );
  2863. await app.leaveUi();
  2864. });
  2865. it("reports a launcher continue hydration failure in the Transcript", async () => {
  2866. const terminal = new FakeTerminal();
  2867. const runtime = createRuntime();
  2868. vi.mocked(runtime.listSessions).mockResolvedValue([
  2869. {
  2870. sessionId: "session-existing",
  2871. title: "Existing session",
  2872. workspaceDir: "/workspace",
  2873. },
  2874. ]);
  2875. vi.mocked(runtime.getSession).mockRejectedValue(
  2876. new Error("Session hydration failed"),
  2877. );
  2878. const app = createTuiApp({
  2879. runtime,
  2880. terminal,
  2881. version: "0.1.0",
  2882. workspaceDir: "/workspace",
  2883. });
  2884. await app.ready;
  2885. await expect(app.continueLatestSession()).rejects.toThrow(
  2886. "Session hydration failed",
  2887. );
  2888. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  2889. kind: "error",
  2890. content:
  2891. "Couldn't continue the latest conversation: Session hydration failed. Retry after the connection recovers.",
  2892. });
  2893. await app.leaveUi();
  2894. });
  2895. it("can disable queue UI and preserve the next draft while a turn is running", async () => {
  2896. const terminal = new FakeTerminal();
  2897. const runtime = createRuntime();
  2898. let finishTool: (() => void) | undefined;
  2899. vi.mocked(runtime.sendMessage).mockImplementation(
  2900. async function* sendMessage() {
  2901. yield {
  2902. type: "delta",
  2903. turnId: "turn-running-tool",
  2904. toolCalls: [
  2905. {
  2906. id: "read-1",
  2907. name: "read",
  2908. status: "running",
  2909. input: { path: "src/cart/price.ts" },
  2910. },
  2911. ],
  2912. };
  2913. await new Promise<void>((resolve) => {
  2914. finishTool = resolve;
  2915. });
  2916. yield { type: "done", turnId: "turn-running-tool" };
  2917. },
  2918. );
  2919. const app = createTuiApp({
  2920. runtime,
  2921. terminal,
  2922. version: "0.1.0",
  2923. workspaceDir: "/workspace",
  2924. productFeatures: { queue: false },
  2925. });
  2926. await app.ready;
  2927. const submission = app.submit("Inspect the pricing logic");
  2928. await vi.waitFor(() => {
  2929. const rendered = app.tui.render(80).join("\n");
  2930. expect(rendered).toContain("Reading (src/cart/price.ts)");
  2931. expect(rendered).toContain("Running");
  2932. expect(rendered).not.toContain("Running · 0s");
  2933. expect(rendered).not.toContain("Running · Read");
  2934. expect(rendered).not.toContain("MCode · Running");
  2935. expect(rendered).toContain("Ctrl+O details");
  2936. expect(rendered).toContain("Esc stop");
  2937. expect(rendered).not.toContain("Enter run next");
  2938. expect(rendered).not.toContain("Message · Enter send");
  2939. expect(rendered).not.toContain("Follow-up");
  2940. expect(rendered).not.toContain("waiting");
  2941. });
  2942. await app.submit("Review the tests next");
  2943. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  2944. expect(app.editor.getText()).toBe("Review the tests next");
  2945. expect(app.tui.render(80).join("\n")).toContain("Esc to interrupt");
  2946. finishTool?.();
  2947. await submission;
  2948. });
  2949. it("refreshes the running queue hint from the same bindings as the hotkeys panel", async () => {
  2950. const keybindings = createTuiHostKeybindings({
  2951. platform: "linux",
  2952. suspendSupported: true,
  2953. });
  2954. const runtime = createRuntime();
  2955. let finishTurn: (() => void) | undefined;
  2956. vi.mocked(runtime.sendMessage).mockImplementation(
  2957. async function* sendMessage() {
  2958. yield {
  2959. type: "delta",
  2960. turnId: "turn-custom-queue",
  2961. thinking: "Inspecting the repository",
  2962. };
  2963. await new Promise<void>((resolve) => {
  2964. finishTurn = resolve;
  2965. });
  2966. yield { type: "done", turnId: "turn-custom-queue" };
  2967. },
  2968. );
  2969. const app = createTuiApp({
  2970. runtime,
  2971. terminal: new FakeTerminal(),
  2972. version: "0.1.0",
  2973. workspaceDir: "/workspace",
  2974. keybindings: keybindings.registry,
  2975. });
  2976. await app.ready;
  2977. keybindings.manager.setUserBindings({ "run.queue-draft": "ctrl+enter" });
  2978. const submission = app.submit("Inspect the repository");
  2979. try {
  2980. await vi.waitFor(() => {
  2981. const rendered = stripAnsi(app.tui.render(100).join("\n"));
  2982. expect(rendered).toContain("Running");
  2983. expect(rendered).toContain("Ctrl+Enter queue");
  2984. expect(rendered).not.toContain("Alt+Enter queue");
  2985. expect(
  2986. keybindings.registry
  2987. .helpRows()
  2988. .find((row) => row.ids.includes("run.queue-draft"))?.keys,
  2989. ).toBe("Ctrl+Enter");
  2990. });
  2991. } finally {
  2992. finishTurn?.();
  2993. await submission;
  2994. await app.stop();
  2995. }
  2996. });
  2997. it("shows running Thinking in chat and opens the full Transcript with /transcript", async () => {
  2998. const terminal = new FakeTerminal();
  2999. const runtime = createRuntime();
  3000. let finishThinking: (() => void) | undefined;
  3001. vi.mocked(runtime.sendMessage).mockImplementation(
  3002. async function* sendMessage() {
  3003. yield {
  3004. type: "delta",
  3005. turnId: "turn-running-thinking",
  3006. thinking: "Inspecting the repository",
  3007. };
  3008. await new Promise<void>((resolve) => {
  3009. finishThinking = resolve;
  3010. });
  3011. yield { type: "done", turnId: "turn-running-thinking" };
  3012. },
  3013. );
  3014. const app = createTuiApp({
  3015. runtime,
  3016. terminal,
  3017. version: "0.1.0",
  3018. workspaceDir: "/workspace",
  3019. });
  3020. app.start();
  3021. await app.ready;
  3022. const submission = app.submit("Inspect the repository");
  3023. const countThinkingBodyRows = (rendered: string): number =>
  3024. rendered
  3025. .split("\n")
  3026. .filter(
  3027. (line) =>
  3028. line.includes("Inspecting the repository") &&
  3029. !line.includes("MCode"),
  3030. ).length;
  3031. let expandedThinkingRows = 0;
  3032. try {
  3033. await vi.waitFor(() => {
  3034. const thinking = app.transcript
  3035. .snapshot()
  3036. .find((cell) => cell.kind === "thinking");
  3037. expect(thinking?.content).toBe("Inspecting the repository");
  3038. expect(thinking?.expanded).toBeUndefined();
  3039. const rendered = app.tui.render(80).join("\n");
  3040. expect(rendered).toContain("Running");
  3041. expect(rendered).not.toContain("Running · 0s");
  3042. expect(rendered).toContain(`${formatTuiShortcut("alt+enter")} queue`);
  3043. expect(rendered).toContain("Enter steer");
  3044. expect(rendered).not.toContain(`${formatTuiShortcut("ctrl+x")} steer`);
  3045. expect(rendered).toContain("Ctrl+O details");
  3046. expect(rendered).toContain("Esc stop");
  3047. expect(rendered).toContain("Thinking…");
  3048. expect(rendered).not.toContain("MCode ·");
  3049. expect(rendered).not.toContain("Thinking · Inspecting the repository");
  3050. expandedThinkingRows = countThinkingBodyRows(rendered);
  3051. expect(expandedThinkingRows).toBeGreaterThan(0);
  3052. });
  3053. await app.submit("/transcript");
  3054. await vi.waitFor(() => {
  3055. const rendered = renderTerminalViewport(app, terminal);
  3056. expect(app.surfaceHost.getActiveSurface()).toEqual({
  3057. kind: "feature",
  3058. id: "transcript",
  3059. });
  3060. expect(rendered).toContain("Transcript");
  3061. expect(rendered).not.toContain("Inspecting the repository");
  3062. expect(countThinkingBodyRows(rendered)).toBeLessThan(
  3063. expandedThinkingRows,
  3064. );
  3065. });
  3066. terminal.input?.("\x14");
  3067. expect(app.surfaceHost.getActiveSurface()).toEqual({
  3068. kind: "feature",
  3069. id: "transcript",
  3070. });
  3071. finishThinking?.();
  3072. finishThinking = undefined;
  3073. await submission;
  3074. expect(app.surfaceHost.getActiveSurface()).toEqual({
  3075. kind: "feature",
  3076. id: "transcript",
  3077. });
  3078. expect(app.controller.snapshot().activeTurnId).toBeUndefined();
  3079. expect(
  3080. app.transcript.snapshot().find((cell) => cell.kind === "thinking"),
  3081. ).toMatchObject({
  3082. status: "succeeded",
  3083. });
  3084. terminal.input?.("\u001B");
  3085. await vi.waitFor(() => {
  3086. const rendered = app.tui.render(80).join("\n");
  3087. expect(app.surfaceHost.getActiveSurface()).toEqual({
  3088. kind: "chat",
  3089. id: "chat",
  3090. });
  3091. expect(rendered).toContain("Message · Enter send");
  3092. expect(rendered).not.toContain("Running");
  3093. });
  3094. } finally {
  3095. finishThinking?.();
  3096. await submission;
  3097. await app.stop();
  3098. }
  3099. });
  3100. it("toggles hidden and full inline Tool output with Ctrl+O", async () => {
  3101. const terminal = new FakeTerminal();
  3102. const app = createTuiApp({
  3103. runtime: createRuntime(),
  3104. terminal,
  3105. version: "0.1.0",
  3106. workspaceDir: "/workspace",
  3107. });
  3108. app.start();
  3109. await app.ready;
  3110. app.transcript.upsert({
  3111. id: "tool-detail-toggle",
  3112. kind: "tool",
  3113. status: "succeeded",
  3114. title: "bash",
  3115. content: '{"command":"pnpm test"}',
  3116. detail: [
  3117. "result line 1",
  3118. "result line 2",
  3119. "result line 3",
  3120. "result line 4",
  3121. ].join("\n"),
  3122. createdAtMs: 1,
  3123. });
  3124. expect(app.tui.render(80).join("\n")).not.toContain("result line 1");
  3125. expect(app.tui.render(80).join("\n")).not.toContain("result line 4");
  3126. terminal.input?.("\x0f");
  3127. const detailed = app.tui.render(80).join("\n");
  3128. expect(detailed).toContain("result line 1");
  3129. expect(detailed).toContain("result line 3");
  3130. expect(detailed).toContain("result line 4");
  3131. expect(detailed).not.toContain("Details expanded");
  3132. terminal.input?.("\x0f");
  3133. const compact = app.tui.render(80).join("\n");
  3134. expect(compact).not.toContain("result line 1");
  3135. expect(compact).not.toContain("result line 3");
  3136. expect(compact).not.toContain("result line 4");
  3137. expect(compact).not.toContain("Details collapsed");
  3138. await app.stop();
  3139. });
  3140. it("uses Ctrl+T for tasks while Ctrl+O remains scoped to transcript details", async () => {
  3141. const terminal = new FakeTerminal();
  3142. const app = createTuiApp({
  3143. runtime: createRuntime(),
  3144. terminal,
  3145. version: "0.1.0",
  3146. workspaceDir: "/workspace",
  3147. });
  3148. app.start();
  3149. await app.ready;
  3150. app.controller.applyRuntimeTurnEvent("turn-todo", {
  3151. type: "generic",
  3152. eventType: "todo_updated",
  3153. turnId: "turn-todo",
  3154. data: {
  3155. todos: [
  3156. { content: "Inspect Desktop behavior", status: "completed" },
  3157. { content: "Polish the task rail", status: "in_progress" },
  3158. { content: "Run focused tests", status: "pending" },
  3159. { content: "Review narrow layouts", status: "pending" },
  3160. { content: "Update user documentation", status: "pending" },
  3161. { content: "Publish the test package", status: "pending" },
  3162. ],
  3163. },
  3164. });
  3165. const compact = app.tui.render(80).join("\n");
  3166. expect(compact).toContain("✓ Inspect Desktop behavior");
  3167. expect(compact).toContain("● Polish the task rail");
  3168. expect(compact).toContain("Ctrl+T expand");
  3169. expect(compact).not.toContain("Publish the test package");
  3170. expect(compact).not.toContain("todo_updated");
  3171. terminal.input?.("\x0f");
  3172. const transcriptDetailed = app.tui.render(80).join("\n");
  3173. expect(transcriptDetailed).toContain("Ctrl+T expand");
  3174. expect(transcriptDetailed).not.toContain("Publish the test package");
  3175. terminal.input?.("\x14");
  3176. const tasksExpanded = app.tui.render(80).join("\n");
  3177. expect(tasksExpanded).toContain(
  3178. "Todo list 1/6 · 5 remaining · Ctrl+T compact",
  3179. );
  3180. expect(tasksExpanded).toContain("Publish the test package");
  3181. terminal.input?.("\x0f");
  3182. expect(app.tui.render(80).join("\n")).toContain("Publish the test package");
  3183. app.controller.applyRuntimeTurnEvent("turn-todo", {
  3184. type: "generic",
  3185. eventType: "todo_updated",
  3186. turnId: "turn-todo",
  3187. data: {
  3188. todos: [
  3189. { content: "Inspect Desktop behavior", status: "completed" },
  3190. { content: "Polish the task rail", status: "completed" },
  3191. { content: "Run focused tests", status: "completed" },
  3192. { content: "Review narrow layouts", status: "completed" },
  3193. { content: "Update user documentation", status: "completed" },
  3194. { content: "Publish the test package", status: "completed" },
  3195. ],
  3196. },
  3197. });
  3198. expect(app.tui.render(80).join("\n")).toContain(
  3199. "✓ Todo list 6/6 completed",
  3200. );
  3201. await app.stop();
  3202. });
  3203. it("keeps settled Thinking hidden until Ctrl+O requests transcript details", async () => {
  3204. const terminal = new FakeTerminal();
  3205. const app = createTuiApp({
  3206. runtime: createRuntime(),
  3207. terminal,
  3208. version: "0.1.0",
  3209. workspaceDir: "/workspace",
  3210. });
  3211. app.start();
  3212. await app.ready;
  3213. app.transcript.upsert({
  3214. id: "thinking-detail-toggle",
  3215. kind: "thinking",
  3216. status: "succeeded",
  3217. content: "Private settled reasoning",
  3218. durationMs: 3_200,
  3219. createdAtMs: 1,
  3220. updatedAtMs: 3_201,
  3221. });
  3222. const compact = app.tui.render(80).join("\n");
  3223. expect(compact).toContain("Thought for 3.2s");
  3224. expect(compact).not.toContain("Private settled reasoning");
  3225. terminal.input?.("\x0f");
  3226. expect(app.tui.render(80).join("\n")).toContain(
  3227. "Private settled reasoning",
  3228. );
  3229. terminal.input?.("\x0f");
  3230. expect(app.tui.render(80).join("\n")).not.toContain(
  3231. "Private settled reasoning",
  3232. );
  3233. await app.stop();
  3234. });
  3235. it("returns from the conversation surface to Welcome after /new", async () => {
  3236. const terminal = new FakeTerminal();
  3237. const runtime = createRuntime();
  3238. const app = createTuiApp({
  3239. runtime,
  3240. terminal,
  3241. version: "0.1.0",
  3242. workspaceDir: "/workspace",
  3243. });
  3244. await app.ready;
  3245. await app.submit("Start a conversation");
  3246. expect(app.getSurface()).toBe("conversation");
  3247. await app.submit("/new");
  3248. expect(app.getSurface()).toBe("welcome");
  3249. expect(app.transcript.snapshot()).toEqual([]);
  3250. });
  3251. it("clears into a fresh conversation while keeping the previous session resumable", async () => {
  3252. const terminal = new FakeTerminal();
  3253. const runtime = createRuntime();
  3254. const app = createTuiApp({
  3255. runtime,
  3256. terminal,
  3257. version: "0.1.0",
  3258. workspaceDir: "/workspace",
  3259. });
  3260. await app.ready;
  3261. await app.submit("Keep this conversation");
  3262. expect(app.controller.snapshot().session?.sessionId).toBe("session-1");
  3263. await app.submit("/clear");
  3264. expect(app.getSurface()).toBe("welcome");
  3265. expect(app.transcript.snapshot()).toEqual([]);
  3266. expect(app.controller.snapshot()).toMatchObject({
  3267. status: "idle",
  3268. session: undefined,
  3269. sessions: [expect.objectContaining({ sessionId: "session-1" })],
  3270. });
  3271. expect(runtime.archiveSession).not.toHaveBeenCalled();
  3272. });
  3273. it("opens read-only Help above the Composer without using a TUI overlay", async () => {
  3274. const terminal = new FakeTerminal();
  3275. const runtime = createRuntime();
  3276. const app = createTuiApp({
  3277. runtime,
  3278. terminal,
  3279. version: "0.1.0",
  3280. workspaceDir: "/workspace",
  3281. });
  3282. const showOverlay = vi.spyOn(app.tui, "showOverlay");
  3283. app.start();
  3284. await app.ready;
  3285. const modelRequestsBeforeHelp = vi.mocked(runtime.listModels).mock.calls
  3286. .length;
  3287. const activeRunRequestsBeforeHelp = vi.mocked(runtime.getActiveRun).mock
  3288. .calls.length;
  3289. await app.submit("/help");
  3290. expect(runtime.sendMessage).not.toHaveBeenCalled();
  3291. expect(app.transcript.snapshot()).toEqual([]);
  3292. expect(app.tui.hasOverlay()).toBe(false);
  3293. expect(app.interaction.isActive()).toBe(true);
  3294. expect(terminal.mouseTracking).toBe(false);
  3295. terminal.input?.("m");
  3296. terminal.input?.("\r");
  3297. expect(app.tui.hasOverlay()).toBe(false);
  3298. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  3299. expect(app.editor.getText()).toBe("");
  3300. expect(runtime.listModels).toHaveBeenCalledTimes(modelRequestsBeforeHelp);
  3301. expect(runtime.getActiveRun).toHaveBeenCalledTimes(
  3302. activeRunRequestsBeforeHelp,
  3303. );
  3304. expect(showOverlay).not.toHaveBeenCalled();
  3305. await app.stop();
  3306. });
  3307. it("lets Help use the available terminal height instead of capping it at twelve rows", async () => {
  3308. const terminal = new FakeTerminal();
  3309. terminal.rows = 30;
  3310. const app = createTuiApp({
  3311. runtime: createRuntime(),
  3312. terminal,
  3313. version: "0.1.0",
  3314. workspaceDir: "/workspace",
  3315. });
  3316. app.start();
  3317. await app.submit("/help");
  3318. expect(app.interaction.current()?.render?.(terminal.columns)).toHaveLength(
  3319. 24,
  3320. );
  3321. terminal.rows = 18;
  3322. expect(app.interaction.current()?.render?.(terminal.columns)).toHaveLength(
  3323. 12,
  3324. );
  3325. await app.stop();
  3326. });
  3327. it("keeps steer executable and exposes it in slash-command discovery", async () => {
  3328. const terminal = new FakeTerminal();
  3329. const runtime = createRuntime();
  3330. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
  3331. schemaVersion: 1,
  3332. sessionId,
  3333. state: "running",
  3334. turnId: "turn-active",
  3335. actions: { steer: true },
  3336. }));
  3337. vi.mocked(runtime.steer).mockResolvedValue({
  3338. turnId: "turn-active",
  3339. mode: "steered",
  3340. });
  3341. const app = createTuiApp({
  3342. runtime,
  3343. terminal,
  3344. version: "0.1.0",
  3345. workspaceDir: "/workspace",
  3346. });
  3347. app.start();
  3348. await app.submit("Create session");
  3349. await app.submit("/help");
  3350. const helpPanel = app.interaction.current();
  3351. expect(helpPanel).toBeDefined();
  3352. expect(app.tui.hasOverlay()).toBe(false);
  3353. const helpPages: string[] = [];
  3354. for (let page = 0; page < 20; page += 1) {
  3355. const current = helpPanel?.render?.(100).join("\n") ?? "";
  3356. if (current === helpPages.at(-1)) break;
  3357. helpPages.push(current);
  3358. helpPanel?.handleInput?.("\x1b[6~");
  3359. }
  3360. const help = helpPages.join("\n");
  3361. expect(help).toContain("/steer <message>");
  3362. expect(help).not.toContain("/send-now");
  3363. expect(help).not.toContain("/retry");
  3364. helpPanel?.handleInput?.("\x1b");
  3365. await app.submit("/steer focus on the failing test");
  3366. expect(runtime.steer).toHaveBeenCalledWith(
  3367. expect.objectContaining({
  3368. sessionId: "session-1",
  3369. source: "api",
  3370. message: { content: "focus on the failing test" },
  3371. producerId: "mcode",
  3372. idempotencyKey: expect.stringMatching(/^run_action_/u),
  3373. }),
  3374. );
  3375. await app.stop();
  3376. });
  3377. it("refreshes Runtime steer capability before Enter submits the active Draft", async () => {
  3378. const terminal = new FakeTerminal();
  3379. const runtime = createRuntime();
  3380. let finishTurn: (() => void) | undefined;
  3381. let consumeSteer: (() => void) | undefined;
  3382. const steerConsumptionReady = new Promise<void>((resolve) => {
  3383. consumeSteer = resolve;
  3384. });
  3385. let steerAvailable = false;
  3386. vi.mocked(runtime.sendMessage).mockImplementation(
  3387. async function* sendMessage() {
  3388. yield {
  3389. type: "delta",
  3390. turnId: "turn-active",
  3391. content: "Working on it",
  3392. };
  3393. await steerConsumptionReady;
  3394. yield {
  3395. type: "message",
  3396. message: {
  3397. id: "message-steer",
  3398. turnId: "turn-active",
  3399. role: "user",
  3400. content: "focus on the failing test",
  3401. },
  3402. };
  3403. await new Promise<void>((resolve) => {
  3404. finishTurn = resolve;
  3405. });
  3406. yield { type: "done", turnId: "turn-active" };
  3407. },
  3408. );
  3409. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) =>
  3410. steerAvailable
  3411. ? {
  3412. schemaVersion: 1,
  3413. sessionId,
  3414. state: "running",
  3415. turnId: "turn-active",
  3416. actions: { steer: true },
  3417. }
  3418. : {
  3419. schemaVersion: 1,
  3420. sessionId,
  3421. state: "idle",
  3422. actions: { steer: false },
  3423. },
  3424. );
  3425. vi.mocked(runtime.steer).mockResolvedValue({
  3426. turnId: "turn-active",
  3427. mode: "steered",
  3428. });
  3429. const app = createTuiApp({
  3430. runtime,
  3431. terminal,
  3432. version: "0.1.0",
  3433. workspaceDir: "/workspace",
  3434. });
  3435. app.start();
  3436. await app.ready;
  3437. const submission = app.submit("Inspect the failure");
  3438. try {
  3439. await vi.waitFor(() =>
  3440. expect(app.tui.render(80).join("\n")).toContain("Running"),
  3441. );
  3442. steerAvailable = true;
  3443. terminal.input?.("focus on the failing test");
  3444. terminal.input?.("\r");
  3445. expect(app.editor.getText()).toBe("");
  3446. await vi.waitFor(() =>
  3447. expect(runtime.steer).toHaveBeenCalledWith(
  3448. expect.objectContaining({
  3449. sessionId: "session-1",
  3450. source: "api",
  3451. message: { content: "focus on the failing test" },
  3452. producerId: "mcode",
  3453. idempotencyKey: expect.stringMatching(/^run_action_/u),
  3454. requestedTurnId: "turn-active",
  3455. }),
  3456. ),
  3457. );
  3458. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  3459. kind: "user",
  3460. status: "pending",
  3461. content: "focus on the failing test",
  3462. userPresentation: "pending-steer",
  3463. });
  3464. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  3465. "↳ Next · focus on the failing test",
  3466. );
  3467. consumeSteer?.();
  3468. await vi.waitFor(() =>
  3469. expect(
  3470. app.transcript.snapshot().filter((cell) => cell.kind === "user"),
  3471. ).toEqual([
  3472. expect.objectContaining({ content: "Inspect the failure" }),
  3473. expect.objectContaining({
  3474. status: "succeeded",
  3475. content: "focus on the failing test",
  3476. sourceMessageId: "message-steer",
  3477. userPresentation: undefined,
  3478. }),
  3479. ]),
  3480. );
  3481. const rendered = app.tui.render(80).join("\n");
  3482. expect(rendered).toContain("Inspect the failure");
  3483. expect(rendered).toContain("focus on the failing test");
  3484. expect(stripAnsi(rendered)).not.toContain("↳ Next ·");
  3485. expect(app.editor.getText()).toBe("");
  3486. } finally {
  3487. consumeSteer?.();
  3488. await vi.waitFor(() => expect(finishTurn).toEqual(expect.any(Function)));
  3489. finishTurn?.();
  3490. await submission;
  3491. await app.stop();
  3492. }
  3493. });
  3494. it("queues with Alt+Enter, restores with Option+Up, then steers with Enter", async () => {
  3495. const terminal = new FakeTerminal();
  3496. const runtime = createRuntime();
  3497. const queuedItems: TuiQueuedMessage[] = [];
  3498. let finishTurn: (() => void) | undefined;
  3499. vi.mocked(runtime.sendMessage).mockImplementation(
  3500. async function* sendMessage() {
  3501. yield {
  3502. type: "delta",
  3503. turnId: "turn-active",
  3504. content: "Working on it",
  3505. };
  3506. await new Promise<void>((resolve) => {
  3507. finishTurn = resolve;
  3508. });
  3509. yield { type: "done", turnId: "turn-active" };
  3510. },
  3511. );
  3512. vi.mocked(runtime.enqueueMessage).mockImplementation(
  3513. async (sessionId, content) => {
  3514. const item: TuiQueuedMessage = {
  3515. itemId: "queue-guidance",
  3516. sessionId,
  3517. status: "queued",
  3518. source: "api",
  3519. content,
  3520. };
  3521. queuedItems.push(item);
  3522. return {
  3523. itemId: item.itemId,
  3524. status: item.status,
  3525. position: queuedItems.length,
  3526. };
  3527. },
  3528. );
  3529. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  3530. ...queuedItems,
  3531. ]);
  3532. vi.mocked(runtime.deleteQueuedMessage).mockImplementation(
  3533. async (_sessionId, itemId) => {
  3534. const index = queuedItems.findIndex((item) => item.itemId === itemId);
  3535. return index >= 0 ? queuedItems.splice(index, 1)[0] : undefined;
  3536. },
  3537. );
  3538. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
  3539. schemaVersion: 1,
  3540. sessionId,
  3541. state: "running",
  3542. turnId: "turn-active",
  3543. actions: { steer: true },
  3544. }));
  3545. const app = createTuiApp({
  3546. runtime,
  3547. terminal,
  3548. version: "0.1.0",
  3549. workspaceDir: "/workspace",
  3550. });
  3551. app.start();
  3552. await app.ready;
  3553. const submission = app.submit("Inspect the failure");
  3554. try {
  3555. await vi.waitFor(() =>
  3556. expect(app.tui.render(80).join("\n")).toContain("Running"),
  3557. );
  3558. terminal.input?.("Use the preview branch directly");
  3559. terminal.input?.("\x1b\r");
  3560. await vi.waitFor(() =>
  3561. expect(app.tui.render(80).join("\n")).toContain(
  3562. "Use the preview branch directly",
  3563. ),
  3564. );
  3565. await vi.waitFor(() =>
  3566. expect(runtime.listQueuedMessages).toHaveBeenCalledWith("session-1"),
  3567. );
  3568. expect(app.editor.getText()).toBe("");
  3569. terminal.input?.("\x1b[1;3A");
  3570. await vi.waitFor(() =>
  3571. expect(app.editor.getText()).toBe("Use the preview branch directly"),
  3572. );
  3573. expect(runtime.deleteQueuedMessage).toHaveBeenCalledWith(
  3574. "session-1",
  3575. "queue-guidance",
  3576. );
  3577. expect(runtime.steerQueuedMessage).not.toHaveBeenCalled();
  3578. await vi.waitFor(() =>
  3579. expect(app.tui.render(80).join("\n")).not.toContain("Queued ·"),
  3580. );
  3581. terminal.input?.("\r");
  3582. await vi.waitFor(() =>
  3583. expect(runtime.steer).toHaveBeenCalledWith(
  3584. expect.objectContaining({
  3585. sessionId: "session-1",
  3586. message: { content: "Use the preview branch directly" },
  3587. requestedTurnId: "turn-active",
  3588. }),
  3589. ),
  3590. );
  3591. expect(app.editor.getText()).toBe("");
  3592. } finally {
  3593. finishTurn?.();
  3594. await submission;
  3595. await app.stop();
  3596. }
  3597. });
  3598. it("renders /context from the Runtime-owned persisted context usage", async () => {
  3599. const runtime = createRuntime();
  3600. vi.mocked(runtime.getContextSnapshot).mockResolvedValue({
  3601. status: "live",
  3602. model: { provider: "minimax", id: "MiniMax-M3", contextWindow: 10_000 },
  3603. contextUsage: {
  3604. contextWindowTokens: 10_000,
  3605. usedTokens: 3_000,
  3606. totalCountSource: "PROVIDER_USAGE_ANCHORED",
  3607. components: [
  3608. { kind: "SYSTEM_PROMPT", tokens: 1_000 },
  3609. { kind: "MEMORY", tokens: 0 },
  3610. { kind: "TOOLS", tokens: 0 },
  3611. { kind: "SKILLS", tokens: 0 },
  3612. { kind: "MESSAGES", tokens: 2_000 },
  3613. { kind: "OTHER", tokens: 0 },
  3614. ],
  3615. },
  3616. });
  3617. const app = createTuiApp({
  3618. runtime,
  3619. terminal: new FakeTerminal(),
  3620. version: "0.1.0",
  3621. workspaceDir: "/workspace",
  3622. });
  3623. await app.submit("Create session");
  3624. const transcriptBeforeContext = app.transcript.snapshot();
  3625. await app.submit("/context");
  3626. expect(app.transcript.snapshot()).toEqual(transcriptBeforeContext);
  3627. expect(app.interaction.current()).toBeDefined();
  3628. const rendered = app.tui.render(80).join("\n");
  3629. expect(rendered).toContain("Context");
  3630. expect(rendered).toContain("3k/10k tokens (30% used)");
  3631. expect(rendered).toContain("Usage by category");
  3632. expect(rendered).toContain("Messages");
  3633. expect(rendered).toMatch(/[⛁⛀⛶]/u);
  3634. app.interaction.current()?.handleInput?.("\x1b");
  3635. expect(app.interaction.current()).toBeUndefined();
  3636. expect(app.transcript.snapshot()).toEqual(transcriptBeforeContext);
  3637. });
  3638. it("routes /init through the Runtime-owned init Skill and the normal Agent turn", async () => {
  3639. const terminal = new FakeTerminal();
  3640. const runtime = createRuntime();
  3641. vi.mocked(runtime.listSkills).mockResolvedValue({
  3642. skills: [
  3643. {
  3644. name: "init",
  3645. displayName: "Init",
  3646. description: "Analyze the codebase and generate AGENTS.md",
  3647. enabled: true,
  3648. sourceKind: "builtin",
  3649. },
  3650. ],
  3651. hasMore: false,
  3652. });
  3653. const app = createTuiApp({
  3654. runtime,
  3655. terminal,
  3656. version: "0.1.0",
  3657. workspaceDir: "/workspace",
  3658. });
  3659. app.start();
  3660. await app.ready;
  3661. await vi.waitFor(() => expect(runtime.listSkills).toHaveBeenCalled());
  3662. await app.submit("/init");
  3663. expect(runtime.sendMessage).toHaveBeenCalledWith(
  3664. expect.objectContaining({ id: "session-1", content: "/init" }),
  3665. expect.any(AbortSignal),
  3666. );
  3667. });
  3668. it("forwards literal slash-prefixed prompts without invoking local commands", async () => {
  3669. const runtime = createRuntime();
  3670. const app = createTuiApp({
  3671. runtime,
  3672. terminal: new FakeTerminal(),
  3673. version: "0.1.0",
  3674. workspaceDir: "/workspace",
  3675. });
  3676. const prompts = [
  3677. "/commands",
  3678. "/diff",
  3679. "/tool",
  3680. "/tools",
  3681. "/resumex",
  3682. "/renamex Renamed by a typo",
  3683. "/clearx",
  3684. "/tmp/sample-photo.JPG 用 read 工具直接读这个图片,告诉我是什么",
  3685. "/not-a-command explain what this text means",
  3686. "/context 这样还是会显示上下文信息",
  3687. ];
  3688. try {
  3689. app.start();
  3690. await app.ready;
  3691. for (const prompt of prompts) {
  3692. await app.submit(prompt);
  3693. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  3694. expect.objectContaining({ id: "session-1", content: prompt }),
  3695. expect.any(AbortSignal),
  3696. );
  3697. expect(app.interaction.current()).toBeUndefined();
  3698. expect(app.tui.hasOverlay()).toBe(false);
  3699. }
  3700. expect(runtime.sendMessage).toHaveBeenCalledTimes(prompts.length);
  3701. expect(runtime.renameSession).not.toHaveBeenCalled();
  3702. // Context metrics refresh independently; the overlay assertions above verify no local command ran.
  3703. expect(app.transcript.snapshot()).not.toContainEqual(
  3704. expect.objectContaining({ content: "Unknown command. Use /help." }),
  3705. );
  3706. } finally {
  3707. await app.stop();
  3708. }
  3709. });
  3710. it("keeps contextual commands local and submits other legacy names as prompts", async () => {
  3711. const terminal = new FakeTerminal();
  3712. const runtime = createRuntime();
  3713. const app = createTuiApp({
  3714. runtime,
  3715. terminal,
  3716. version: "0.1.0",
  3717. workspaceDir: "/workspace",
  3718. });
  3719. await app.submit("/queue");
  3720. expect(runtime.listQueuedMessages).not.toHaveBeenCalled();
  3721. expect(app.transcript.snapshot()).toEqual([]);
  3722. expect(app.tui.render(80).join("\n")).toContain(
  3723. "No messages are waiting and no response is currently running.",
  3724. );
  3725. await app.submit("/queue-clear");
  3726. expect(runtime.deleteQueuedMessage).not.toHaveBeenCalled();
  3727. await app.submit("/send-now do this first");
  3728. await app.submit("/retry");
  3729. expect(
  3730. vi
  3731. .mocked(runtime.sendMessage)
  3732. .mock.calls.map(([request]) => request.content),
  3733. ).toEqual(["/queue-clear", "/send-now do this first"]);
  3734. expect(app.tui.render(80).join("\n")).toContain(
  3735. "There is no failed response to retry in this Session.",
  3736. );
  3737. });
  3738. it("resends the failed user submission through /retry instead of sending the command as text", async () => {
  3739. const terminal = new FakeTerminal();
  3740. const runtime = createRuntime();
  3741. let attempt = 0;
  3742. vi.mocked(runtime.sendMessage).mockImplementation(
  3743. async function* sendMessage() {
  3744. attempt += 1;
  3745. if (attempt === 1) {
  3746. yield { type: "error", message: "terminated" };
  3747. return;
  3748. }
  3749. yield { type: "delta", content: "Recovered response" };
  3750. yield { type: "done" };
  3751. },
  3752. );
  3753. const app = createTuiApp({
  3754. runtime,
  3755. terminal,
  3756. version: "0.1.0",
  3757. workspaceDir: "/workspace",
  3758. });
  3759. await app.submit("Explain this failure");
  3760. expect(app.tui.render(100).join("\n")).toContain(
  3761. "The model connection ended before the response was completed.",
  3762. );
  3763. expect(app.tui.render(100).join("\n")).toContain(
  3764. "Run /retry to resend your last message.",
  3765. );
  3766. await app.submit("/retry");
  3767. expect(
  3768. vi
  3769. .mocked(runtime.sendMessage)
  3770. .mock.calls.map(([request]) => request.content),
  3771. ).toEqual(["Explain this failure", "Explain this failure"]);
  3772. expect(
  3773. vi
  3774. .mocked(runtime.sendMessage)
  3775. .mock.calls.some(([request]) => request.content === "/retry"),
  3776. ).toBe(false);
  3777. expect(app.transcript.snapshot()).toContainEqual(
  3778. expect.objectContaining({
  3779. kind: "assistant",
  3780. content: "Recovered response",
  3781. }),
  3782. );
  3783. await app.stop();
  3784. });
  3785. it("uses Runtime retry-continuation when a terminal failure has no local submission snapshot", async () => {
  3786. const terminal = new FakeTerminal();
  3787. const runtime = createRuntime();
  3788. const restoredSession = {
  3789. sessionId: "session-1",
  3790. title: "Restored session",
  3791. workspaceDir: "/workspace",
  3792. status: "error",
  3793. errorMessage: "terminated",
  3794. };
  3795. vi.mocked(runtime.listSessions).mockResolvedValue([restoredSession]);
  3796. vi.mocked(runtime.getSession).mockResolvedValue(restoredSession);
  3797. const app = createTuiApp({
  3798. runtime,
  3799. terminal,
  3800. version: "0.1.0",
  3801. workspaceDir: "/workspace",
  3802. });
  3803. app.start();
  3804. await app.ready;
  3805. await app.submit("/resume session-1");
  3806. expect(app.tui.render(100).join("\n")).toContain(
  3807. "The model connection ended before the response was completed.",
  3808. );
  3809. await app.submit("/retry");
  3810. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  3811. expect.objectContaining({
  3812. id: "session-1",
  3813. content: "",
  3814. clientIntent: "retry-continuation",
  3815. }),
  3816. expect.any(AbortSignal),
  3817. );
  3818. await app.stop();
  3819. });
  3820. it("reports service authentication failures without assuming the user needs to sign in", async () => {
  3821. const runtime = createRuntime();
  3822. vi.mocked(runtime.sendMessage).mockImplementation(
  3823. async function* sendMessage() {
  3824. yield { type: "error", message: "authentication failed" };
  3825. },
  3826. );
  3827. const app = createTuiApp({
  3828. runtime,
  3829. terminal: new FakeTerminal(),
  3830. version: "0.1.0",
  3831. workspaceDir: "/workspace",
  3832. });
  3833. await app.submit("Use the protected model");
  3834. expect(app.tui.render(100).join("\n")).toContain(
  3835. "The service rejected request authentication.",
  3836. );
  3837. expect(app.tui.render(100).join("\n")).not.toContain("Run /login");
  3838. expect(app.tui.render(100).join("\n")).not.toContain("Run /retry");
  3839. await app.submit("/retry");
  3840. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  3841. await app.stop();
  3842. });
  3843. it("cycles the shared permission mode with Alt+M without repeating the shortcut", async () => {
  3844. const terminal = new FakeTerminal();
  3845. const runtime = createRuntime();
  3846. const app = createTuiApp({
  3847. runtime,
  3848. terminal,
  3849. version: "0.1.0",
  3850. workspaceDir: "/workspace",
  3851. });
  3852. app.start();
  3853. await app.ready;
  3854. expect(app.tui.render(80).join("\n")).toContain("Auto");
  3855. expect(app.tui.render(80).join("\n")).not.toContain("Shift+Tab");
  3856. expect(app.tui.render(80).join("\n")).not.toContain(
  3857. "Shift+Tab switch mode",
  3858. );
  3859. terminal.input?.("\x1bm");
  3860. await vi.waitFor(() => {
  3861. expect(runtime.setPermissionMode).toHaveBeenCalledWith(
  3862. "bypassPermissions",
  3863. );
  3864. const rendered = app.tui.render(80).join("\n");
  3865. expect(rendered).toContain("Full access");
  3866. expect(rendered).not.toContain("Shift+Tab");
  3867. expect(rendered.match(/Full access/g)).toHaveLength(1);
  3868. expect(rendered).not.toContain("Desktop permissions:");
  3869. });
  3870. await app.stop();
  3871. });
  3872. it("projects Token Plan warnings into the status rail", async () => {
  3873. const terminal = new FakeTerminal();
  3874. const runtime = createRuntime();
  3875. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  3876. status: "ready",
  3877. defaultModel: "minimax/MiniMax-M2.7",
  3878. providerId: "minimax",
  3879. modelId: "MiniMax-M2.7",
  3880. authMode: "managed-login",
  3881. managedTokenPresent: true,
  3882. modelSource: "token-plan",
  3883. tokenPlanQuotaState: "available",
  3884. tokenPlanQuota: {
  3885. fiveHour: { remainingPercent: 30, unlimited: false },
  3886. weekly: { remainingPercent: 64, unlimited: false },
  3887. },
  3888. warnings: [],
  3889. });
  3890. const app = createTuiApp({
  3891. runtime,
  3892. terminal,
  3893. version: "0.1.0",
  3894. workspaceDir: "/workspace",
  3895. });
  3896. app.start();
  3897. await app.ready;
  3898. await app.submit("Measure this turn");
  3899. await vi.waitFor(() => {
  3900. const rendered = app.tui.render(120).join("\n");
  3901. expect(rendered).toContain("5h 30%");
  3902. expect(rendered).not.toContain("Week 64%");
  3903. });
  3904. await app.stop();
  3905. });
  3906. it("keeps Token Plan subscription state out of the status rail when no quota exists", async () => {
  3907. const terminal = new FakeTerminal();
  3908. const runtime = createRuntime();
  3909. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  3910. status: "ready",
  3911. defaultModel: "minimax/MiniMax-M3",
  3912. providerId: "minimax",
  3913. modelId: "MiniMax-M3",
  3914. authMode: "managed-login",
  3915. managedTokenPresent: true,
  3916. modelSource: "token-plan",
  3917. tokenPlanQuotaState: "not-subscribed",
  3918. warnings: [],
  3919. });
  3920. const app = createTuiApp({
  3921. runtime,
  3922. terminal,
  3923. version: "0.1.0",
  3924. workspaceDir: "/workspace",
  3925. });
  3926. app.start();
  3927. await app.ready;
  3928. await app.submit("Measure this turn");
  3929. await vi.waitFor(() => {
  3930. const rendered = app.tui.render(120).join("\n");
  3931. expect(rendered).toContain("✦ MiniMax M2.7");
  3932. expect(rendered).not.toMatch(/Context 5%|Quota|Plan|5h|Week/u);
  3933. });
  3934. await app.stop();
  3935. });
  3936. it("keeps the current permission mode when an Alt+M update fails", async () => {
  3937. const terminal = new FakeTerminal();
  3938. const runtime = createRuntime();
  3939. vi.mocked(runtime.setPermissionMode).mockRejectedValueOnce(
  3940. new Error("config is read-only"),
  3941. );
  3942. const app = createTuiApp({
  3943. runtime,
  3944. terminal,
  3945. version: "0.1.0",
  3946. workspaceDir: "/workspace",
  3947. });
  3948. app.start();
  3949. await app.ready;
  3950. terminal.input?.("\x1bm");
  3951. await vi.waitFor(() => {
  3952. expect(app.tui.render(80).join("\n")).toContain("Auto");
  3953. expect(app.tui.render(80).join("\n")).not.toContain("FULL");
  3954. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  3955. kind: "warning",
  3956. content:
  3957. "Permission mode was not changed: config is read-only. Retry /permission or Alt+M.",
  3958. });
  3959. });
  3960. await app.stop();
  3961. });
  3962. it("arms Plan with Shift+Tab and sends the one-shot Runtime intent", async () => {
  3963. const terminal = new FakeTerminal();
  3964. const runtime = createRuntime();
  3965. const app = createTuiApp({
  3966. runtime,
  3967. terminal,
  3968. version: "0.1.0",
  3969. workspaceDir: "/workspace",
  3970. });
  3971. app.start();
  3972. await app.ready;
  3973. terminal.input?.("\x1b[Z");
  3974. expect(app.tui.render(100).join("\n")).toContain("PLAN next");
  3975. expect(app.tui.render(100).join("\n")).toContain(
  3976. "Plan Mode · next message enters Plan",
  3977. );
  3978. terminal.input?.("计");
  3979. expect(app.tui.render(100).join("\n")).toContain(
  3980. "Plan Mode · next message enters Plan",
  3981. );
  3982. expect(app.tui.render(32).join("\n")).toContain("Plan Mode");
  3983. terminal.input?.("\x7f");
  3984. expect(app.editor.getText()).toBe("");
  3985. expect(app.tui.render(100).join("\n")).toContain(
  3986. "Plan Mode · next message enters Plan",
  3987. );
  3988. terminal.input?.("计");
  3989. terminal.input?.("划");
  3990. expect(app.editor.getText()).toBe("计划");
  3991. expect(app.tui.render(100).join("\n")).toContain("PLAN next");
  3992. expect(app.tui.render(100).join("\n")).toContain(
  3993. "Plan Mode · next message enters Plan",
  3994. );
  3995. terminal.input?.("\r");
  3996. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
  3997. await app.controller.whenIdle();
  3998. expect(runtime.sendMessage).toHaveBeenCalledWith(
  3999. expect.objectContaining({
  4000. content: "计划",
  4001. clientIntent: "plan-entry",
  4002. }),
  4003. expect.any(AbortSignal),
  4004. );
  4005. expect(app.tui.render(100).join("\n")).toContain("PLAN");
  4006. expect(app.tui.render(100).join("\n")).toContain("Auto");
  4007. await app.stop();
  4008. });
  4009. it("keeps ordinary messages in Plan and exits only with an explicit one-shot intent", async () => {
  4010. const runtime = createRuntime();
  4011. const app = createTuiApp({
  4012. runtime,
  4013. terminal: new FakeTerminal(),
  4014. version: "0.1.0",
  4015. workspaceDir: "/workspace",
  4016. });
  4017. app.start();
  4018. await app.ready;
  4019. await app.submit("/plan on");
  4020. await app.submit("Draft the implementation plan");
  4021. await app.submit("Refine the verification section");
  4022. expect(runtime.sendMessage).toHaveBeenNthCalledWith(
  4023. 2,
  4024. expect.not.objectContaining({ clientIntent: expect.anything() }),
  4025. expect.any(AbortSignal),
  4026. );
  4027. expect(app.tui.render(100).join("\n")).toContain(
  4028. "/workspace │ PLAN │ Auto",
  4029. );
  4030. await app.submit("/plan off");
  4031. await app.submit("Implement the approved direction");
  4032. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  4033. expect.objectContaining({ clientIntent: "plan-exit" }),
  4034. expect.any(AbortSignal),
  4035. );
  4036. expect(app.tui.render(100).join("\n")).not.toContain("PLAN");
  4037. await app.stop();
  4038. });
  4039. it("keeps the one-shot Plan intent armed when direct admission rejects it", async () => {
  4040. const runtime = createRuntime();
  4041. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  4042. async function* rejectedAdmission() {
  4043. yield* [] as TuiStreamEvent[];
  4044. throw Object.assign(new Error("Plan entry is disabled"), {
  4045. code: "local_plan_entry_disabled",
  4046. });
  4047. },
  4048. );
  4049. const app = createTuiApp({
  4050. runtime,
  4051. terminal: new FakeTerminal(),
  4052. version: "0.1.0",
  4053. workspaceDir: "/workspace",
  4054. });
  4055. app.start();
  4056. await app.ready;
  4057. await app.submit("/plan on");
  4058. await app.submit("Plan this after the feature is enabled");
  4059. expect(app.tui.render(100).join("\n")).toContain("PLAN next");
  4060. await app.submit("Retry the same Plan intent");
  4061. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  4062. expect.objectContaining({ clientIntent: "plan-entry" }),
  4063. expect.any(AbortSignal),
  4064. );
  4065. await app.stop();
  4066. });
  4067. it("settles a Plan transition from authoritative Session metadata when the stream is empty", async () => {
  4068. const runtime = createRuntime();
  4069. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  4070. async function* emptyAcceptedStream() {
  4071. yield* [] as TuiStreamEvent[];
  4072. },
  4073. );
  4074. vi.mocked(runtime.getSession).mockResolvedValue({
  4075. sessionId: "session-1",
  4076. workspace: "/workspace",
  4077. interactionMode: "plan",
  4078. });
  4079. const app = createTuiApp({
  4080. runtime,
  4081. terminal: new FakeTerminal(),
  4082. version: "0.1.0",
  4083. workspaceDir: "/workspace",
  4084. });
  4085. app.start();
  4086. await app.ready;
  4087. await app.submit("/plan on");
  4088. await app.submit("Plan without emitting a stream event");
  4089. expect(runtime.getSession).toHaveBeenCalledWith("session-1");
  4090. expect(app.tui.render(100).join("\n")).toContain(
  4091. "/workspace │ PLAN │ Auto",
  4092. );
  4093. expect(app.tui.render(100).join("\n")).not.toContain("PLAN next");
  4094. await app.stop();
  4095. });
  4096. it("clears accepted Plan entry while authoritative metadata refresh is unavailable", async () => {
  4097. const runtime = createRuntime();
  4098. vi.mocked(runtime.getSession).mockRejectedValue(
  4099. new Error("metadata temporarily unavailable"),
  4100. );
  4101. const app = createTuiApp({
  4102. runtime,
  4103. terminal: new FakeTerminal(),
  4104. version: "0.1.0",
  4105. workspaceDir: "/workspace",
  4106. });
  4107. app.start();
  4108. await app.ready;
  4109. await app.submit("/plan on");
  4110. await app.submit("OK");
  4111. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4112. expect.objectContaining({ content: "OK", clientIntent: "plan-entry" }),
  4113. expect.any(AbortSignal),
  4114. );
  4115. expect(app.tui.render(100).join("\n")).not.toContain("/workspace │ PLAN");
  4116. expect(app.tui.render(100).join("\n")).not.toContain("DEFAULT next");
  4117. await app.stop();
  4118. });
  4119. it("preserves Plan intent through direct busy fallback into the Runtime Queue", async () => {
  4120. const runtime = createRuntime();
  4121. vi.mocked(runtime.listModels).mockResolvedValue([
  4122. {
  4123. providerId: "minimax",
  4124. modelId: "MiniMax-M2.7",
  4125. selected: true,
  4126. variant: "",
  4127. },
  4128. ]);
  4129. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  4130. async function* busyAdmission() {
  4131. yield* [] as TuiStreamEvent[];
  4132. throw Object.assign(new Error("Session is busy"), {
  4133. code: "local_session_busy",
  4134. });
  4135. },
  4136. );
  4137. const app = createTuiApp({
  4138. runtime,
  4139. terminal: new FakeTerminal(),
  4140. version: "0.1.0",
  4141. workspaceDir: "/workspace",
  4142. });
  4143. app.start();
  4144. await app.ready;
  4145. await app.submit("/plan on");
  4146. await app.submit("Queue this Plan request");
  4147. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  4148. "session-1",
  4149. "Queue this Plan request",
  4150. {
  4151. attachments: [],
  4152. clientIntent: "plan-entry",
  4153. model: { providerId: "minimax", modelId: "MiniMax-M2.7", variant: "" },
  4154. },
  4155. );
  4156. expect(app.tui.render(100).join("\n")).not.toContain("PLAN queued");
  4157. await app.stop();
  4158. });
  4159. it("binds a one-shot Plan intent to only the first concurrent submission", async () => {
  4160. let releaseFirstEvent: (() => void) | undefined;
  4161. const firstEventGate = new Promise<void>((resolve) => {
  4162. releaseFirstEvent = resolve;
  4163. });
  4164. const runtime = createRuntime();
  4165. vi.mocked(runtime.sendMessage).mockImplementation(
  4166. async function* delayedAdmission() {
  4167. await firstEventGate;
  4168. yield { type: "delta", content: "Planning" };
  4169. yield { type: "done" };
  4170. },
  4171. );
  4172. const app = createTuiApp({
  4173. runtime,
  4174. terminal: new FakeTerminal(),
  4175. version: "0.1.0",
  4176. workspaceDir: "/workspace",
  4177. });
  4178. app.start();
  4179. await app.ready;
  4180. await app.submit("/plan on");
  4181. const first = app.submit("Plan the implementation");
  4182. await vi.waitFor(() =>
  4183. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  4184. );
  4185. await app.submit("Queue a follow-up while admission is quiet");
  4186. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4187. expect.objectContaining({ clientIntent: "plan-entry" }),
  4188. expect.any(AbortSignal),
  4189. );
  4190. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  4191. "session-1",
  4192. "Queue a follow-up while admission is quiet",
  4193. {
  4194. attachments: [],
  4195. model: { providerId: "minimax", modelId: "MiniMax-M2.7" },
  4196. },
  4197. );
  4198. releaseFirstEvent?.();
  4199. await first;
  4200. await app.stop();
  4201. });
  4202. it("shows the Desktop-aligned confirmation when the Agent calls EnterPlanMode", async () => {
  4203. let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  4204. const runtime = createRuntime();
  4205. vi.mocked(runtime.watchEvents).mockImplementation(
  4206. async function* watchEvents(signal) {
  4207. const event = await new Promise<TuiRuntimeEvent | undefined>(
  4208. (resolve) => {
  4209. emitEvent = resolve;
  4210. signal.addEventListener("abort", () => resolve(undefined), {
  4211. once: true,
  4212. });
  4213. },
  4214. );
  4215. if (event) yield event;
  4216. await new Promise<void>((resolve) => {
  4217. signal.addEventListener("abort", resolve, { once: true });
  4218. });
  4219. },
  4220. );
  4221. const app = createTuiApp({
  4222. runtime,
  4223. terminal: new FakeTerminal(),
  4224. version: "0.1.0",
  4225. workspaceDir: "/workspace",
  4226. });
  4227. app.start();
  4228. await app.ready;
  4229. await app.submit("Plan a complex change");
  4230. await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
  4231. const askEvent = runtimeEvent({
  4232. type: "questionnaire.ask",
  4233. timestamp: Date.now(),
  4234. source: "runtime",
  4235. payload: {
  4236. sessionId: "session-1",
  4237. agentName: "mavis",
  4238. request: planEntryEventRequest("plan-entry-agent-tool"),
  4239. },
  4240. });
  4241. expect(askEvent).toMatchObject({
  4242. type: "questionnaire.ask",
  4243. sessionId: "session-1",
  4244. request: { id: "plan-entry-agent-tool", mode: "plan" },
  4245. });
  4246. emitEvent?.(askEvent);
  4247. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  4248. const panel = app.interaction.current();
  4249. const rendered = panel?.render?.(100).join("\n") ?? "";
  4250. expect(rendered).toContain("Use Plan mode?");
  4251. expect(rendered).toContain(
  4252. "Plan mode structures complex tasks before execution.",
  4253. );
  4254. expect(rendered).toContain("Continue with plan");
  4255. expect(rendered).toContain("Deny");
  4256. panel?.handleInput?.("\r");
  4257. await vi.waitFor(() =>
  4258. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  4259. "mavis",
  4260. "plan-entry-agent-tool",
  4261. [
  4262. {
  4263. stepId: "plan-enter",
  4264. selectedOptionIds: ["confirm"],
  4265. selectedOther: false,
  4266. },
  4267. ],
  4268. ),
  4269. );
  4270. await app.stop();
  4271. });
  4272. it("keeps a pending Plan exit armed when steer guides the current Plan Turn", async () => {
  4273. let finishTurn: (() => void) | undefined;
  4274. let interactionMode: "plan" | undefined;
  4275. const runtime = createRuntime();
  4276. vi.mocked(runtime.getSession).mockImplementation(async () => ({
  4277. sessionId: "session-1",
  4278. workspace: "/workspace",
  4279. ...(interactionMode ? { interactionMode } : {}),
  4280. }));
  4281. vi.mocked(runtime.sendMessage).mockImplementation(
  4282. async function* activePlanTurn() {
  4283. interactionMode = "plan";
  4284. yield { type: "delta", content: "Drafting the plan" };
  4285. await new Promise<void>((resolve) => {
  4286. finishTurn = resolve;
  4287. });
  4288. yield { type: "done" };
  4289. },
  4290. );
  4291. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
  4292. schemaVersion: 1,
  4293. sessionId,
  4294. state: "running",
  4295. turnId: "turn-plan",
  4296. actions: { steer: true },
  4297. }));
  4298. vi.mocked(runtime.steer).mockResolvedValue({
  4299. turnId: "turn-plan",
  4300. mode: "steered",
  4301. });
  4302. const app = createTuiApp({
  4303. runtime,
  4304. terminal: new FakeTerminal(),
  4305. version: "0.1.0",
  4306. workspaceDir: "/workspace",
  4307. });
  4308. app.start();
  4309. await app.ready;
  4310. await app.submit("/plan on");
  4311. const planTurn = app.submit("Draft a plan");
  4312. await vi.waitFor(() =>
  4313. expect(app.tui.render(100).join("\n")).toContain(
  4314. "/workspace │ PLAN │ Auto",
  4315. ),
  4316. );
  4317. await app.submit("/plan off");
  4318. await app.submit("/steer include rollback checks");
  4319. expect(runtime.steer).toHaveBeenCalledWith(
  4320. expect.objectContaining({
  4321. sessionId: "session-1",
  4322. message: { content: "include rollback checks" },
  4323. }),
  4324. );
  4325. expect(app.tui.render(100).join("\n")).toContain("DEFAULT next");
  4326. finishTurn?.();
  4327. await planTurn;
  4328. await app.stop();
  4329. });
  4330. it("does not arm a mode transition while a Plan Review is pending", async () => {
  4331. let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  4332. const runtime = createRuntime();
  4333. vi.mocked(runtime.watchEvents).mockImplementation(
  4334. async function* watchEvents(signal) {
  4335. const event = await new Promise<TuiRuntimeEvent | undefined>(
  4336. (resolve) => {
  4337. emitEvent = resolve;
  4338. signal.addEventListener("abort", () => resolve(undefined), {
  4339. once: true,
  4340. });
  4341. },
  4342. );
  4343. if (event) yield event;
  4344. await new Promise<void>((resolve) => {
  4345. signal.addEventListener("abort", resolve, { once: true });
  4346. });
  4347. },
  4348. );
  4349. const terminal = new FakeTerminal();
  4350. const app = createTuiApp({
  4351. runtime,
  4352. terminal,
  4353. version: "0.1.0",
  4354. workspaceDir: "/workspace",
  4355. });
  4356. app.start();
  4357. await app.ready;
  4358. await app.submit("/plan on");
  4359. await app.submit("Draft a plan");
  4360. await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
  4361. emitEvent?.(
  4362. runtimeEvent({
  4363. type: "questionnaire.ask",
  4364. timestamp: Date.now(),
  4365. source: "runtime",
  4366. payload: {
  4367. sessionId: "session-1",
  4368. agentName: "mavis",
  4369. request: planReviewEventRequest("plan-review-mode-guard"),
  4370. },
  4371. }),
  4372. );
  4373. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  4374. // The compact panel owns the decision; the frozen plan is projected to the Transcript.
  4375. expect(app.interaction.current()?.render?.(100).join("\n")).toContain(
  4376. "Plan complete. What would you like to do?",
  4377. );
  4378. expect(app.tui.render(100).join("\n")).toContain("Frozen plan");
  4379. terminal.input?.("\x1b[Z");
  4380. expect(app.interaction.isActive()).toBe(true);
  4381. expect(app.tui.render(100).join("\n")).toContain(
  4382. "/workspace │ PLAN │ Auto",
  4383. );
  4384. expect(app.tui.render(100).join("\n")).not.toContain("DEFAULT next");
  4385. await app.submit("/plan off");
  4386. expect(app.interaction.isActive()).toBe(true);
  4387. expect(app.tui.render(100).join("\n")).toContain(
  4388. "/workspace │ PLAN │ Auto",
  4389. );
  4390. expect(app.tui.render(100).join("\n")).not.toContain("DEFAULT next");
  4391. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  4392. await app.submit("/steer bypass the review");
  4393. expect(app.interaction.isActive()).toBe(true);
  4394. expect(runtime.steer).not.toHaveBeenCalled();
  4395. app.interaction.current()?.handleInput?.("\u001b");
  4396. await vi.waitFor(() =>
  4397. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  4398. "mavis",
  4399. "plan-review-mode-guard",
  4400. [expect.objectContaining({ skipped: true })],
  4401. ),
  4402. );
  4403. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  4404. expect(app.tui.render(100).join("\n")).toContain(
  4405. "/workspace │ PLAN │ Auto",
  4406. );
  4407. await app.stop();
  4408. });
  4409. it("streams Plan feedback and replaces it with the revised Plan Review", async () => {
  4410. let emitReview: ((event: TuiRuntimeEvent) => void) | undefined;
  4411. let releaseContinuation: (() => void) | undefined;
  4412. let finishReply: ((value: boolean) => void) | undefined;
  4413. const runtime = createRuntime();
  4414. vi.mocked(runtime.replyQuestionnaire).mockImplementation(
  4415. async () =>
  4416. await new Promise<boolean>((resolve) => {
  4417. finishReply = resolve;
  4418. }),
  4419. );
  4420. vi.mocked(runtime.watchEvents).mockImplementation(
  4421. async function* watchEvents(signal) {
  4422. const review = await new Promise<TuiRuntimeEvent | undefined>(
  4423. (resolve) => {
  4424. emitReview = resolve;
  4425. signal.addEventListener("abort", () => resolve(undefined), {
  4426. once: true,
  4427. });
  4428. },
  4429. );
  4430. if (!review || signal.aborted) return;
  4431. yield review;
  4432. await new Promise<void>((resolve) => {
  4433. releaseContinuation = resolve;
  4434. signal.addEventListener("abort", resolve, { once: true });
  4435. });
  4436. if (signal.aborted) return;
  4437. const turnId = "turn-runtime-plan-feedback";
  4438. yield runtimeEvent({
  4439. type: "session.start",
  4440. timestamp: Date.now(),
  4441. source: "runtime",
  4442. payload: { sessionId: "session-1", turnId },
  4443. });
  4444. vi.mocked(runtime.getMessages).mockResolvedValue([
  4445. {
  4446. id: "assistant-revised-plan",
  4447. role: "assistant",
  4448. content: "I revised the plan with rollback coverage.",
  4449. },
  4450. ]);
  4451. yield runtimeEvent({
  4452. type: "questionnaire.ask",
  4453. timestamp: Date.now(),
  4454. source: "runtime",
  4455. payload: {
  4456. sessionId: "session-1",
  4457. agentName: "mavis",
  4458. request: {
  4459. ...planReviewEventRequest("plan-review-feedback-revised"),
  4460. modePayload: {
  4461. planReview: {
  4462. markdown:
  4463. "# Revised frozen plan\n\nIncludes rollback coverage.",
  4464. path: "/history/session-1/artifacts/plan.md",
  4465. },
  4466. },
  4467. },
  4468. },
  4469. });
  4470. yield runtimeEvent({
  4471. type: "session.finish",
  4472. timestamp: Date.now(),
  4473. source: "runtime",
  4474. payload: { sessionId: "session-1", turnId },
  4475. });
  4476. finishReply?.(true);
  4477. await new Promise<void>((resolve) => {
  4478. signal.addEventListener("abort", resolve, { once: true });
  4479. });
  4480. },
  4481. );
  4482. const terminal = new FakeTerminal();
  4483. const app = createTuiApp({
  4484. runtime,
  4485. terminal,
  4486. version: "0.1.0",
  4487. workspaceDir: "/workspace",
  4488. });
  4489. app.start();
  4490. await app.ready;
  4491. await app.submit("/plan on");
  4492. await app.submit("Draft a plan");
  4493. await vi.waitFor(() => expect(emitReview).toBeTypeOf("function"));
  4494. emitReview?.(
  4495. runtimeEvent({
  4496. type: "questionnaire.ask",
  4497. timestamp: Date.now(),
  4498. source: "runtime",
  4499. payload: {
  4500. sessionId: "session-1",
  4501. agentName: "mavis",
  4502. request: planReviewEventRequest("plan-review-feedback-live"),
  4503. },
  4504. }),
  4505. );
  4506. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  4507. terminal.input?.("\u001b[B");
  4508. terminal.input?.("\u001b[B");
  4509. terminal.input?.("\r");
  4510. for (const character of "Add rollback coverage")
  4511. terminal.input?.(character);
  4512. terminal.input?.("\r");
  4513. await vi.waitFor(() => expect(finishReply).toBeTypeOf("function"));
  4514. releaseContinuation?.();
  4515. await vi.waitFor(() =>
  4516. expect(
  4517. app.transcript
  4518. .snapshot()
  4519. .map((cell) => cell.content)
  4520. .join("\n"),
  4521. ).toContain("I revised the plan with rollback coverage."),
  4522. );
  4523. expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
  4524. "session-1",
  4525. "turn-runtime-plan-feedback",
  4526. expect.any(AbortSignal),
  4527. );
  4528. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  4529. // The revised plan is projected to the Transcript; the panel stays the compact decision.
  4530. expect(app.interaction.current()?.render?.(100).join("\n")).toContain(
  4531. "Plan complete. What would you like to do?",
  4532. );
  4533. expect(app.tui.render(100).join("\n")).toContain("Revised frozen plan");
  4534. expect(app.tui.render(100).join("\n")).not.toContain(
  4535. "Message · Enter send",
  4536. );
  4537. await app.stop();
  4538. });
  4539. it("supports explicit /plan and /permission mode commands", async () => {
  4540. const runtime = createRuntime();
  4541. const app = createTuiApp({
  4542. runtime,
  4543. terminal: new FakeTerminal(),
  4544. version: "0.1.0",
  4545. workspaceDir: "/workspace",
  4546. });
  4547. app.start();
  4548. await app.ready;
  4549. await app.submit("/plan on");
  4550. expect(app.tui.render(100).join("\n")).toContain("PLAN next");
  4551. await app.submit("/permission full");
  4552. expect(runtime.setPermissionMode).toHaveBeenCalledWith("bypassPermissions");
  4553. expect(app.tui.render(100).join("\n")).toContain("Full access");
  4554. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4555. await app.submit("Plan with Full access");
  4556. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4557. expect.objectContaining({ clientIntent: "plan-entry" }),
  4558. expect.any(AbortSignal),
  4559. );
  4560. expect(app.tui.render(100).join("\n")).toContain("PLAN");
  4561. expect(app.tui.render(100).join("\n")).toContain("Full access");
  4562. await app.stop();
  4563. });
  4564. it("opens a permission mode selector for bare /permission", async () => {
  4565. const runtime = createRuntime();
  4566. const terminal = new FakeTerminal();
  4567. const app = createTuiApp({
  4568. runtime,
  4569. terminal,
  4570. version: "0.1.0",
  4571. workspaceDir: "/workspace",
  4572. });
  4573. app.start();
  4574. await app.ready;
  4575. await app.submit("/permission");
  4576. expect(app.interaction.isActive()).toBe(true);
  4577. const rendered = app.interaction.current()?.render?.(100).join("\n") ?? "";
  4578. expect(rendered).toContain("╭─ Permission");
  4579. expect(rendered).toContain("Current · Auto");
  4580. expect(rendered).toContain("ASK");
  4581. expect(rendered).toContain("› AUTO");
  4582. expect(rendered).toContain("FULL");
  4583. expect(runtime.setPermissionMode).not.toHaveBeenCalled();
  4584. terminal.input?.("\u001b[B");
  4585. terminal.input?.("\r");
  4586. await vi.waitFor(() =>
  4587. expect(runtime.setPermissionMode).toHaveBeenCalledWith(
  4588. "bypassPermissions",
  4589. ),
  4590. );
  4591. expect(app.interaction.isActive()).toBe(false);
  4592. expect(app.tui.render(100).join("\n")).toContain("Full access");
  4593. await app.submit("/permission status");
  4594. expect(app.interaction.isActive()).toBe(false);
  4595. expect(
  4596. app.transcript
  4597. .snapshot()
  4598. .map((cell) => cell.content)
  4599. .join("\n"),
  4600. ).toContain("Permission mode: Full access.");
  4601. await app.stop();
  4602. });
  4603. it("opens the latest settled Plan as a read-only full snapshot", async () => {
  4604. const runtime = createRuntime();
  4605. vi.mocked(runtime.getLatestPlanReview).mockResolvedValue(
  4606. planReviewEventRequest("plan-review-settled"),
  4607. );
  4608. const app = createTuiApp({
  4609. runtime,
  4610. terminal: new FakeTerminal(),
  4611. version: "0.1.0",
  4612. workspaceDir: "/workspace",
  4613. });
  4614. app.start();
  4615. await app.ready;
  4616. await app.openSession("session-1");
  4617. await app.submit("/plan view");
  4618. expect(runtime.getLatestPlanReview).toHaveBeenCalledWith(
  4619. "mavis",
  4620. "session-1",
  4621. );
  4622. const rendered = app.interaction.current()?.render?.(100).join("\n") ?? "";
  4623. expect(rendered).toContain("Frozen plan");
  4624. expect(rendered).toContain("/history/session-1/artifacts/plan.md");
  4625. expect(rendered).not.toContain("Agree and start implementation");
  4626. app.interaction.current()?.handleInput?.("\u001b");
  4627. expect(app.interaction.isActive()).toBe(false);
  4628. await app.stop();
  4629. });
  4630. it("does not open a settled Plan after the active Session changes", async () => {
  4631. let resolveReview:
  4632. | ((request: TuiQuestionnaireRequest | undefined) => void)
  4633. | undefined;
  4634. const runtime = createRuntime();
  4635. vi.mocked(runtime.getLatestPlanReview).mockImplementation(
  4636. async () =>
  4637. await new Promise<TuiQuestionnaireRequest | undefined>((resolve) => {
  4638. resolveReview = resolve;
  4639. }),
  4640. );
  4641. const app = createTuiApp({
  4642. runtime,
  4643. terminal: new FakeTerminal(),
  4644. version: "0.1.0",
  4645. workspaceDir: "/workspace",
  4646. });
  4647. app.start();
  4648. await app.ready;
  4649. await app.openSession("session-1");
  4650. const viewing = app.submit("/plan view");
  4651. await vi.waitFor(() => expect(resolveReview).toBeTypeOf("function"));
  4652. await app.openSession("session-2");
  4653. resolveReview?.(planReviewEventRequest("stale-plan-review"));
  4654. await viewing;
  4655. expect(app.interaction.isActive()).toBe(false);
  4656. expect(app.tui.render(100).join("\n")).not.toContain("Frozen plan");
  4657. await app.stop();
  4658. });
  4659. it("blocks Plan entry but still allows Plan exit when the Runtime capability is disabled", async () => {
  4660. const runtime = createRuntime();
  4661. vi.mocked(runtime.getPlanModeCapabilities).mockResolvedValue({
  4662. entryEnabled: false,
  4663. });
  4664. const terminal = new FakeTerminal();
  4665. const app = createTuiApp({
  4666. runtime,
  4667. terminal,
  4668. version: "0.1.0",
  4669. workspaceDir: "/workspace",
  4670. });
  4671. app.start();
  4672. await app.ready;
  4673. await app.openSession("session-1");
  4674. terminal.input?.("\x1b[Z");
  4675. await app.submit("/plan on");
  4676. expect(app.tui.render(100).join("\n")).not.toContain("PLAN next");
  4677. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4678. vi.mocked(runtime.getSession).mockResolvedValue({
  4679. sessionId: "session-1",
  4680. workspace: "/workspace",
  4681. interactionMode: "plan",
  4682. });
  4683. await app.controller.refreshSessionMetadata("session-1");
  4684. terminal.input?.("\x1b[Z");
  4685. expect(app.tui.render(100).join("\n")).toContain("DEFAULT next");
  4686. await app.stop();
  4687. });
  4688. it("fails closed when the Runtime Plan capability cannot be loaded", async () => {
  4689. const runtime = createRuntime();
  4690. vi.mocked(runtime.getPlanModeCapabilities).mockRejectedValue(
  4691. new Error("Runtime unavailable"),
  4692. );
  4693. const terminal = new FakeTerminal();
  4694. const app = createTuiApp({
  4695. runtime,
  4696. terminal,
  4697. version: "0.1.0",
  4698. workspaceDir: "/workspace",
  4699. });
  4700. app.start();
  4701. await app.ready;
  4702. terminal.input?.("\x1b[Z");
  4703. await app.submit("/plan on");
  4704. expect(app.tui.render(100).join("\n")).not.toContain("PLAN next");
  4705. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4706. await app.stop();
  4707. });
  4708. it("submits the hidden Runtime engineering log command name as an ordinary prompt", async () => {
  4709. const terminal = new FakeTerminal();
  4710. const runtime = createRuntime();
  4711. const app = createTuiApp({
  4712. runtime,
  4713. terminal,
  4714. version: "0.1.0",
  4715. workspaceDir: "/workspace",
  4716. runtimeLogDirectory: "/home/dev/.minimax/v2/observability/logs",
  4717. });
  4718. await app.submit("/logs");
  4719. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4720. expect.objectContaining({ id: "session-1", content: "/logs" }),
  4721. expect.any(AbortSignal),
  4722. );
  4723. });
  4724. it("exposes sanitized checks and submits the hidden /config name as ordinary text", async () => {
  4725. const terminal = new FakeTerminal();
  4726. const runtime = createRuntime();
  4727. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  4728. {
  4729. requestId: "permission-1",
  4730. sessionId: "session-1",
  4731. toolName: "bash",
  4732. toolDescription: "Run tests",
  4733. },
  4734. ]);
  4735. const app = createTuiApp({
  4736. runtime,
  4737. terminal,
  4738. version: "0.1.0",
  4739. workspaceDir: "/workspace",
  4740. });
  4741. await app.submit("/doctor");
  4742. const doctorOutput = app.transcript.snapshot().at(-1)?.content ?? "";
  4743. expect(app.interaction.current()).toBeUndefined();
  4744. await app.submit("/config");
  4745. expect(app.interaction.current()).toBeUndefined();
  4746. await app.submit("/skills docs");
  4747. const skillsPanel = app.interaction.current();
  4748. const skillsOutput = skillsPanel?.render(80).join("\n") ?? "";
  4749. expect(app.tui.render(80).join("\n")).not.toContain("Message · Enter");
  4750. skillsPanel?.handleInput?.("\x1b");
  4751. await app.submit("/mcp browser");
  4752. const mcpPanel = app.interaction.current();
  4753. const mcpOutput = mcpPanel?.render(80).join("\n") ?? "";
  4754. expect(app.tui.render(80).join("\n")).not.toContain("Message · Enter");
  4755. mcpPanel?.handleInput?.("\x1b");
  4756. await app.submit("/permissions");
  4757. const output = app.transcript
  4758. .snapshot()
  4759. .map((cell) => cell.content)
  4760. .join("\n");
  4761. expect(runtime.getRuntimeDiagnostics).toHaveBeenCalledTimes(1);
  4762. expect(runtime.listSkills).toHaveBeenCalledWith("mavis", "docs");
  4763. expect(runtime.listMcpServers).toHaveBeenCalledWith("browser", "session-1");
  4764. expect(runtime.listPendingPermissions).toHaveBeenCalled();
  4765. expect(doctorOutput).toContain("Configuration check");
  4766. expect(doctorOutput).toContain("Status: Valid");
  4767. expect(doctorOutput).not.toContain("/doctor");
  4768. expect(output).toContain("Configuration check");
  4769. expect(output).not.toContain("Effective configuration");
  4770. expect(skillsOutput).toContain("Skills");
  4771. expect(skillsOutput).toContain("Built-in · 1");
  4772. expect(skillsOutput).toContain("Docs");
  4773. expect(skillsOutput).toContain("● available · builtin");
  4774. expect(mcpOutput).toContain("MCP servers");
  4775. expect(mcpOutput).toContain("browser");
  4776. expect(mcpOutput).toContain("◆ configured · stdio");
  4777. expect(output).toContain("bash · Run tests");
  4778. expect(output).not.toContain("TOKEN");
  4779. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  4780. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4781. expect.objectContaining({ id: "session-1", content: "/config" }),
  4782. expect.any(AbortSignal),
  4783. );
  4784. });
  4785. it("previews /feedback without uploading until Enter confirms the Runtime draft", async () => {
  4786. const terminal = new FakeTerminal();
  4787. terminal.rows = 30;
  4788. const runtime = createRuntime();
  4789. const app = createTuiApp({
  4790. runtime,
  4791. terminal,
  4792. version: "0.1.0",
  4793. workspaceDir: "/workspace",
  4794. });
  4795. app.start();
  4796. await app.ready;
  4797. await app.submit("/feedback Upload failed token=****");
  4798. expect(runtime.prepareFeedback).toHaveBeenCalledWith({
  4799. description: "Upload failed token=****",
  4800. });
  4801. expect(runtime.submitFeedback).not.toHaveBeenCalled();
  4802. expect(app.tui.hasOverlay()).toBe(false);
  4803. expect(app.interaction.isActive()).toBe(true);
  4804. const panel = app.interaction.current();
  4805. expect(panel?.render(80).join("\n")).toContain("Review feedback");
  4806. panel?.handleInput?.("d");
  4807. expect(panel?.render(80).join("\n")).toContain("Client mcode 0.1.0");
  4808. terminal.input?.("\r");
  4809. await vi.waitFor(() =>
  4810. expect(runtime.submitFeedback).toHaveBeenCalledWith(
  4811. "feedback-draft-1",
  4812. expect.objectContaining({ onPhase: expect.any(Function) }),
  4813. ),
  4814. );
  4815. expect(panel?.render(80).join("\n")).toContain("ticket-1");
  4816. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4817. terminal.input?.("\x1b");
  4818. expect(app.interaction.isActive()).toBe(false);
  4819. await app.stop();
  4820. });
  4821. it("cancels /feedback without uploading and keeps missing descriptions out of the Agent", async () => {
  4822. const terminal = new FakeTerminal();
  4823. const runtime = createRuntime();
  4824. const app = createTuiApp({
  4825. runtime,
  4826. terminal,
  4827. version: "0.1.0",
  4828. workspaceDir: "/workspace",
  4829. });
  4830. app.start();
  4831. await app.ready;
  4832. await app.submit("/feedback");
  4833. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  4834. kind: "final-summary",
  4835. content: "Usage: /feedback <message>",
  4836. });
  4837. expect(runtime.prepareFeedback).not.toHaveBeenCalled();
  4838. await app.submit("/feedback Cancel this report");
  4839. terminal.input?.("\x1b");
  4840. await vi.waitFor(() =>
  4841. expect(runtime.cancelFeedback).toHaveBeenCalledWith("feedback-draft-1"),
  4842. );
  4843. expect(runtime.submitFeedback).not.toHaveBeenCalled();
  4844. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4845. await app.stop();
  4846. });
  4847. it("keeps the status report local and submits the hidden /config name as text", async () => {
  4848. const terminal = new FakeTerminal();
  4849. terminal.rows = 24;
  4850. const runtime = createRuntime();
  4851. const app = createTuiApp({
  4852. runtime,
  4853. terminal,
  4854. version: "0.1.0",
  4855. workspaceDir: "/workspace",
  4856. });
  4857. app.start();
  4858. await app.ready;
  4859. const transcriptBeforeStatus = app.transcript.snapshot();
  4860. await app.submit("/status");
  4861. expect(app.tui.hasOverlay()).toBe(false);
  4862. expect(app.interaction.isActive()).toBe(true);
  4863. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  4864. const statusOutput = app.tui.render(80).join("\n");
  4865. expect(statusOutput).toContain("MCode status");
  4866. expect(statusOutput).toContain("Model");
  4867. expect(statusOutput).not.toContain("/status");
  4868. expect(statusOutput).toContain("/workspace");
  4869. expect(statusOutput).toMatch(/Branch:\s+Not a Git repository/u);
  4870. expect(statusOutput).toContain("Not applicable");
  4871. expect(statusOutput).toContain("Session");
  4872. expect(statusOutput).toContain("Permissions");
  4873. expect(statusOutput).toContain("Auto");
  4874. app.interaction.current()?.handleInput?.("\x1b");
  4875. expect(app.interaction.isActive()).toBe(false);
  4876. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  4877. await app.submit("/config");
  4878. expect(app.tui.hasOverlay()).toBe(false);
  4879. expect(app.interaction.isActive()).toBe(false);
  4880. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4881. expect.objectContaining({ id: "session-1", content: "/config" }),
  4882. expect.any(AbortSignal),
  4883. );
  4884. expect(runtime.getRuntimeDiagnostics).not.toHaveBeenCalled();
  4885. await app.stop();
  4886. });
  4887. it("commits the first frame immediately when the Pi renderer starts", async () => {
  4888. const terminal = new FakeTerminal();
  4889. const app = createTuiApp({
  4890. runtime: createRuntime(),
  4891. terminal,
  4892. version: "0.1.0",
  4893. workspaceDir: "/workspace",
  4894. });
  4895. let firstFrameCommitted = false;
  4896. void app.firstFrame.then(() => {
  4897. firstFrameCommitted = true;
  4898. });
  4899. app.start();
  4900. await app.firstFrame;
  4901. expect(terminal.started).toBe(true);
  4902. expect(firstFrameCommitted).toBe(true);
  4903. expect(terminal.writes.join("")).toContain("Tips for getting started");
  4904. await app.stop();
  4905. });
  4906. it("chooses the account region before routing login through the auth application", async () => {
  4907. const runtime = createRuntime();
  4908. const openedTargets: string[] = [];
  4909. const logoutUrl =
  4910. "https://agent.minimax.io/auth/logout?logout_redirect_uri=https%3A%2F%2Fagent.minimax.io";
  4911. let authenticated = false;
  4912. vi.mocked(runtime.getAccountStatus).mockImplementation(async () =>
  4913. authenticated
  4914. ? {
  4915. status: "ready",
  4916. defaultModel: "minimax/MiniMax-M2.7",
  4917. providerId: "minimax",
  4918. modelId: "MiniMax-M2.7",
  4919. authMode: "managed-login",
  4920. managedTokenPresent: true,
  4921. warnings: [],
  4922. }
  4923. : {
  4924. status: "needs-login",
  4925. authMode: "managed-login",
  4926. managedTokenPresent: false,
  4927. warnings: [],
  4928. },
  4929. );
  4930. const auth = {
  4931. login: vi.fn(
  4932. async (
  4933. onProgress?: (progress: McodeAuthProgress) => void,
  4934. _region?: "cn" | "en",
  4935. ) => {
  4936. authenticated = true;
  4937. onProgress?.({
  4938. state: "device-authorization",
  4939. userCode: "ABCD-EFGH",
  4940. verificationUri: "https://account.example.test/device",
  4941. expiresInSec: 300,
  4942. });
  4943. return {
  4944. state: "authenticated" as const,
  4945. message:
  4946. _region === "en"
  4947. ? "Signed in with MiniMax Global. Restart MCode to use this account region."
  4948. : "Signed in with MiniMax.",
  4949. };
  4950. },
  4951. ),
  4952. logout: vi.fn(async () => {
  4953. authenticated = false;
  4954. return {
  4955. state: "signed-out" as const,
  4956. message: "Signed out of MiniMax.",
  4957. logoutUrl,
  4958. };
  4959. }),
  4960. };
  4961. const notifyAuthContextChanged = vi.fn(async () => {
  4962. throw new Error("Hook lifecycle cleanup failed");
  4963. });
  4964. const app = createTuiApp({
  4965. runtime,
  4966. auth,
  4967. terminal: new FakeTerminal(),
  4968. version: "0.1.0",
  4969. workspaceDir: "/workspace",
  4970. openExternalTarget: async (target) => {
  4971. openedTargets.push(target);
  4972. throw new Error("no desktop session");
  4973. },
  4974. notifyAuthContextChanged,
  4975. });
  4976. app.start();
  4977. await app.ready;
  4978. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login");
  4979. await app.submit("/login");
  4980. expect(auth.login).not.toHaveBeenCalled();
  4981. expect(app.interaction.render(80).join("\n")).toContain("China (CN)");
  4982. expect(app.interaction.render(80).join("\n")).toContain("Global");
  4983. app.interaction.current()?.handleInput("\u001b[B");
  4984. app.interaction.current()?.handleInput("\r");
  4985. await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
  4986. await vi.waitFor(() =>
  4987. expect(app.controller.snapshot().account?.managedTokenPresent).toBe(true),
  4988. );
  4989. expect(app.getSurface()).toBe("conversation");
  4990. expect(app.tui.render(80).join("\n")).not.toContain("Sign in with /login");
  4991. expect(app.tui.render(80).join("\n")).not.toContain("Login required");
  4992. await app.submit("/logout");
  4993. await vi.waitFor(() =>
  4994. expect(app.controller.snapshot().account?.managedTokenPresent).toBe(
  4995. false,
  4996. ),
  4997. );
  4998. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login");
  4999. expect(auth.login).toHaveBeenCalledWith(expect.any(Function), "en");
  5000. expect(openedTargets).toEqual([
  5001. "https://account.example.test/device?client_surface=tui&download_source=mcode-internal",
  5002. logoutUrl,
  5003. ]);
  5004. await vi.waitFor(() =>
  5005. expect(app.transcript.snapshot()).toEqual(
  5006. expect.arrayContaining([
  5007. expect.objectContaining({
  5008. kind: "warning",
  5009. content:
  5010. "Couldn't open the default browser. Open the authorization URL above manually.",
  5011. }),
  5012. expect.objectContaining({
  5013. kind: "warning",
  5014. content:
  5015. "Couldn't open the default browser. Open the sign-out URL above manually.",
  5016. }),
  5017. ]),
  5018. ),
  5019. );
  5020. expect(app.transcript.snapshot().slice(-6)).toMatchObject([
  5021. {
  5022. kind: "final-summary",
  5023. content:
  5024. "Complete MiniMax login in your browser:\nhttps://account.example.test/device?client_surface=tui&download_source=mcode-internal\nCode: ABCD-EFGH",
  5025. },
  5026. {
  5027. kind: "warning",
  5028. content:
  5029. "Couldn't open the default browser. Open the authorization URL above manually.",
  5030. },
  5031. {
  5032. kind: "final-summary",
  5033. content:
  5034. "Signed in with MiniMax Global. Restart MCode to use this account region.",
  5035. },
  5036. {
  5037. kind: "final-summary",
  5038. content: "Signed out of MiniMax.",
  5039. },
  5040. {
  5041. kind: "final-summary",
  5042. content: `Finish signing out in your browser:\n${logoutUrl}`,
  5043. },
  5044. {
  5045. kind: "warning",
  5046. content:
  5047. "Couldn't open the default browser. Open the sign-out URL above manually.",
  5048. },
  5049. ]);
  5050. expect(auth.login).toHaveBeenCalledOnce();
  5051. expect(auth.logout).toHaveBeenCalledOnce();
  5052. expect(notifyAuthContextChanged.mock.calls).toEqual([
  5053. ["authenticated"],
  5054. ["logged_out"],
  5055. ]);
  5056. expect(
  5057. app.transcript
  5058. .snapshot()
  5059. .map((cell) => cell.content)
  5060. .join("\n"),
  5061. ).not.toContain("Sign-in wasn't completed");
  5062. expect(
  5063. app.transcript
  5064. .snapshot()
  5065. .map((cell) => cell.content)
  5066. .join("\n"),
  5067. ).not.toContain("Couldn't sign out");
  5068. expect(runtime.sendMessage).not.toHaveBeenCalled();
  5069. await app.stop();
  5070. });
  5071. it("clears Runtime auth context when the shared account is already signed out", async () => {
  5072. const notifyAuthContextChanged = vi.fn(async () => undefined);
  5073. const logoutUrl =
  5074. "https://agent.minimax.cn/auth/logout?logout_redirect_uri=https%3A%2F%2Fagent.minimax.cn";
  5075. const openExternalTarget = vi.fn(() => new Promise<void>(() => {}));
  5076. const app = createTuiApp({
  5077. runtime: createRuntime(),
  5078. auth: {
  5079. login: vi.fn(),
  5080. logout: vi.fn(async () => ({
  5081. state: "already-signed-out" as const,
  5082. message: "Already signed out of MiniMax.",
  5083. logoutUrl,
  5084. })),
  5085. },
  5086. terminal: new FakeTerminal(),
  5087. version: "0.1.0",
  5088. workspaceDir: "/workspace",
  5089. notifyAuthContextChanged,
  5090. openExternalTarget,
  5091. });
  5092. app.start();
  5093. await app.ready;
  5094. await app.submit("/logout");
  5095. expect(notifyAuthContextChanged).toHaveBeenCalledOnce();
  5096. expect(notifyAuthContextChanged).toHaveBeenCalledWith("logged_out");
  5097. expect(openExternalTarget).toHaveBeenCalledWith(logoutUrl);
  5098. expect(app.transcript.snapshot()).toEqual(
  5099. expect.arrayContaining([
  5100. expect.objectContaining({
  5101. content: `Finish signing out in your browser:\n${logoutUrl}`,
  5102. }),
  5103. ]),
  5104. );
  5105. await app.stop();
  5106. });
  5107. it("refreshes Runtime auth context when login renews an existing account", async () => {
  5108. const runtime = createRuntime();
  5109. let authenticated = false;
  5110. vi.mocked(runtime.getAccountStatus).mockImplementation(async () =>
  5111. authenticated
  5112. ? {
  5113. status: "ready",
  5114. defaultModel: "minimax/MiniMax-M2.7",
  5115. providerId: "minimax",
  5116. modelId: "MiniMax-M2.7",
  5117. authMode: "managed-login",
  5118. managedTokenPresent: true,
  5119. warnings: [],
  5120. }
  5121. : {
  5122. status: "needs-login",
  5123. authMode: "managed-login",
  5124. managedTokenPresent: false,
  5125. warnings: [],
  5126. },
  5127. );
  5128. const notifyAuthContextChanged = vi.fn(async () => undefined);
  5129. const auth = {
  5130. login: vi.fn(async () => {
  5131. authenticated = true;
  5132. return {
  5133. state: "already-authenticated" as const,
  5134. message: "Already signed in with MiniMax.",
  5135. };
  5136. }),
  5137. logout: vi.fn(async () => ({
  5138. state: "signed-out" as const,
  5139. message: "Signed out of MiniMax.",
  5140. })),
  5141. };
  5142. const app = createTuiApp({
  5143. runtime,
  5144. auth,
  5145. notifyAuthContextChanged,
  5146. terminal: new FakeTerminal(),
  5147. version: "0.1.0",
  5148. workspaceDir: "/workspace",
  5149. });
  5150. app.start();
  5151. await app.ready;
  5152. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login");
  5153. await app.submit("/login");
  5154. app.interaction.current()?.handleInput("\u001b[B");
  5155. app.interaction.current()?.handleInput("\r");
  5156. await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
  5157. expect(notifyAuthContextChanged).toHaveBeenCalledOnce();
  5158. expect(notifyAuthContextChanged).toHaveBeenCalledWith("authenticated");
  5159. await vi.waitFor(() =>
  5160. expect(app.controller.snapshot().account?.managedTokenPresent).toBe(true),
  5161. );
  5162. expect(app.getSurface()).toBe("conversation");
  5163. expect(app.tui.render(80).join("\n")).not.toContain("Sign in with /login");
  5164. expect(app.tui.render(80).join("\n")).not.toContain("Login required");
  5165. await app.stop();
  5166. });
  5167. it("exits immediately through /quit without aborting the shared Runtime turn", async () => {
  5168. const terminal = new FakeTerminal();
  5169. const runtime = createRuntime();
  5170. const abortSession = vi.spyOn(runtime, "abortSession");
  5171. const app = createTuiApp({
  5172. runtime,
  5173. terminal,
  5174. version: "0.1.0",
  5175. workspaceDir: "/workspace",
  5176. });
  5177. app.start();
  5178. await app.ready;
  5179. await app.submit("/quit");
  5180. await app.stopped;
  5181. expect(terminal.stopped).toBe(true);
  5182. expect(abortSession).not.toHaveBeenCalled();
  5183. });
  5184. it("does not restore /quit after reopening the exited Session", async () => {
  5185. const dataDir = await mkdtemp(join(tmpdir(), "mcode-quit-draft-"));
  5186. try {
  5187. const first = createTuiApp({
  5188. runtime: createRuntime(),
  5189. terminal: new FakeTerminal(),
  5190. version: "0.1.0",
  5191. dataDir,
  5192. workspaceDir: "/workspace",
  5193. });
  5194. await first.ready;
  5195. await first.openSession("session-1");
  5196. first.editor.setText("/quit");
  5197. first.editor.handleInput("\r");
  5198. await first.stopped;
  5199. const restored = createTuiApp({
  5200. runtime: createRuntime(),
  5201. terminal: new FakeTerminal(),
  5202. version: "0.1.0",
  5203. dataDir,
  5204. workspaceDir: "/workspace",
  5205. });
  5206. await restored.ready;
  5207. await restored.openSession("session-1");
  5208. expect(restored.editor.getText()).toBe("");
  5209. await restored.stop();
  5210. } finally {
  5211. await rm(dataDir, { recursive: true, force: true });
  5212. }
  5213. });
  5214. it("keeps warning status details visible until the local panel closes", async () => {
  5215. const terminal = new FakeTerminal();
  5216. terminal.rows = 40;
  5217. const runtime = createRuntime();
  5218. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  5219. status: "warning",
  5220. defaultModel: "minimax/MiniMax-M2.7",
  5221. providerId: "minimax",
  5222. modelId: "MiniMax-M2.7",
  5223. authMode: "managed-login",
  5224. managedTokenPresent: true,
  5225. warnings: ["Desktop login should be refreshed soon."],
  5226. });
  5227. const app = createTuiApp({
  5228. runtime,
  5229. terminal,
  5230. version: "0.1.0",
  5231. workspaceDir: "/workspace",
  5232. });
  5233. app.start();
  5234. await app.ready;
  5235. const transcriptBeforeStatus = app.transcript.snapshot();
  5236. await app.submit("/status");
  5237. const rendered = app.tui.render(80).join("\n");
  5238. expect(app.interaction.current()).toBeDefined();
  5239. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  5240. expect(rendered).toContain("Needs attention");
  5241. expect(rendered).toContain("Connected with warnings");
  5242. expect(rendered).toContain("Model");
  5243. expect(rendered).toContain("Desktop login should be refreshed");
  5244. expect(rendered).toContain("soon.");
  5245. app.interaction.current()?.handleInput?.("\x1b");
  5246. expect(app.interaction.current()).toBeUndefined();
  5247. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  5248. expect(app.tui.render(80).join("\n")).not.toContain(
  5249. "Desktop login should be refreshed",
  5250. );
  5251. await app.stop();
  5252. });
  5253. it("reports doctor failures and submits the hidden /config name as text", async () => {
  5254. const runtime = createRuntime();
  5255. vi.mocked(runtime.getRuntimeDiagnostics).mockRejectedValue(
  5256. new Error("Diagnostics unavailable"),
  5257. );
  5258. const app = createTuiApp({
  5259. runtime,
  5260. terminal: new FakeTerminal(),
  5261. version: "0.1.0",
  5262. workspaceDir: "/workspace",
  5263. });
  5264. await app.submit("/doctor");
  5265. expect(app.tui.hasOverlay()).toBe(false);
  5266. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  5267. kind: "error",
  5268. content:
  5269. "Couldn't load configuration check: Diagnostics unavailable. Retry.",
  5270. });
  5271. await app.submit("/config");
  5272. expect(app.tui.hasOverlay()).toBe(false);
  5273. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5274. expect.objectContaining({ id: "session-1", content: "/config" }),
  5275. expect.any(AbortSignal),
  5276. );
  5277. expect(runtime.getRuntimeDiagnostics).toHaveBeenCalledTimes(1);
  5278. });
  5279. it("lets an async Session card replace a local status panel", async () => {
  5280. const terminal = new FakeTerminal();
  5281. const runtime = createRuntime();
  5282. let resolveSessionPage:
  5283. | ((page: {
  5284. sessions: Array<{
  5285. sessionId: string;
  5286. title: string;
  5287. workspaceDir: string;
  5288. updatedAt: number;
  5289. }>;
  5290. hasMore: boolean;
  5291. }) => void)
  5292. | undefined;
  5293. vi.mocked(runtime.listSessionPage).mockImplementationOnce(
  5294. async () =>
  5295. await new Promise((resolve) => {
  5296. resolveSessionPage = resolve;
  5297. }),
  5298. );
  5299. const app = createTuiApp({
  5300. runtime,
  5301. terminal,
  5302. version: "0.1.0",
  5303. workspaceDir: "/workspace",
  5304. });
  5305. await app.ready;
  5306. const transcriptBeforeStatus = app.transcript.snapshot();
  5307. const sessionCard = app.submit("/sessions");
  5308. await vi.waitFor(() =>
  5309. expect(runtime.listSessionPage).toHaveBeenCalledOnce(),
  5310. );
  5311. await app.submit("/status");
  5312. expect(app.tui.hasOverlay()).toBe(false);
  5313. expect(app.interaction.isActive()).toBe(true);
  5314. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  5315. expect(app.tui.render(80).join("\n")).toContain("MCode status");
  5316. resolveSessionPage?.({
  5317. sessions: [
  5318. {
  5319. sessionId: "session-race",
  5320. title: "Session opened after status",
  5321. workspaceDir: "/workspace",
  5322. updatedAt: Date.now(),
  5323. },
  5324. ],
  5325. hasMore: false,
  5326. });
  5327. await sessionCard;
  5328. expect(app.tui.hasOverlay()).toBe(false);
  5329. expect(app.interaction.isActive()).toBe(true);
  5330. app.interaction.current()?.handleInput?.("\x03");
  5331. expect(runtime.getSession).not.toHaveBeenCalled();
  5332. expect(app.interaction.isActive()).toBe(false);
  5333. expect(app.tui.hasOverlay()).toBe(false);
  5334. await app.stop();
  5335. });
  5336. it("keeps unsupported standalone MCP inspection concise and recoverable", async () => {
  5337. const runtime = createRuntime();
  5338. vi.mocked(runtime.listMcpServers).mockRejectedValue(
  5339. Object.assign(new Error("DesktopService implementation detail"), {
  5340. status: 501,
  5341. code: "NOT_IMPLEMENTED",
  5342. }),
  5343. );
  5344. const app = createTuiApp({
  5345. runtime,
  5346. terminal: new FakeTerminal(),
  5347. version: "0.1.0",
  5348. workspaceDir: "/workspace",
  5349. });
  5350. await app.submit("/mcp");
  5351. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  5352. kind: "warning",
  5353. content:
  5354. "MCP status is not available in this build. Configured MCP tools remain available.",
  5355. });
  5356. });
  5357. it("registers enabled Skills as discoverable slash commands without shadowing built-ins", async () => {
  5358. const terminal = new FakeTerminal();
  5359. const runtime = createRuntime();
  5360. vi.mocked(runtime.listSkills).mockResolvedValue({
  5361. skills: [
  5362. {
  5363. name: "docs",
  5364. displayName: "Docs",
  5365. description: "Read project docs",
  5366. enabled: true,
  5367. sourceKind: "builtin",
  5368. },
  5369. {
  5370. name: "disabled-skill",
  5371. enabled: false,
  5372. },
  5373. {
  5374. name: "help",
  5375. enabled: true,
  5376. },
  5377. ...Array.from({ length: 14 }, (_, index) => ({
  5378. name: `skill-${index}`,
  5379. description: `Generated skill ${index}`,
  5380. enabled: true,
  5381. })),
  5382. ],
  5383. hasMore: false,
  5384. });
  5385. const app = createTuiApp({
  5386. runtime,
  5387. terminal,
  5388. version: "0.1.0",
  5389. workspaceDir: "/workspace",
  5390. });
  5391. app.start();
  5392. await app.ready;
  5393. app.editor.setText("/docs summarize this repository");
  5394. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5395. "Skill · instructions · Enter invoke",
  5396. );
  5397. app.editor.setText("/context");
  5398. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5399. "Command · Enter run",
  5400. );
  5401. app.editor.setText("/context explain this repository");
  5402. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5403. "Prompt · Enter send",
  5404. );
  5405. app.editor.setText("/stop");
  5406. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5407. "Command · Enter run",
  5408. );
  5409. app.editor.setText("/config");
  5410. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5411. "Prompt · Enter send",
  5412. );
  5413. app.editor.setText("");
  5414. await app.submit("/help");
  5415. expect(app.transcript.snapshot()).toEqual([]);
  5416. expect(app.tui.hasOverlay()).toBe(false);
  5417. expect(app.interaction.isActive()).toBe(true);
  5418. for (const character of "docs") terminal.input?.(character);
  5419. terminal.input?.("\r");
  5420. expect(app.tui.hasOverlay()).toBe(false);
  5421. expect(app.interaction.isActive()).toBe(false);
  5422. expect(app.editor.getText()).toBe("");
  5423. await app.submit("/docs summarize this repository");
  5424. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5425. expect.objectContaining({
  5426. id: "session-1",
  5427. content: "/docs summarize this repository",
  5428. }),
  5429. expect.any(AbortSignal),
  5430. );
  5431. vi.mocked(runtime.sendMessage).mockClear();
  5432. await app.submit("/disabled-skill");
  5433. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5434. expect.objectContaining({ id: "session-1", content: "/disabled-skill" }),
  5435. expect.any(AbortSignal),
  5436. );
  5437. await app.stop();
  5438. });
  5439. it("deduplicates configured Skills case-insensitively and reserves built-in names", async () => {
  5440. const terminal = new FakeTerminal();
  5441. const runtime = createRuntime();
  5442. vi.mocked(runtime.listSkills).mockResolvedValue({
  5443. skills: [
  5444. {
  5445. name: "HELP",
  5446. description: "A Skill that must not shadow /help",
  5447. enabled: true,
  5448. },
  5449. {
  5450. name: "Docs",
  5451. description: "Read project docs",
  5452. enabled: true,
  5453. },
  5454. {
  5455. name: "docs",
  5456. description: "Duplicate project docs command",
  5457. enabled: true,
  5458. },
  5459. ],
  5460. hasMore: false,
  5461. });
  5462. const app = createTuiApp({
  5463. runtime,
  5464. terminal,
  5465. version: "0.1.0",
  5466. workspaceDir: "/workspace",
  5467. });
  5468. app.start();
  5469. await app.ready;
  5470. await app.submit("/help");
  5471. const helpPanel = app.interaction.current();
  5472. expect(helpPanel).toBeDefined();
  5473. helpPanel?.handleInput?.("\x1b");
  5474. await app.submit("/help [arguments]");
  5475. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5476. expect.objectContaining({
  5477. id: "session-1",
  5478. content: "/help [arguments]",
  5479. }),
  5480. expect.any(AbortSignal),
  5481. );
  5482. vi.mocked(runtime.sendMessage).mockClear();
  5483. await app.submit("/docs explain this repository");
  5484. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5485. expect.objectContaining({
  5486. id: "session-1",
  5487. content: "/docs explain this repository",
  5488. }),
  5489. expect.any(AbortSignal),
  5490. );
  5491. await app.stop();
  5492. });
  5493. it("uses public Runtime owners for Session inspection commands", async () => {
  5494. const terminal = new FakeTerminal();
  5495. terminal.rows = 40;
  5496. const runtime = createRuntime();
  5497. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  5498. status: "ready",
  5499. defaultModel: "minimax/MiniMax-M3",
  5500. providerId: "minimax-cn-coding-plan",
  5501. authMode: "managed-login",
  5502. managedTokenPresent: true,
  5503. modelSource: "token-plan",
  5504. tokenPlanQuotaState: "available",
  5505. tokenPlanSummary: { tier: "Ultra Plan", creditBalance: "0" },
  5506. tokenPlanQuota: {
  5507. fiveHour: { remainingPercent: 100, unlimited: false },
  5508. weekly: { remainingPercent: 99, unlimited: false },
  5509. video: { remainingCount: 5, totalCount: 5, unlimited: false },
  5510. },
  5511. warnings: [],
  5512. });
  5513. const app = createTuiApp({
  5514. runtime,
  5515. terminal,
  5516. version: "0.1.0",
  5517. workspaceDir: "/workspace",
  5518. });
  5519. await app.submit("Create a session");
  5520. vi.mocked(runtime.sendMessage).mockClear();
  5521. vi.mocked(runtime.getSessionUsage).mockClear();
  5522. vi.mocked(runtime.getContextSnapshot).mockResolvedValueOnce({
  5523. status: "live",
  5524. contextUsage: {
  5525. contextWindowTokens: 10_000,
  5526. usedTokens: 3_000,
  5527. totalCountSource: "PROVIDER_USAGE_ANCHORED",
  5528. components: [],
  5529. },
  5530. });
  5531. const transcriptBeforeUsage = app.transcript.snapshot();
  5532. await app.submit("/usage");
  5533. const usageOutput = app.tui.render(80).join("\n");
  5534. expect(app.interaction.current()).toBeDefined();
  5535. expect(app.transcript.snapshot()).toEqual(transcriptBeforeUsage);
  5536. expect(usageOutput).toContain("Usage");
  5537. expect(usageOutput).toContain("120 total");
  5538. expect(usageOutput).toContain("30% used · 70% free");
  5539. expect(usageOutput).toContain("Ultra Plan");
  5540. expect(usageOutput).toContain("100% left");
  5541. app.interaction.current()?.handleInput?.("\x1b");
  5542. expect(app.interaction.current()).toBeUndefined();
  5543. expect(app.transcript.snapshot()).toEqual(transcriptBeforeUsage);
  5544. await app.submit("/compact keep test evidence");
  5545. expect(runtime.getSessionUsage).toHaveBeenCalledWith("session-1");
  5546. expect(runtime.getContextSnapshot).toHaveBeenCalledWith("session-1");
  5547. expect(runtime.getAccountStatus).toHaveBeenCalledWith("session-1", {
  5548. includeMembership: true,
  5549. forceRefresh: true,
  5550. });
  5551. expect(runtime.requestCompaction).toHaveBeenCalledWith(
  5552. "session-1",
  5553. "mavis",
  5554. "keep test evidence",
  5555. );
  5556. expect(runtime.sendMessage).not.toHaveBeenCalled();
  5557. const output = app.transcript
  5558. .snapshot()
  5559. .map((cell) => cell.content)
  5560. .join("\n");
  5561. expect(output).not.toContain("Session usage");
  5562. expect(output).not.toMatch(
  5563. /Turns|Total tokens|Cost|Reasoning|Cache|Runtime|source|compaction|snapshot/i,
  5564. );
  5565. expect(output).not.toContain("Compaction completed");
  5566. expect(output).not.toContain("4,000 → 1,200 tokens");
  5567. expect(output).not.toContain("compact-1");
  5568. });
  5569. it("shows compaction as live activity until the Runtime request settles", async () => {
  5570. const runtime = createRuntime();
  5571. let resolveCompaction:
  5572. | ((result: {
  5573. success: true;
  5574. sessionId: string;
  5575. compactionId: string;
  5576. }) => void)
  5577. | undefined;
  5578. vi.mocked(runtime.requestCompaction).mockImplementationOnce(
  5579. async () =>
  5580. await new Promise((resolve) => {
  5581. resolveCompaction = resolve;
  5582. }),
  5583. );
  5584. const app = createTuiApp({
  5585. runtime,
  5586. terminal: new FakeTerminal(),
  5587. version: "0.1.0",
  5588. workspaceDir: "/workspace",
  5589. });
  5590. await app.submit("Create a session");
  5591. const pending = app.submit("/compact keep decisions");
  5592. await vi.waitFor(() =>
  5593. expect(app.tui.render(80).join("\n")).toContain("Compacting context"),
  5594. );
  5595. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
  5596. resolveCompaction?.({
  5597. success: true,
  5598. sessionId: "session-1",
  5599. compactionId: "compact-1",
  5600. });
  5601. await pending;
  5602. expect(app.tui.render(80).join("\n")).not.toContain("Compacting context");
  5603. });
  5604. it("treats Runtime NOTHING_TO_COMPACT as a recoverable Session state", async () => {
  5605. const runtime = createRuntime();
  5606. vi.mocked(runtime.requestCompaction).mockRejectedValue(
  5607. Object.assign(new Error("HTTP 400 implementation detail"), {
  5608. status: 400,
  5609. code: "NOTHING_TO_COMPACT",
  5610. }),
  5611. );
  5612. const app = createTuiApp({
  5613. runtime,
  5614. terminal: new FakeTerminal(),
  5615. version: "0.1.0",
  5616. workspaceDir: "/workspace",
  5617. });
  5618. await app.submit("Create a session");
  5619. await app.submit("/compact");
  5620. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  5621. kind: "final-summary",
  5622. content: "No compaction is needed for this conversation yet.",
  5623. });
  5624. });
  5625. it("shows account usage before a Session exists and keeps Session-only inspection recoverable", async () => {
  5626. const runtime = createRuntime();
  5627. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  5628. status: "ready",
  5629. authMode: "byok",
  5630. managedTokenPresent: false,
  5631. modelSource: "byok",
  5632. tokenPlanQuotaState: "available",
  5633. tokenPlanSummary: { tier: "Pro Plan" },
  5634. tokenPlanQuota: {
  5635. fiveHour: { remainingPercent: 75, unlimited: false },
  5636. weekly: { remainingPercent: 50, unlimited: false },
  5637. },
  5638. warnings: [],
  5639. });
  5640. const terminal = new FakeTerminal();
  5641. terminal.rows = 40;
  5642. const app = createTuiApp({
  5643. runtime,
  5644. terminal,
  5645. version: "0.1.0",
  5646. workspaceDir: "/workspace",
  5647. });
  5648. await app.submit("/usage");
  5649. const usageOutput = app.tui.render(80).join("\n");
  5650. expect(app.interaction.current()).toBeDefined();
  5651. expect(app.transcript.snapshot()).toEqual([]);
  5652. expect(usageOutput).toContain("Usage");
  5653. expect(usageOutput).toContain("Account only");
  5654. expect(usageOutput).toContain("Pro Plan");
  5655. expect(usageOutput).toContain("75% left");
  5656. app.interaction.current()?.handleInput?.("\x1b");
  5657. expect(app.interaction.current()).toBeUndefined();
  5658. expect(app.transcript.snapshot()).toEqual([]);
  5659. await app.submit("/compact");
  5660. expect(runtime.getSessionUsage).not.toHaveBeenCalled();
  5661. expect(runtime.getContextSnapshot).not.toHaveBeenCalled();
  5662. expect(runtime.getAccountStatus).toHaveBeenCalledWith(undefined, {
  5663. includeMembership: true,
  5664. forceRefresh: true,
  5665. });
  5666. expect(app.transcript.snapshot()).toEqual([]);
  5667. expect(app.tui.render(80).join("\n")).toContain(
  5668. "Start or resume a Session before compacting it.",
  5669. );
  5670. });
  5671. it("keeps prompt history and long bracketed paste intact in the Composer", async () => {
  5672. const terminal = new FakeTerminal();
  5673. const runtime = createRuntime();
  5674. const app = createTuiApp({
  5675. runtime,
  5676. terminal,
  5677. version: "0.1.0",
  5678. workspaceDir: "/workspace",
  5679. });
  5680. app.start();
  5681. await app.ready;
  5682. terminal.input?.("first prompt");
  5683. terminal.input?.("\r");
  5684. await vi.waitFor(() =>
  5685. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  5686. );
  5687. terminal.input?.("second prompt");
  5688. terminal.input?.("\r");
  5689. await vi.waitFor(() =>
  5690. expect(runtime.sendMessage).toHaveBeenCalledTimes(2),
  5691. );
  5692. terminal.input?.("\x1b[A");
  5693. expect(app.editor.getText()).toBe("second prompt");
  5694. terminal.input?.("\x1b[A");
  5695. expect(app.editor.getText()).toBe("first prompt");
  5696. terminal.input?.("\x1b[B");
  5697. expect(app.editor.getText()).toBe("second prompt");
  5698. app.editor.setText("");
  5699. const pasted = `Explain this payload:\n${"x".repeat(1_200)}`;
  5700. terminal.input?.(`\x1b[200~${pasted}\x1b[201~`);
  5701. expect(app.editor.getText()).toContain("[paste #");
  5702. expect(app.editor.getExpandedText()).toBe(pasted);
  5703. terminal.input?.("\r");
  5704. await vi.waitFor(() =>
  5705. expect(runtime.sendMessage).toHaveBeenCalledTimes(3),
  5706. );
  5707. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  5708. expect.objectContaining({ id: "session-1", content: pasted }),
  5709. expect.any(AbortSignal),
  5710. );
  5711. await app.stop();
  5712. });
  5713. it("trusts bracketed paste and submits dense typed input without a false newline", async () => {
  5714. const terminal = new FakeTerminal();
  5715. Object.defineProperty(terminal, "capabilities", {
  5716. value: {
  5717. terminalId: "unknown",
  5718. platform: "linux",
  5719. isTTY: true,
  5720. transport: "local",
  5721. multiplexer: "none",
  5722. color: true,
  5723. colorLevel: 3,
  5724. } satisfies TerminalCapabilities,
  5725. });
  5726. const runtime = createRuntime();
  5727. const app = createTuiApp({
  5728. runtime,
  5729. terminal,
  5730. version: "0.1.0",
  5731. workspaceDir: "/workspace",
  5732. });
  5733. app.start();
  5734. await app.ready;
  5735. for (const character of "abcdefgh") terminal.input?.(character);
  5736. terminal.input?.("\r");
  5737. await vi.waitFor(() =>
  5738. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  5739. );
  5740. expect(app.editor.getText()).toBe("");
  5741. await app.stop();
  5742. });
  5743. it("projects an otty image paste as an inline editor placeholder", async () => {
  5744. const terminal = new FakeTerminal();
  5745. const resolveAttachment = vi.fn(async () => ({
  5746. type: "image" as const,
  5747. filePath: "/tmp/otty-paste/image-123.png",
  5748. fileName: "image-123.png",
  5749. mimeType: "image/png",
  5750. sizeBytes: 1_024,
  5751. }));
  5752. const app = createTuiApp({
  5753. runtime: createRuntime(),
  5754. terminal,
  5755. version: "0.1.0",
  5756. workspaceDir: "/workspace",
  5757. resolveAttachment,
  5758. });
  5759. app.start();
  5760. await app.ready;
  5761. terminal.input?.("\x1b[200~/tmp/otty-paste/image-123.png\x1b[201~");
  5762. await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledTimes(1));
  5763. const rendered = app.tui.render(80).join("\n");
  5764. expect(app.editor.getText()).toBe("[Image #1] ");
  5765. expect(rendered).toContain("[Image #1]");
  5766. expect(rendered).not.toContain("/tmp/otty-paste/");
  5767. await app.stop();
  5768. });
  5769. it.each(["regular", "fullscreen"] as const)(
  5770. "keeps image preview controls separate from Enter submission in %s mode",
  5771. async (tuiMode) => {
  5772. const terminal = new FakeTerminal();
  5773. terminal.rows = 40;
  5774. const runtime = createRuntime();
  5775. const app = createTuiApp({
  5776. runtime,
  5777. terminal,
  5778. tuiMode,
  5779. version: "0.1.0",
  5780. workspaceDir: "/workspace",
  5781. resolveAttachment: async () => ({
  5782. type: "image",
  5783. filePath: "/tmp/image-preview-missing.png",
  5784. fileName: "preview.png",
  5785. mimeType: "image/png",
  5786. sizeBytes: 32768,
  5787. }),
  5788. });
  5789. app.start();
  5790. await app.ready;
  5791. terminal.input?.("\x1b[200~/tmp/image-preview-missing.png\x1b[201~");
  5792. await vi.waitFor(() =>
  5793. expect(app.editor.getAttachmentPreview()?.id).toBe(
  5794. "/tmp/image-preview-missing.png",
  5795. ),
  5796. );
  5797. expect(app.editor.getText()).toBe("[Image #1] ");
  5798. expect(app.tui.render(80).join("\n")).toContain("preview.png");
  5799. expect(app.tui.render(80).join("\n")).toContain("32 KB");
  5800. expect(app.tui.render(80).join("\n")).not.toMatch(/Option\+I|Alt\+I/);
  5801. expect(runtime.sendMessage).not.toHaveBeenCalled();
  5802. terminal.input?.("\x1b");
  5803. expect(app.editor.getAttachmentPreview()).toBeUndefined();
  5804. terminal.input?.("\x1b[D");
  5805. expect(app.editor.getAttachmentPreview()?.id).toBe(
  5806. "/tmp/image-preview-missing.png",
  5807. );
  5808. terminal.input?.("\r");
  5809. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalled());
  5810. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5811. expect.objectContaining({
  5812. content: "",
  5813. attachments: [
  5814. expect.objectContaining({
  5815. local: { filePath: "/tmp/image-preview-missing.png" },
  5816. }),
  5817. ],
  5818. }),
  5819. expect.any(AbortSignal),
  5820. );
  5821. expect(app.editor.getAttachmentPreview()).toBeUndefined();
  5822. await app.stop();
  5823. },
  5824. );
  5825. it("projects a pasted absolute WeChat image path as a short inline placeholder", async () => {
  5826. const terminal = new FakeTerminal();
  5827. const runtime = createRuntime();
  5828. const wechatImagePath =
  5829. "D:\\Yingyong\\social\\wechat\\xwechat_files\\wxid_demo\\temp\\RWTemp\\2026-08\\3336519cd4d5351f4bc5a5a68c7fea75.png";
  5830. const resolveAttachment = vi.fn(async () => ({
  5831. type: "image" as const,
  5832. filePath: wechatImagePath,
  5833. fileName: "3336519cd4d5351f4bc5a5a68c7fea75.png",
  5834. mimeType: "image/png",
  5835. sizeBytes: 1_024,
  5836. }));
  5837. const app = createTuiApp({
  5838. runtime,
  5839. terminal,
  5840. version: "0.1.0",
  5841. workspaceDir: "D:\\workspace",
  5842. resolveAttachment,
  5843. });
  5844. app.start();
  5845. await app.ready;
  5846. terminal.input?.(`\x1b[200~'${wechatImagePath}'\x1b[201~`);
  5847. await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledOnce());
  5848. expect(resolveAttachment).toHaveBeenCalledWith(`'${wechatImagePath}'`, {
  5849. source: "terminal-paste",
  5850. workspaceDir: "D:\\workspace",
  5851. });
  5852. expect(app.editor.getText()).toBe("[Image #1] ");
  5853. expect(app.tui.render(80).join("\n")).not.toContain("xwechat_files");
  5854. await app.submit("Inspect this image");
  5855. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5856. expect.objectContaining({
  5857. content: "Inspect this image",
  5858. attachments: [
  5859. expect.objectContaining({
  5860. local: { filePath: wechatImagePath },
  5861. }),
  5862. ],
  5863. }),
  5864. expect.any(AbortSignal),
  5865. );
  5866. await app.stop();
  5867. });
  5868. it("keeps an image placeholder visible before a long CJK prompt", async () => {
  5869. const terminal = new FakeTerminal();
  5870. const resolveAttachment = vi.fn(async () => ({
  5871. type: "image" as const,
  5872. filePath: "/tmp/otty-paste/logo.png",
  5873. fileName: "logo.png",
  5874. mimeType: "image/png",
  5875. sizeBytes: 1_024,
  5876. }));
  5877. const app = createTuiApp({
  5878. runtime: createRuntime(),
  5879. terminal,
  5880. version: "0.1.0",
  5881. workspaceDir: "/workspace",
  5882. resolveAttachment,
  5883. });
  5884. app.start();
  5885. await app.ready;
  5886. terminal.input?.("\x1b[200~/tmp/otty-paste/logo.png\x1b[201~");
  5887. await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledTimes(1));
  5888. app.editor.insertTextAtCursor(
  5889. "logo 不太对还是,还出现了奇怪的--; logo你自己截取把:",
  5890. );
  5891. const rendered = app.tui.render(80).join("\n");
  5892. expect(rendered).toContain("[Image #1]");
  5893. await app.stop();
  5894. });
  5895. it("removes an inline image placeholder and its attachment with Backspace", async () => {
  5896. const terminal = new FakeTerminal();
  5897. const resolveAttachment = vi.fn(async () => ({
  5898. type: "image" as const,
  5899. filePath: "/tmp/otty-paste/image-123.png",
  5900. fileName: "image-123.png",
  5901. mimeType: "image/png",
  5902. sizeBytes: 1_024,
  5903. }));
  5904. const app = createTuiApp({
  5905. runtime: createRuntime(),
  5906. terminal,
  5907. version: "0.1.0",
  5908. workspaceDir: "/workspace",
  5909. resolveAttachment,
  5910. });
  5911. app.start();
  5912. await app.ready;
  5913. app.editor.setText("first line\nsecond line");
  5914. terminal.input?.("\x1b[200~/tmp/otty-paste/image-123.png\x1b[201~");
  5915. await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledTimes(1));
  5916. expect(app.editor.getText()).toBe("first line\nsecond line [Image #1] ");
  5917. expect(app.tui.render(80).join("\n")).toContain("[Image #1]");
  5918. terminal.input?.("\x7f");
  5919. await vi.waitFor(() =>
  5920. expect(app.editor.getText().trimEnd()).toBe("first line\nsecond line"),
  5921. );
  5922. expect(app.tui.render(80).join("\n")).not.toContain("[Image #1]");
  5923. await app.stop();
  5924. });
  5925. it("resumes Desktop history, supports rename, and executes the files-unchanged fork flow", async () => {
  5926. const terminal = new FakeTerminal();
  5927. const runtime = createRuntime();
  5928. vi.mocked(runtime.listSessions).mockResolvedValue([
  5929. {
  5930. sessionId: "session-existing",
  5931. title: "Existing session",
  5932. workspaceDir: "/workspace",
  5933. updatedAt: 200,
  5934. },
  5935. ]);
  5936. const history = [
  5937. {
  5938. id: "msg-user-v1-fork-source",
  5939. turnId: "turn-history",
  5940. role: "user" as const,
  5941. content: "Try the original approach",
  5942. timestamp: 90,
  5943. },
  5944. {
  5945. id: "assistant-fork-source",
  5946. turnId: "turn-history",
  5947. role: "assistant" as const,
  5948. content: "Recovered answer",
  5949. timestamp: 100,
  5950. actions: { fork: true },
  5951. },
  5952. ];
  5953. const forkRuntime = runtime as TuiRuntime & TuiSessionForkPort;
  5954. vi.mocked(runtime.getMessages).mockResolvedValue(history);
  5955. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  5956. messages: history,
  5957. hasMore: false,
  5958. });
  5959. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  5960. sessionId === "session-fork"
  5961. ? {
  5962. sessionId,
  5963. parentSessionId: "session-existing",
  5964. title: "Existing session (fork 1)",
  5965. workspaceDir: "/workspace",
  5966. }
  5967. : {
  5968. sessionId,
  5969. title: "Existing session",
  5970. workspaceDir: "/workspace",
  5971. },
  5972. );
  5973. vi.mocked(forkRuntime.getSessionForkOptions).mockResolvedValue({
  5974. canFork: true,
  5975. suggestedTitle: "Existing session (fork 1)",
  5976. worktreeVisible: false,
  5977. worktreeEligible: false,
  5978. });
  5979. vi.mocked(forkRuntime.forkSession).mockResolvedValue({
  5980. session: {
  5981. sessionId: "session-fork",
  5982. parentSessionId: "session-existing",
  5983. title: "Existing session (fork 1)",
  5984. workspaceDir: "/workspace",
  5985. },
  5986. });
  5987. const app = createTuiApp({
  5988. runtime,
  5989. terminal,
  5990. version: "0.1.0",
  5991. workspaceDir: "/workspace",
  5992. });
  5993. app.start();
  5994. await app.ready;
  5995. await app.submit("/sessions");
  5996. expect(app.tui.hasOverlay()).toBe(false);
  5997. expect(app.interaction.isActive()).toBe(true);
  5998. app.interaction.current()?.handleInput?.("\x1b");
  5999. expect(app.interaction.isActive()).toBe(false);
  6000. await app.submit("/resume 1");
  6001. expect(app.getSurface()).toBe("conversation");
  6002. vi.mocked(runtime.renameSession).mockClear();
  6003. await app.submit("/rename");
  6004. expect(runtime.renameSession).not.toHaveBeenCalled();
  6005. expect(app.interaction.isActive()).toBe(true);
  6006. expect(app.tui.render(100).join("\n")).toContain(
  6007. "Sessions / Rename session",
  6008. );
  6009. app.interaction.current()?.handleInput?.("\x1b");
  6010. expect(app.tui.render(100).join("\n")).toContain("Sessions");
  6011. app.interaction.current()?.handleInput?.("\x1b");
  6012. expect(app.interaction.isActive()).toBe(false);
  6013. await app.submit("/rename Renamed session");
  6014. vi.mocked(runtime.createSession).mockClear();
  6015. await app.submit("/fork");
  6016. await vi.waitFor(() =>
  6017. expect(runtime.listSessionInputSummaries).toHaveBeenCalledWith(
  6018. "session-existing",
  6019. {
  6020. limit: 100,
  6021. },
  6022. ),
  6023. );
  6024. // The new fork flow owns the surface with the history picker, not the
  6025. // generic transcript panel.
  6026. expect(renderTerminalViewport(app, terminal)).toContain(
  6027. "Fork from a previous message",
  6028. );
  6029. expect(renderTerminalViewport(app, terminal)).not.toContain("Transcript");
  6030. // Esc cancels without calling the fork Runtime API.
  6031. const beforeForkCalls = vi.mocked(runtime.forkSession).mock.calls.length;
  6032. app.surfaceHost.popFeature();
  6033. expect(vi.mocked(runtime.forkSession).mock.calls.length).toBe(
  6034. beforeForkCalls,
  6035. );
  6036. const transcriptBeforeStatus = app.transcript.snapshot();
  6037. await app.submit("/status");
  6038. expect(runtime.getSession).toHaveBeenCalledWith("session-existing");
  6039. expect(app.interaction.current()).toBeDefined();
  6040. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  6041. expect(app.tui.render(100).join("\n")).toContain("MCode status");
  6042. expect(runtime.renameSession).toHaveBeenCalledWith(
  6043. "session-existing",
  6044. "Renamed session",
  6045. );
  6046. expect(runtime.createSession).not.toHaveBeenCalled();
  6047. expect(app.transcript.snapshot()).not.toEqual(
  6048. expect.arrayContaining([
  6049. expect.objectContaining({ content: "Unknown command. Use /help." }),
  6050. ]),
  6051. );
  6052. app.interaction.current()?.handleInput?.("\x1b");
  6053. await app.stop();
  6054. });
  6055. it.each(["regular", "fullscreen"] as const)(
  6056. "presents /history in %s mode and returns to chat on cancel",
  6057. async (tuiMode) => {
  6058. const terminal = new FakeTerminal();
  6059. const runtime = createRuntime();
  6060. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6061. {
  6062. userMessageId: "msg-user-history",
  6063. assistantMessageId: "msg-assistant-history",
  6064. contentHead: "Inspect the Session UI",
  6065. timestamp: 1_700_000_000_000,
  6066. fileChangeCount: 1,
  6067. },
  6068. ]);
  6069. const app = createTuiApp({
  6070. runtime,
  6071. terminal,
  6072. version: "0.1.0",
  6073. workspaceDir: "/workspace",
  6074. tuiMode,
  6075. });
  6076. app.start();
  6077. await app.ready;
  6078. await app.submit("Seed the session");
  6079. await app.submit("/history");
  6080. await vi.waitFor(() =>
  6081. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6082. kind: "feature",
  6083. id: "session-history:explorer",
  6084. }),
  6085. );
  6086. expect(renderTerminalViewport(app, terminal)).toContain(
  6087. "Inspect the Session UI",
  6088. );
  6089. expect(renderTerminalViewport(app, terminal)).toContain("Search:");
  6090. expect(renderTerminalViewport(app, terminal)).toContain("Enter actions");
  6091. terminal.input?.("\u001b");
  6092. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6093. kind: "chat",
  6094. id: "chat",
  6095. });
  6096. await app.stop();
  6097. },
  6098. );
  6099. it("forks with the assistant boundary and starts a new operation after a terminal failure", async () => {
  6100. const terminal = new FakeTerminal();
  6101. const runtime = createRuntime();
  6102. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6103. {
  6104. userMessageId: "msg-user-1",
  6105. assistantMessageId: "msg-assistant-1",
  6106. contentHead: "Investigate flaky login tests",
  6107. timestamp: 1_700_000_000_000,
  6108. fileChangeCount: 2,
  6109. },
  6110. {
  6111. userMessageId: "msg-user-2",
  6112. assistantMessageId: "msg-assistant-2",
  6113. contentHead: "Draft a new CLI handler",
  6114. timestamp: 1_699_999_000_000,
  6115. fileChangeCount: 0,
  6116. },
  6117. ]);
  6118. vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
  6119. canFork: true,
  6120. worktreeVisible: false,
  6121. worktreeEligible: false,
  6122. });
  6123. vi.mocked(runtime.forkSession).mockRejectedValueOnce(
  6124. Object.assign(new Error("persisted fork recovery failed"), {
  6125. key: "FORK_RECOVERY_FAILED",
  6126. }),
  6127. );
  6128. const app = createTuiApp({
  6129. runtime,
  6130. terminal,
  6131. version: "0.1.0",
  6132. workspaceDir: "/workspace",
  6133. });
  6134. app.start();
  6135. await app.ready;
  6136. // Submit a message so the controller has an active session id.
  6137. await app.submit("Seed the session");
  6138. await vi.waitFor(() =>
  6139. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6140. );
  6141. const sourceSessionId = app.controller.snapshot().session?.sessionId;
  6142. expect(sourceSessionId).toBe("session-1");
  6143. const transcriptBefore = app.transcript.snapshot();
  6144. vi.mocked(runtime.createSession).mockClear();
  6145. vi.mocked(runtime.forkSession).mockClear();
  6146. vi.mocked(runtime.getSessionForkOptions).mockClear();
  6147. vi.mocked(runtime.listSessionInputSummaries).mockClear();
  6148. await app.submit("/fork");
  6149. // 1. /fork loads input summaries, not the generic transcript.
  6150. await vi.waitFor(() =>
  6151. expect(runtime.listSessionInputSummaries).toHaveBeenCalledWith(
  6152. sourceSessionId,
  6153. {
  6154. limit: 100,
  6155. },
  6156. ),
  6157. );
  6158. expect(renderTerminalViewport(app, terminal)).toContain(
  6159. "Fork from a previous message",
  6160. );
  6161. expect(renderTerminalViewport(app, terminal)).not.toContain("Transcript");
  6162. // 2. The newest summary (last entry) is selected by default; confirm with Enter.
  6163. await vi.waitFor(() =>
  6164. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6165. kind: "feature",
  6166. id: "session-mutation:history",
  6167. }),
  6168. );
  6169. terminal.input?.("\r");
  6170. // The history selection only fetches options; it must not mutate yet.
  6171. await vi.waitFor(() =>
  6172. expect(runtime.getSessionForkOptions).toHaveBeenCalledWith(
  6173. sourceSessionId,
  6174. "msg-assistant-2",
  6175. ),
  6176. );
  6177. await vi.waitFor(() =>
  6178. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6179. kind: "feature",
  6180. id: "session-mutation:fork-confirm",
  6181. }),
  6182. );
  6183. expect(runtime.forkSession).not.toHaveBeenCalled();
  6184. expect(renderTerminalViewport(app, terminal)).toContain("Confirm fork");
  6185. // 3. Explicit confirmation performs the mutation.
  6186. terminal.input?.("\r");
  6187. await vi.waitFor(() =>
  6188. expect(runtime.forkSession).toHaveBeenCalledWith(
  6189. expect.objectContaining({
  6190. sessionId: sourceSessionId,
  6191. assistantMessageId: "msg-assistant-2",
  6192. useSuggestedTitle: true,
  6193. createIsolatedWorktree: false,
  6194. }),
  6195. ),
  6196. );
  6197. await vi.waitFor(() =>
  6198. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6199. kind: "feature",
  6200. id: "session-mutation:fork-confirm",
  6201. }),
  6202. );
  6203. terminal.input?.("\r");
  6204. await vi.waitFor(() =>
  6205. expect(runtime.forkSession).toHaveBeenCalledTimes(2),
  6206. );
  6207. const forkCalls = vi.mocked(runtime.forkSession).mock.calls;
  6208. const operationIds = forkCalls.map(([input]) => input.clientRequestId);
  6209. expect(operationIds[0]).toBeTruthy();
  6210. expect(operationIds[1]).toBeTruthy();
  6211. expect(operationIds[0]).not.toBe(operationIds[1]);
  6212. // 5. Activation moves the controller to the child session id.
  6213. await vi.waitFor(() =>
  6214. expect(app.controller.snapshot().session?.sessionId).toBe("session-fork"),
  6215. );
  6216. expect(runtime.createSession).not.toHaveBeenCalled();
  6217. // The user message that seeded the source session was already projected
  6218. // into the transcript before the fork ran; the fork flow must not write
  6219. // any new user-typed cell while the picker is open or the mutation runs.
  6220. expect(
  6221. transcriptBefore.filter((cell) => cell.kind === "user").length,
  6222. ).toBeGreaterThan(0);
  6223. });
  6224. it("does not call forkSession when /fork is cancelled, unavailable, or fails", async () => {
  6225. const scenarios: ReadonlyArray<{
  6226. readonly label: string;
  6227. readonly setup: (runtime: ReturnType<typeof createRuntime>) => void;
  6228. readonly interact: (terminal: FakeTerminal) => void | Promise<void>;
  6229. /** When true, expect forkSession to have been called exactly once. */
  6230. readonly expectForkCall: boolean;
  6231. readonly confirmAfterSelection?: boolean;
  6232. }> = [
  6233. {
  6234. label: "esc cancels the picker without invoking fork",
  6235. setup: (runtime) => {
  6236. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6237. {
  6238. userMessageId: "msg-user-1",
  6239. assistantMessageId: "msg-assistant-1",
  6240. contentHead: "Investigate flaky login tests",
  6241. timestamp: 1_700_000_000_000,
  6242. fileChangeCount: 0,
  6243. },
  6244. ]);
  6245. },
  6246. interact: (terminal) => {
  6247. terminal.input?.("\u001b");
  6248. },
  6249. expectForkCall: false,
  6250. },
  6251. {
  6252. label: "unavailable fork surfaces a warning without invoking fork",
  6253. setup: (runtime) => {
  6254. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6255. {
  6256. userMessageId: "msg-user-1",
  6257. assistantMessageId: "msg-assistant-1",
  6258. contentHead: "Investigate flaky login tests",
  6259. timestamp: 1_700_000_000_000,
  6260. fileChangeCount: 0,
  6261. },
  6262. ]);
  6263. vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
  6264. canFork: false,
  6265. unavailableReason: "No persisted user prompts yet.",
  6266. worktreeVisible: false,
  6267. worktreeEligible: false,
  6268. });
  6269. },
  6270. interact: (terminal) => {
  6271. terminal.input?.("\r");
  6272. },
  6273. expectForkCall: false,
  6274. },
  6275. {
  6276. label:
  6277. "forkSession failure preserves the source session and transcript",
  6278. setup: (runtime) => {
  6279. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6280. {
  6281. userMessageId: "msg-user-1",
  6282. assistantMessageId: "msg-assistant-1",
  6283. contentHead: "Investigate flaky login tests",
  6284. timestamp: 1_700_000_000_000,
  6285. fileChangeCount: 0,
  6286. },
  6287. ]);
  6288. vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
  6289. canFork: true,
  6290. worktreeVisible: false,
  6291. worktreeEligible: false,
  6292. });
  6293. vi.mocked(runtime.forkSession).mockRejectedValue(
  6294. new Error("Runtime offline."),
  6295. );
  6296. },
  6297. interact: (terminal) => {
  6298. terminal.input?.("\r");
  6299. },
  6300. expectForkCall: true,
  6301. confirmAfterSelection: true,
  6302. },
  6303. ];
  6304. for (const scenario of scenarios) {
  6305. const terminal = new FakeTerminal();
  6306. const runtime = createRuntime();
  6307. scenario.setup(runtime);
  6308. const app = createTuiApp({
  6309. runtime,
  6310. terminal,
  6311. version: "0.1.0",
  6312. workspaceDir: "/workspace",
  6313. });
  6314. app.start();
  6315. await app.ready;
  6316. await app.submit("Seed the session");
  6317. await vi.waitFor(() =>
  6318. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6319. );
  6320. const sourceSessionId = app.controller.snapshot().session?.sessionId;
  6321. const transcriptBefore = app.transcript.snapshot();
  6322. await app.submit("/fork");
  6323. await vi.waitFor(() =>
  6324. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6325. kind: "feature",
  6326. id: "session-mutation:history",
  6327. }),
  6328. );
  6329. await scenario.interact(terminal);
  6330. if (scenario.expectForkCall || scenario.label.includes("unavailable")) {
  6331. await vi.waitFor(() =>
  6332. expect(runtime.getSessionForkOptions).toHaveBeenCalled(),
  6333. );
  6334. }
  6335. expect(runtime.forkSession).not.toHaveBeenCalled();
  6336. if (scenario.confirmAfterSelection) {
  6337. terminal.input?.("\r");
  6338. }
  6339. // Give the async fork pipeline a chance to settle.
  6340. await new Promise((resolve) => setTimeout(resolve, 40));
  6341. if (scenario.expectForkCall) {
  6342. expect(
  6343. vi.mocked(runtime.forkSession).mock.calls.length,
  6344. `${scenario.label} should call forkSession once`,
  6345. ).toBe(1);
  6346. } else {
  6347. expect(
  6348. vi.mocked(runtime.forkSession).mock.calls.length,
  6349. `${scenario.label} should not call forkSession`,
  6350. ).toBe(0);
  6351. }
  6352. expect(
  6353. app.controller.snapshot().session?.sessionId,
  6354. `${scenario.label} must not switch sessions`,
  6355. ).toBe(sourceSessionId);
  6356. expect(
  6357. app.transcript.snapshot().filter((cell) => cell.kind === "user").length,
  6358. `${scenario.label} must preserve the source transcript`,
  6359. ).toBe(transcriptBefore.filter((cell) => cell.kind === "user").length);
  6360. await app.stop();
  6361. }
  6362. });
  6363. it("does not call forkSession when the source session changes between summary and selection", async () => {
  6364. const terminal = new FakeTerminal();
  6365. const runtime = createRuntime();
  6366. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6367. {
  6368. userMessageId: "msg-user-1",
  6369. assistantMessageId: "msg-assistant-1",
  6370. contentHead: "Investigate flaky login tests",
  6371. timestamp: 1_700_000_000_000,
  6372. fileChangeCount: 0,
  6373. },
  6374. ]);
  6375. vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
  6376. canFork: true,
  6377. worktreeVisible: false,
  6378. worktreeEligible: false,
  6379. });
  6380. const app = createTuiApp({
  6381. runtime,
  6382. terminal,
  6383. version: "0.1.0",
  6384. workspaceDir: "/workspace",
  6385. });
  6386. app.start();
  6387. await app.ready;
  6388. await app.submit("Seed the session");
  6389. await vi.waitFor(() =>
  6390. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6391. );
  6392. await app.submit("/fork");
  6393. await vi.waitFor(() =>
  6394. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6395. kind: "feature",
  6396. id: "session-mutation:history",
  6397. }),
  6398. );
  6399. // Simulate the source session changing while the picker is open.
  6400. const otherSession = {
  6401. sessionId: "session-other",
  6402. title: "Other session",
  6403. workspaceDir: "/workspace",
  6404. };
  6405. vi.mocked(runtime.listSessions).mockResolvedValue([otherSession]);
  6406. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  6407. sessionId === otherSession.sessionId
  6408. ? otherSession
  6409. : { sessionId, workspaceDir: "/workspace" },
  6410. );
  6411. await app.openSession(otherSession.sessionId);
  6412. expect(app.controller.snapshot().session?.sessionId).toBe(
  6413. otherSession.sessionId,
  6414. );
  6415. // Confirming the picker now must not call forkSession.
  6416. terminal.input?.("\r");
  6417. await new Promise((resolve) => setTimeout(resolve, 20));
  6418. expect(vi.mocked(runtime.forkSession)).not.toHaveBeenCalled();
  6419. expect(vi.mocked(runtime.getSessionForkOptions).mock.calls.length).toBe(0);
  6420. });
  6421. it("preserves the /fork command draft and skips mutation when a turn is running", async () => {
  6422. const terminal = new FakeTerminal();
  6423. const runtime = createRuntime();
  6424. let finishTurn: (() => void) | undefined;
  6425. vi.mocked(runtime.sendMessage).mockImplementation(
  6426. async function* sendMessage() {
  6427. await new Promise<void>((resolve) => {
  6428. finishTurn = resolve;
  6429. });
  6430. yield { type: "done" };
  6431. },
  6432. );
  6433. const app = createTuiApp({
  6434. runtime,
  6435. terminal,
  6436. version: "0.1.0",
  6437. workspaceDir: "/workspace",
  6438. });
  6439. app.start();
  6440. await app.ready;
  6441. const submission = app.submit("Seed the session");
  6442. await vi.waitFor(() =>
  6443. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6444. );
  6445. await vi.waitFor(() =>
  6446. expect(vi.mocked(runtime.sendMessage)).toHaveBeenCalled(),
  6447. );
  6448. const summariesBefore = vi.mocked(runtime.listSessionInputSummaries).mock
  6449. .calls.length;
  6450. const forkOptionsBefore = vi.mocked(runtime.getSessionForkOptions).mock
  6451. .calls.length;
  6452. const forkBefore = vi.mocked(runtime.forkSession).mock.calls.length;
  6453. // While the turn is still running, /fork should preserve the draft and
  6454. // skip every runtime mutation method.
  6455. app.editor.setText("/fork");
  6456. await app.submit("/fork");
  6457. expect(app.editor.getText()).toBe("/fork");
  6458. expect(vi.mocked(runtime.listSessionInputSummaries).mock.calls.length).toBe(
  6459. summariesBefore,
  6460. );
  6461. expect(vi.mocked(runtime.getSessionForkOptions).mock.calls.length).toBe(
  6462. forkOptionsBefore,
  6463. );
  6464. expect(vi.mocked(runtime.forkSession).mock.calls.length).toBe(forkBefore);
  6465. // The fork surface should not have been pushed either.
  6466. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6467. kind: "chat",
  6468. id: "chat",
  6469. });
  6470. finishTurn?.();
  6471. await submission;
  6472. await app.stop();
  6473. });
  6474. it.each([
  6475. ["conversation", []],
  6476. ["conversation_and_files", ["\u001b[B"]],
  6477. ] as const)(
  6478. "runs /rewind with explicit %s scope and stable operation id",
  6479. async (scope, navigation) => {
  6480. const terminal = new FakeTerminal();
  6481. const runtime = createRuntime();
  6482. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6483. {
  6484. userMessageId: "msg-user-rewind",
  6485. contentHead: "Undo this point",
  6486. timestamp: 1_700_000_000_000,
  6487. fileChangeCount: 2,
  6488. },
  6489. ]);
  6490. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  6491. turns: [
  6492. {
  6493. turnId: "turn-1",
  6494. files: [
  6495. { filePath: "src/ready.ts", action: "modified", skipped: false },
  6496. { filePath: "src/skipped.ts", action: "deleted", skipped: true },
  6497. ],
  6498. },
  6499. ],
  6500. });
  6501. vi.mocked(runtime.rewindSession).mockResolvedValue(
  6502. scope === "conversation"
  6503. ? { rewound: true }
  6504. : {
  6505. rewound: true,
  6506. turnDiffRewind: {
  6507. status: "rewound",
  6508. revertedTurnIds: ["turn-1"],
  6509. },
  6510. },
  6511. );
  6512. const app = createTuiApp({
  6513. runtime,
  6514. terminal,
  6515. version: "0.1.0",
  6516. workspaceDir: "/workspace",
  6517. });
  6518. app.start();
  6519. await app.ready;
  6520. await app.submit("Seed rewind session");
  6521. await vi.waitFor(() =>
  6522. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6523. );
  6524. expect(
  6525. app.transcript.snapshot().some((cell) => cell.kind === "turn-duration"),
  6526. ).toBe(true);
  6527. vi.mocked(runtime.getMessages).mockResolvedValue([]);
  6528. await app.submit("/rewind");
  6529. await vi.waitFor(() =>
  6530. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6531. kind: "feature",
  6532. id: "session-mutation:history",
  6533. }),
  6534. );
  6535. terminal.input?.("\r");
  6536. await vi.waitFor(() =>
  6537. expect(runtime.getSessionRewindPreview).toHaveBeenCalledWith({
  6538. sessionId: "session-1",
  6539. userMessageId: "msg-user-rewind",
  6540. }),
  6541. );
  6542. await vi.waitFor(() =>
  6543. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6544. kind: "feature",
  6545. id: "session-mutation:rewind-preview",
  6546. }),
  6547. );
  6548. expect(renderTerminalViewport(app, terminal)).toContain("src/ready.ts");
  6549. expect(renderTerminalViewport(app, terminal)).toContain("src/skipped.ts");
  6550. terminal.input?.("\r");
  6551. await vi.waitFor(() =>
  6552. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6553. kind: "feature",
  6554. id: "session-mutation:scope",
  6555. }),
  6556. );
  6557. for (const key of navigation) terminal.input?.(key);
  6558. terminal.input?.("\r");
  6559. await vi.waitFor(() =>
  6560. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6561. kind: "feature",
  6562. id: "session-mutation:rewind-confirm",
  6563. }),
  6564. );
  6565. expect(runtime.rewindSession).not.toHaveBeenCalled();
  6566. terminal.input?.("\r");
  6567. await vi.waitFor(() =>
  6568. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  6569. );
  6570. const input = vi.mocked(runtime.rewindSession).mock.calls[0]?.[0];
  6571. expect(input).toEqual({
  6572. sessionId: "session-1",
  6573. userMessageId: "msg-user-rewind",
  6574. clientRequestId: expect.stringMatching(/^tui-rewind_/),
  6575. ...(scope === "conversation_and_files" ? { rewindTurnDiff: true } : {}),
  6576. });
  6577. expect(input?.clientRequestId).toMatch(/^tui-rewind_/);
  6578. await vi.waitFor(() => expect(runtime.getMessages).toHaveBeenCalled());
  6579. await vi.waitFor(() =>
  6580. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6581. kind: "chat",
  6582. id: "chat",
  6583. }),
  6584. );
  6585. expect(
  6586. app.transcript
  6587. .snapshot()
  6588. .some((cell) => cell.content === "Rewind completed."),
  6589. ).toBe(false);
  6590. expect(app.transcript.snapshot()).toEqual([]);
  6591. await app.stop();
  6592. },
  6593. );
  6594. it("edits only the latest user turn, hides that turn while editing, and adds no completion cell", async () => {
  6595. const terminal = new FakeTerminal();
  6596. const runtime = createRuntime();
  6597. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6598. {
  6599. userMessageId: "msg-user-older",
  6600. assistantMessageId: "msg-assistant-older",
  6601. contentHead: "Older prompt",
  6602. timestamp: 1,
  6603. fileChangeCount: 0,
  6604. },
  6605. {
  6606. userMessageId: "msg-user-latest",
  6607. assistantMessageId: "msg-assistant-latest",
  6608. contentHead: "Latest prompt",
  6609. timestamp: 2,
  6610. fileChangeCount: 0,
  6611. },
  6612. ]);
  6613. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  6614. messages: [
  6615. {
  6616. id: "msg-user-older",
  6617. role: "user",
  6618. content: "Older prompt",
  6619. timestamp: 1,
  6620. },
  6621. {
  6622. id: "msg-user-latest",
  6623. role: "user",
  6624. content: "Latest prompt",
  6625. timestamp: 2,
  6626. },
  6627. ],
  6628. hasMore: false,
  6629. });
  6630. const app = createTuiApp({
  6631. runtime,
  6632. terminal,
  6633. version: "0.1.0",
  6634. workspaceDir: "/workspace",
  6635. });
  6636. app.start();
  6637. await app.ready;
  6638. await app.submit("Seed edit session");
  6639. await vi.waitFor(() =>
  6640. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6641. );
  6642. app.transcript.upsert({
  6643. id: "older-user-cell",
  6644. kind: "user",
  6645. status: "succeeded",
  6646. content: "Older prompt",
  6647. sourceMessageId: "msg-user-older",
  6648. turnId: "turn-older",
  6649. createdAtMs: 1,
  6650. });
  6651. app.transcript.upsert({
  6652. id: "latest-user-cell",
  6653. kind: "user",
  6654. status: "succeeded",
  6655. content: "Latest prompt",
  6656. sourceMessageId: "msg-user-latest",
  6657. turnId: "turn-latest",
  6658. createdAtMs: 2,
  6659. });
  6660. app.transcript.upsert({
  6661. id: "latest-assistant-cell",
  6662. kind: "assistant",
  6663. status: "succeeded",
  6664. content: "Latest response",
  6665. sourceMessageId: "msg-assistant-latest",
  6666. turnId: "turn-latest",
  6667. createdAtMs: 3,
  6668. });
  6669. await app.submit("/edit");
  6670. await vi.waitFor(() =>
  6671. expect(app.editor.getExpandedText()).toBe("Latest prompt"),
  6672. );
  6673. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6674. kind: "chat",
  6675. id: "chat",
  6676. });
  6677. const editingFrame = app.tui.render(100).join("\n");
  6678. expect(editingFrame).toContain("Older prompt");
  6679. expect(editingFrame).not.toContain("Latest response");
  6680. const historyRefreshCount = vi.mocked(runtime.getMessages).mock.calls
  6681. .length;
  6682. app.editor.setText("Edited latest prompt");
  6683. app.editor.handleInput("\r");
  6684. await vi.waitFor(() =>
  6685. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  6686. );
  6687. await vi.waitFor(() =>
  6688. expect(vi.mocked(runtime.getMessages).mock.calls.length).toBeGreaterThan(
  6689. historyRefreshCount,
  6690. ),
  6691. );
  6692. expect(
  6693. app.transcript
  6694. .snapshot()
  6695. .some(
  6696. (cell) =>
  6697. cell.content ===
  6698. "Edited message submitted; regenerating from this point.",
  6699. ),
  6700. ).toBe(false);
  6701. expect(runtime.editSessionMessage).toHaveBeenCalledWith(
  6702. expect.objectContaining({
  6703. userMessageId: "msg-user-latest",
  6704. content: "Edited latest prompt",
  6705. }),
  6706. );
  6707. await app.stop();
  6708. });
  6709. it("restores the hidden latest turn when Edit is cancelled", async () => {
  6710. const terminal = new FakeTerminal();
  6711. const runtime = createRuntime();
  6712. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6713. {
  6714. userMessageId: "msg-user-latest",
  6715. assistantMessageId: "msg-assistant-latest",
  6716. contentHead: "Latest prompt",
  6717. timestamp: 2,
  6718. fileChangeCount: 0,
  6719. },
  6720. ]);
  6721. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  6722. messages: [
  6723. {
  6724. id: "msg-user-latest",
  6725. role: "user",
  6726. content: "Latest prompt",
  6727. timestamp: 2,
  6728. },
  6729. ],
  6730. hasMore: false,
  6731. });
  6732. const app = createTuiApp({
  6733. runtime,
  6734. terminal,
  6735. version: "0.1.0",
  6736. workspaceDir: "/workspace",
  6737. });
  6738. app.start();
  6739. await app.ready;
  6740. await app.submit("Seed edit session");
  6741. app.transcript.upsert({
  6742. id: "latest-user-cell",
  6743. kind: "user",
  6744. status: "succeeded",
  6745. content: "Latest prompt",
  6746. sourceMessageId: "msg-user-latest",
  6747. turnId: "turn-latest",
  6748. createdAtMs: 2,
  6749. });
  6750. app.transcript.upsert({
  6751. id: "latest-assistant-cell",
  6752. kind: "assistant",
  6753. status: "succeeded",
  6754. content: "Latest response restored on cancel",
  6755. sourceMessageId: "msg-assistant-latest",
  6756. turnId: "turn-latest",
  6757. createdAtMs: 3,
  6758. });
  6759. await app.submit("/edit");
  6760. await vi.waitFor(() =>
  6761. expect(app.editor.getExpandedText()).toBe("Latest prompt"),
  6762. );
  6763. expect(app.tui.render(100).join("\n")).not.toContain(
  6764. "Latest response restored on cancel",
  6765. );
  6766. terminal.input?.("\u001b");
  6767. await vi.waitFor(() => expect(app.editor.getExpandedText()).toBe(""));
  6768. expect(app.tui.render(100).join("\n")).toContain(
  6769. "Latest response restored on cancel",
  6770. );
  6771. expect(runtime.editSessionMessage).not.toHaveBeenCalled();
  6772. await app.stop();
  6773. });
  6774. it.each([
  6775. { reference: "filePath", action: "cancel" },
  6776. { reference: "assetId", action: "send" },
  6777. { reference: "assetId", action: "delete" },
  6778. { reference: "filePath", action: "undo" },
  6779. { reference: "assetId", action: "add" },
  6780. { reference: "filePath", action: "clear-restore" },
  6781. { reference: "filePath", action: "cached" },
  6782. ] as const)(
  6783. "restores editable image chips after double Escape and retry ($reference / $action)",
  6784. async ({ reference, action }) => {
  6785. const terminal = new FakeTerminal();
  6786. const runtime = createRuntime();
  6787. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6788. {
  6789. userMessageId: "msg-user-latest",
  6790. assistantMessageId: "msg-assistant-latest",
  6791. contentHead: "Latest prompt from shortcut",
  6792. timestamp: 2,
  6793. fileChangeCount: 0,
  6794. },
  6795. ]);
  6796. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  6797. messages: [
  6798. {
  6799. id: "msg-user-latest",
  6800. role: "user",
  6801. content: "Latest prompt from shortcut",
  6802. attachments: [
  6803. {
  6804. type: "image",
  6805. fileName: "edit-reference.png",
  6806. mimeType: "image/png",
  6807. [reference]:
  6808. reference === "filePath"
  6809. ? "/workspace/edit-reference.png"
  6810. : "asset-edit-image",
  6811. },
  6812. ],
  6813. timestamp: 2,
  6814. },
  6815. ],
  6816. hasMore: false,
  6817. });
  6818. const app = createTuiApp({
  6819. runtime,
  6820. terminal,
  6821. version: "0.1.0",
  6822. workspaceDir: "/workspace",
  6823. resolveAttachment: async (path) => ({
  6824. type: "image",
  6825. filePath: path,
  6826. fileName: path.endsWith("new.png") ? "new.png" : "edit-reference.png",
  6827. mimeType: "image/png",
  6828. sizeBytes: 123,
  6829. }),
  6830. });
  6831. app.start();
  6832. await app.ready;
  6833. let restoredText = "Latest prompt from shortcut [Image #1] ";
  6834. if (action === "cached") {
  6835. terminal.input?.("\x1b[200~/workspace/edit-reference.png\x1b[201~");
  6836. await vi.waitFor(() =>
  6837. expect(app.editor.getText()).toContain("[Image #1]"),
  6838. );
  6839. app.editor.handleInput("Latest prompt from shortcut");
  6840. restoredText = app.editor.getText();
  6841. app.editor.handleInput("\r");
  6842. await vi.waitFor(() =>
  6843. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  6844. );
  6845. await vi.waitFor(() =>
  6846. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  6847. );
  6848. } else {
  6849. await app.submit("Seed edit session");
  6850. }
  6851. terminal.input?.("\u001b");
  6852. terminal.input?.("\u001b");
  6853. await vi.waitFor(() =>
  6854. expect(app.editor.getExpandedText()).toBe(restoredText),
  6855. );
  6856. expect(runtime.listSessionInputSummaries).toHaveBeenCalledWith(
  6857. "session-1",
  6858. { limit: 100 },
  6859. );
  6860. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6861. kind: "chat",
  6862. id: "chat",
  6863. });
  6864. expect(stripAnsi(app.tui.render(100).join("\n"))).toContain("[Image #1]");
  6865. vi.mocked(runtime.editSessionMessage).mockRejectedValueOnce(
  6866. new Error("Temporary failure"),
  6867. );
  6868. app.editor.handleInput("\r");
  6869. await vi.waitFor(() =>
  6870. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  6871. );
  6872. await vi.waitFor(() =>
  6873. expect(app.editor.getExpandedText()).toBe(restoredText),
  6874. );
  6875. expect(stripAnsi(app.tui.render(100).join("\n"))).toContain("[Image #1]");
  6876. expect(runtime.editSessionMessage).toHaveBeenCalledWith(
  6877. expect.objectContaining({
  6878. content: "Latest prompt from shortcut",
  6879. attachments: [
  6880. expect.objectContaining({
  6881. fileName: "edit-reference.png",
  6882. [reference]:
  6883. reference === "filePath"
  6884. ? "/workspace/edit-reference.png"
  6885. : "asset-edit-image",
  6886. }),
  6887. ],
  6888. }),
  6889. );
  6890. if (action === "delete" || action === "undo") {
  6891. app.editor.handleInput("\x05");
  6892. app.editor.handleInput("\x7f");
  6893. await vi.waitFor(() =>
  6894. expect(app.editor.getText()).not.toContain("[Image #1]"),
  6895. );
  6896. if (action === "undo") {
  6897. app.editor.handleInput("\x1f");
  6898. expect(app.editor.getText()).toContain("[Image #1]");
  6899. }
  6900. }
  6901. if (action === "add") {
  6902. terminal.input?.("\x1b[200~/workspace/new.png\x1b[201~");
  6903. await vi.waitFor(() =>
  6904. expect(app.editor.getText()).toContain("[Image #2]"),
  6905. );
  6906. expect(app.editor.captureDraft().attachmentPlaceholders).toHaveLength(
  6907. 2,
  6908. );
  6909. }
  6910. if (action === "clear-restore") {
  6911. terminal.input?.("\x03");
  6912. expect(app.editor.getText()).toBe("");
  6913. terminal.input?.("\x1f");
  6914. expect(app.editor.getText()).toContain("[Image #1]");
  6915. }
  6916. if (action === "cancel") {
  6917. terminal.input?.("\u001b");
  6918. } else {
  6919. app.editor.handleInput("\r");
  6920. await vi.waitFor(() =>
  6921. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(2),
  6922. );
  6923. const sent = vi.mocked(runtime.editSessionMessage).mock.calls[1]?.[0];
  6924. expect(sent?.content).toBe("Latest prompt from shortcut");
  6925. expect(sent?.attachments ?? []).toHaveLength(
  6926. action === "delete" ? 0 : action === "add" ? 2 : 1,
  6927. );
  6928. if (action !== "delete")
  6929. expect(sent?.attachments?.[0]?.fileName).toBe("edit-reference.png");
  6930. }
  6931. await vi.waitFor(() =>
  6932. expect(stripAnsi(app.tui.render(100).join("\n"))).not.toContain(
  6933. "[Image #1]",
  6934. ),
  6935. );
  6936. await app.stop();
  6937. },
  6938. );
  6939. it("edits the latest committed user turn through the desktop-aligned mutation contract", async () => {
  6940. const terminal = new FakeTerminal();
  6941. const runtime = createRuntime();
  6942. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6943. {
  6944. userMessageId: "msg-user-v1-target",
  6945. assistantMessageId: "msg-assistant-v1-target",
  6946. contentHead: "Original prompt head",
  6947. timestamp: 1_700_000_000_000,
  6948. fileChangeCount: 1,
  6949. },
  6950. ]);
  6951. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  6952. messages: [
  6953. {
  6954. id: "msg-user-v1-target",
  6955. role: "user",
  6956. content: "Original complete prompt",
  6957. attachments: [
  6958. {
  6959. type: "file",
  6960. fileName: "spec.md",
  6961. mimeType: "text/markdown",
  6962. sizeBytes: 42,
  6963. filePath: "/workspace/spec.md",
  6964. },
  6965. ],
  6966. timestamp: 1_700_000_000_000,
  6967. },
  6968. ],
  6969. hasMore: false,
  6970. });
  6971. const app = createTuiApp({
  6972. runtime,
  6973. terminal,
  6974. version: "0.1.0",
  6975. workspaceDir: "/workspace",
  6976. });
  6977. app.start();
  6978. await app.ready;
  6979. await app.submit("Seed edit session");
  6980. await vi.waitFor(() =>
  6981. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6982. );
  6983. await app.submit("/edit");
  6984. await vi.waitFor(() =>
  6985. expect(app.editor.getExpandedText()).toBe(
  6986. "Original complete prompt [File #1] ",
  6987. ),
  6988. );
  6989. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6990. kind: "chat",
  6991. id: "chat",
  6992. });
  6993. app.editor.setText("Updated prompt");
  6994. app.editor.handleInput("\r");
  6995. await vi.waitFor(() =>
  6996. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  6997. );
  6998. expect(runtime.editSessionMessage).toHaveBeenCalledWith({
  6999. sessionId: "session-1",
  7000. userMessageId: "msg-user-v1-target",
  7001. clientRequestId: expect.stringMatching(/^tui-edit_/u),
  7002. content: "Updated prompt",
  7003. attachments: [
  7004. {
  7005. type: "file",
  7006. fileName: "spec.md",
  7007. mimeType: "text/markdown",
  7008. sizeBytes: 42,
  7009. filePath: "/workspace/spec.md",
  7010. },
  7011. ],
  7012. rewindTurnDiff: true,
  7013. });
  7014. await app.stop();
  7015. });
  7016. it("keeps hidden chat context out of the editor and restores it for Edit transport", async () => {
  7017. const terminal = new FakeTerminal();
  7018. const runtime = createRuntime();
  7019. const transportContent = [
  7020. "<user-provided-context>",
  7021. "Referenced context",
  7022. "</user-provided-context>",
  7023. "",
  7024. "Original visible prompt",
  7025. ].join("\n");
  7026. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7027. {
  7028. userMessageId: "msg-user-v1-context",
  7029. assistantMessageId: "msg-assistant-v1-context",
  7030. contentHead: "Original visible prompt",
  7031. timestamp: 1_700_000_000_000,
  7032. fileChangeCount: 0,
  7033. },
  7034. ]);
  7035. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7036. messages: [
  7037. {
  7038. id: "msg-user-v1-context",
  7039. role: "user",
  7040. content: transportContent,
  7041. timestamp: 1_700_000_000_000,
  7042. },
  7043. ],
  7044. hasMore: false,
  7045. });
  7046. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7047. const app = createTuiApp({
  7048. runtime,
  7049. terminal,
  7050. version: "0.1.0",
  7051. workspaceDir: "/workspace",
  7052. });
  7053. app.start();
  7054. await app.ready;
  7055. await app.submit("Seed edit session");
  7056. await app.submit("/edit");
  7057. await vi.waitFor(() =>
  7058. expect(app.editor.getExpandedText()).toBe("Original visible prompt"),
  7059. );
  7060. expect(app.editor.getExpandedText()).not.toContain("user-provided-context");
  7061. app.editor.setText("Updated visible prompt");
  7062. app.editor.handleInput("\r");
  7063. await vi.waitFor(() =>
  7064. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7065. );
  7066. expect(runtime.editSessionMessage).toHaveBeenCalledWith(
  7067. expect.objectContaining({
  7068. content: [
  7069. "<user-provided-context>",
  7070. "Referenced context",
  7071. "</user-provided-context>",
  7072. "",
  7073. "Updated visible prompt",
  7074. ].join("\n"),
  7075. }),
  7076. );
  7077. await app.stop();
  7078. });
  7079. it("preserves hidden context and attachments when Edit recovery requires a new message", async () => {
  7080. const terminal = new FakeTerminal();
  7081. const runtime = createRuntime();
  7082. const transportContent = [
  7083. "<mavis-chat-context>",
  7084. "Referenced context",
  7085. "</mavis-chat-context>",
  7086. "",
  7087. "Original visible prompt",
  7088. ].join("\n");
  7089. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7090. {
  7091. userMessageId: "msg-user-v1-recovery",
  7092. assistantMessageId: "msg-assistant-v1-recovery",
  7093. contentHead: "Original visible prompt",
  7094. timestamp: 1_700_000_000_000,
  7095. fileChangeCount: 0,
  7096. },
  7097. ]);
  7098. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7099. messages: [
  7100. {
  7101. id: "msg-user-v1-recovery",
  7102. role: "user",
  7103. content: transportContent,
  7104. attachments: [
  7105. {
  7106. type: "file",
  7107. fileName: "context.md",
  7108. mimeType: "text/markdown",
  7109. sizeBytes: 42,
  7110. assetId: "asset-context-md",
  7111. },
  7112. ],
  7113. timestamp: 1_700_000_000_000,
  7114. },
  7115. ],
  7116. hasMore: false,
  7117. });
  7118. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7119. vi.mocked(runtime.editSessionMessage).mockRejectedValueOnce(
  7120. Object.assign(new Error("history already rewound"), {
  7121. key: "EDIT_RESTART_NEEDS_RESUBMIT",
  7122. }),
  7123. );
  7124. const app = createTuiApp({
  7125. runtime,
  7126. terminal,
  7127. version: "0.1.0",
  7128. workspaceDir: "/workspace",
  7129. });
  7130. app.start();
  7131. await app.ready;
  7132. await app.submit("Seed edit session");
  7133. const sendCountBeforeEdit = vi.mocked(runtime.sendMessage).mock.calls
  7134. .length;
  7135. await app.submit("/edit");
  7136. await vi.waitFor(() =>
  7137. expect(app.editor.getExpandedText()).toBe(
  7138. "Original visible prompt [File #1] ",
  7139. ),
  7140. );
  7141. app.editor.setText("/help should remain message text");
  7142. app.editor.handleInput("\r");
  7143. await vi.waitFor(() =>
  7144. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7145. );
  7146. await vi.waitFor(() =>
  7147. expect(app.editor.getExpandedText()).toBe(
  7148. "/help should remain message text [File #1] ",
  7149. ),
  7150. );
  7151. expect(app.editor.getExpandedText()).not.toContain("mavis-chat-context");
  7152. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
  7153. let releaseAdmission!: () => void;
  7154. vi.mocked(runtime.getAccountStatus).mockImplementationOnce(
  7155. async () =>
  7156. await new Promise((resolve) => {
  7157. releaseAdmission = () =>
  7158. resolve({
  7159. status: "ready",
  7160. defaultModel: "minimax/MiniMax-M2.7",
  7161. providerId: "minimax",
  7162. modelId: "MiniMax-M2.7",
  7163. authMode: "managed-login",
  7164. managedTokenPresent: true,
  7165. warnings: [],
  7166. });
  7167. }),
  7168. );
  7169. app.editor.handleInput("\r");
  7170. await vi.waitFor(() =>
  7171. expect(app.controller.snapshot().activeTurnId).toBeDefined(),
  7172. );
  7173. terminal.input?.("\u001b");
  7174. releaseAdmission();
  7175. await vi.waitFor(() =>
  7176. expect(app.editor.getExpandedText()).toBe(
  7177. "/help should remain message text [File #1] ",
  7178. ),
  7179. );
  7180. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
  7181. app.editor.handleInput("\r");
  7182. await vi.waitFor(() =>
  7183. expect(runtime.sendMessage).toHaveBeenCalledTimes(
  7184. sendCountBeforeEdit + 1,
  7185. ),
  7186. );
  7187. expect(vi.mocked(runtime.sendMessage).mock.calls.at(-1)?.[0]).toMatchObject(
  7188. {
  7189. content: [
  7190. "<mavis-chat-context>",
  7191. "Referenced context",
  7192. "</mavis-chat-context>",
  7193. "",
  7194. "/help should remain message text",
  7195. ].join("\n"),
  7196. attachments: [
  7197. {
  7198. meta: {
  7199. attachmentType: "file",
  7200. fileName: "context.md",
  7201. mimeType: "text/markdown",
  7202. sizeBytes: 42,
  7203. },
  7204. local: { assetId: "asset-context-md" },
  7205. },
  7206. ],
  7207. },
  7208. );
  7209. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1);
  7210. expect(
  7211. app.transcript
  7212. .snapshot()
  7213. .filter((cell) => cell.kind === "user")
  7214. .map((cell) => cell.content)
  7215. .join("\n"),
  7216. ).toContain("/help should remain message text");
  7217. expect(
  7218. app.transcript
  7219. .snapshot()
  7220. .filter((cell) => cell.kind === "user")
  7221. .map((cell) => cell.content)
  7222. .join("\n"),
  7223. ).not.toContain("mavis-chat-context");
  7224. await app.stop();
  7225. });
  7226. it("allows an attachment-only committed message to enter Edit and gain a body", async () => {
  7227. const terminal = new FakeTerminal();
  7228. const runtime = createRuntime();
  7229. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7230. {
  7231. userMessageId: "msg-user-v1-attachment-only",
  7232. assistantMessageId: "msg-assistant-v1-attachment-only",
  7233. timestamp: 1_700_000_000_000,
  7234. fileChangeCount: 0,
  7235. },
  7236. ]);
  7237. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7238. messages: [
  7239. {
  7240. id: "msg-user-v1-attachment-only",
  7241. role: "user",
  7242. content: "",
  7243. attachments: [
  7244. {
  7245. type: "image",
  7246. fileName: "reference.png",
  7247. mimeType: "image/png",
  7248. filePath: "/workspace/reference.png",
  7249. },
  7250. ],
  7251. timestamp: 1_700_000_000_000,
  7252. },
  7253. ],
  7254. hasMore: false,
  7255. });
  7256. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7257. const app = createTuiApp({
  7258. runtime,
  7259. terminal,
  7260. version: "0.1.0",
  7261. workspaceDir: "/workspace",
  7262. });
  7263. app.start();
  7264. await app.ready;
  7265. await app.submit("Seed edit session");
  7266. const sendCountBeforeEdit = vi.mocked(runtime.sendMessage).mock.calls
  7267. .length;
  7268. await app.submit("/edit");
  7269. await vi.waitFor(() =>
  7270. expect(app.tui.render(100).join("\n")).toContain(
  7271. "Editing the selected message",
  7272. ),
  7273. );
  7274. expect(app.editor.getExpandedText()).toBe("[Image #1] ");
  7275. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7276. kind: "chat",
  7277. id: "chat",
  7278. });
  7279. app.editor.setText("Describe this reference");
  7280. app.editor.handleInput("\r");
  7281. await vi.waitFor(() =>
  7282. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7283. );
  7284. expect(runtime.editSessionMessage).toHaveBeenCalledWith({
  7285. sessionId: "session-1",
  7286. userMessageId: "msg-user-v1-attachment-only",
  7287. clientRequestId: expect.stringMatching(/^tui-edit_/u),
  7288. content: "Describe this reference",
  7289. attachments: [
  7290. {
  7291. type: "image",
  7292. fileName: "reference.png",
  7293. mimeType: "image/png",
  7294. filePath: "/workspace/reference.png",
  7295. },
  7296. ],
  7297. rewindTurnDiff: true,
  7298. });
  7299. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
  7300. await app.stop();
  7301. });
  7302. it("keeps a second composer submission while an edit request is still in flight", async () => {
  7303. const terminal = new FakeTerminal();
  7304. const runtime = createRuntime();
  7305. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7306. {
  7307. userMessageId: "msg-user-v1-target",
  7308. assistantMessageId: "msg-assistant-v1-target",
  7309. contentHead: "Original prompt",
  7310. timestamp: 1,
  7311. fileChangeCount: 0,
  7312. },
  7313. ]);
  7314. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7315. messages: [
  7316. {
  7317. id: "msg-user-v1-target",
  7318. role: "user",
  7319. content: "Original prompt",
  7320. timestamp: 1,
  7321. },
  7322. ],
  7323. hasMore: false,
  7324. });
  7325. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7326. let resolveEdit!: (value: {
  7327. rewound: boolean;
  7328. turnId: string;
  7329. userMessageId: string;
  7330. }) => void;
  7331. vi.mocked(runtime.editSessionMessage).mockImplementation(
  7332. () =>
  7333. new Promise((resolve) => {
  7334. resolveEdit = resolve;
  7335. }),
  7336. );
  7337. const app = createTuiApp({
  7338. runtime,
  7339. terminal,
  7340. version: "0.1.0",
  7341. workspaceDir: "/workspace",
  7342. });
  7343. app.start();
  7344. await app.ready;
  7345. await app.submit("Seed edit session");
  7346. const sendCountBeforeEdit = vi.mocked(runtime.sendMessage).mock.calls
  7347. .length;
  7348. await app.submit("/edit");
  7349. await vi.waitFor(() =>
  7350. expect(app.editor.getText()).toBe("Original prompt"),
  7351. );
  7352. app.editor.setText("First edited prompt");
  7353. app.editor.handleInput("\r");
  7354. await vi.waitFor(() =>
  7355. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7356. );
  7357. app.editor.setText("Keep this until edit settles");
  7358. app.editor.handleInput("\r");
  7359. await vi.waitFor(() =>
  7360. expect(app.editor.getText()).toBe("Keep this until edit settles"),
  7361. );
  7362. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
  7363. resolveEdit({
  7364. rewound: true,
  7365. turnId: "turn-edit-1",
  7366. userMessageId: "msg-user-v1-edited",
  7367. });
  7368. await app.stop();
  7369. });
  7370. it("preserves the edit and retries the same operation when submission fails after rewind", async () => {
  7371. const terminal = new FakeTerminal();
  7372. const runtime = createRuntime();
  7373. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7374. {
  7375. userMessageId: "msg-user-v1-target",
  7376. assistantMessageId: "msg-assistant-v1-target",
  7377. contentHead: "Original prompt",
  7378. timestamp: 1,
  7379. fileChangeCount: 0,
  7380. },
  7381. ]);
  7382. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7383. messages: [
  7384. {
  7385. id: "msg-user-v1-target",
  7386. role: "user",
  7387. content: "Original prompt",
  7388. timestamp: 1,
  7389. },
  7390. ],
  7391. hasMore: false,
  7392. });
  7393. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7394. vi.mocked(runtime.editSessionMessage)
  7395. .mockRejectedValueOnce(
  7396. Object.assign(new Error("submit failed"), {
  7397. key: "EDIT_SUBMIT_FAILED_AFTER_REWIND",
  7398. }),
  7399. )
  7400. .mockResolvedValueOnce({
  7401. rewound: true,
  7402. turnId: "turn-edit-retry",
  7403. userMessageId: "msg-user-v1-edited",
  7404. });
  7405. const app = createTuiApp({
  7406. runtime,
  7407. terminal,
  7408. version: "0.1.0",
  7409. workspaceDir: "/workspace",
  7410. });
  7411. app.start();
  7412. await app.ready;
  7413. await app.submit("Seed edit session");
  7414. await app.submit("/edit");
  7415. await vi.waitFor(() =>
  7416. expect(app.editor.getText()).toBe("Original prompt"),
  7417. );
  7418. app.editor.setText("Preserve this edited prompt");
  7419. app.editor.handleInput("\r");
  7420. await vi.waitFor(() =>
  7421. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7422. );
  7423. await vi.waitFor(() =>
  7424. expect(app.editor.getText()).toBe("Preserve this edited prompt"),
  7425. );
  7426. expect(
  7427. app.transcript
  7428. .snapshot()
  7429. .some((cell) => cell.content.includes("History was rewound")),
  7430. ).toBe(true);
  7431. const firstOperationId = vi.mocked(runtime.editSessionMessage).mock
  7432. .calls[0]?.[0].clientRequestId;
  7433. const sendCount = vi.mocked(runtime.sendMessage).mock.calls.length;
  7434. app.editor.handleInput("\r");
  7435. await vi.waitFor(() =>
  7436. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(2),
  7437. );
  7438. expect(runtime.editSessionMessage).toHaveBeenLastCalledWith(
  7439. expect.objectContaining({ clientRequestId: firstOperationId }),
  7440. );
  7441. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCount);
  7442. await app.stop();
  7443. });
  7444. it("cancels /rewind preview and ignores duplicate scope submission", async () => {
  7445. const terminal = new FakeTerminal();
  7446. const runtime = createRuntime();
  7447. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7448. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7449. ]);
  7450. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7451. turns: [
  7452. {
  7453. turnId: "turn-1",
  7454. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7455. },
  7456. ],
  7457. });
  7458. let resolveRewind!: (value: { rewound: boolean }) => void;
  7459. vi.mocked(runtime.rewindSession).mockImplementation(
  7460. () =>
  7461. new Promise((resolve) => {
  7462. resolveRewind = resolve;
  7463. }),
  7464. );
  7465. const app = createTuiApp({
  7466. runtime,
  7467. terminal,
  7468. version: "0.1.0",
  7469. workspaceDir: "/workspace",
  7470. });
  7471. app.start();
  7472. await app.ready;
  7473. await app.submit("Seed rewind session");
  7474. await app.submit("/rewind");
  7475. await vi.waitFor(() =>
  7476. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7477. kind: "feature",
  7478. id: "session-mutation:history",
  7479. }),
  7480. );
  7481. terminal.input?.("\r");
  7482. await vi.waitFor(() =>
  7483. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7484. kind: "feature",
  7485. id: "session-mutation:rewind-preview",
  7486. }),
  7487. );
  7488. terminal.input?.("\u001b");
  7489. expect(runtime.rewindSession).not.toHaveBeenCalled();
  7490. await app.submit("/rewind");
  7491. await vi.waitFor(() =>
  7492. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7493. kind: "feature",
  7494. id: "session-mutation:history",
  7495. }),
  7496. );
  7497. terminal.input?.("\r");
  7498. await vi.waitFor(() =>
  7499. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7500. kind: "feature",
  7501. id: "session-mutation:rewind-preview",
  7502. }),
  7503. );
  7504. terminal.input?.("\r");
  7505. await vi.waitFor(() =>
  7506. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7507. kind: "feature",
  7508. id: "session-mutation:scope",
  7509. }),
  7510. );
  7511. terminal.input?.("\r");
  7512. await vi.waitFor(() =>
  7513. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7514. kind: "feature",
  7515. id: "session-mutation:rewind-confirm",
  7516. }),
  7517. );
  7518. terminal.input?.("\r");
  7519. await vi.waitFor(() =>
  7520. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  7521. );
  7522. terminal.input?.("\u001b");
  7523. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7524. kind: "feature",
  7525. id: "session-mutation:rewind-confirm",
  7526. });
  7527. resolveRewind({ rewound: true });
  7528. await app.stop();
  7529. });
  7530. it("invalidates /rewind when the active session switches before mutation", async () => {
  7531. const terminal = new FakeTerminal();
  7532. const runtime = createRuntime();
  7533. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7534. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 0 },
  7535. ]);
  7536. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7537. const app = createTuiApp({
  7538. runtime,
  7539. terminal,
  7540. version: "0.1.0",
  7541. workspaceDir: "/workspace",
  7542. });
  7543. app.start();
  7544. await app.ready;
  7545. await app.submit("Seed rewind session");
  7546. await app.submit("/rewind");
  7547. await vi.waitFor(() =>
  7548. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7549. kind: "feature",
  7550. id: "session-mutation:history",
  7551. }),
  7552. );
  7553. const other = {
  7554. sessionId: "session-other",
  7555. title: "Other",
  7556. workspaceDir: "/workspace",
  7557. };
  7558. vi.mocked(runtime.getSession).mockResolvedValue(other);
  7559. await app.openSession(other.sessionId);
  7560. terminal.input?.("\r");
  7561. await new Promise((resolve) => setTimeout(resolve, 20));
  7562. expect(runtime.getSessionRewindPreview).not.toHaveBeenCalled();
  7563. expect(runtime.rewindSession).not.toHaveBeenCalled();
  7564. expect(app.controller.snapshot().session?.sessionId).toBe(other.sessionId);
  7565. await app.stop();
  7566. });
  7567. it("retries a failed file rewind with the same operation id", async () => {
  7568. const terminal = new FakeTerminal();
  7569. const runtime = createRuntime();
  7570. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7571. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7572. ]);
  7573. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7574. turns: [
  7575. {
  7576. turnId: "turn-1",
  7577. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7578. },
  7579. ],
  7580. });
  7581. vi.mocked(runtime.rewindSession)
  7582. .mockRejectedValueOnce(new Error("temporary conflict"))
  7583. .mockResolvedValueOnce({
  7584. rewound: true,
  7585. turnDiffRewind: { status: "rewound", revertedTurnIds: ["turn-1"] },
  7586. });
  7587. const app = createTuiApp({
  7588. runtime,
  7589. terminal,
  7590. version: "0.1.0",
  7591. workspaceDir: "/workspace",
  7592. });
  7593. app.start();
  7594. await app.ready;
  7595. await app.submit("Seed rewind session");
  7596. await app.submit("/rewind");
  7597. await vi.waitFor(() =>
  7598. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7599. kind: "feature",
  7600. id: "session-mutation:history",
  7601. }),
  7602. );
  7603. terminal.input?.("\r");
  7604. await vi.waitFor(() =>
  7605. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7606. kind: "feature",
  7607. id: "session-mutation:rewind-preview",
  7608. }),
  7609. );
  7610. terminal.input?.("\r");
  7611. await vi.waitFor(() =>
  7612. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7613. kind: "feature",
  7614. id: "session-mutation:scope",
  7615. }),
  7616. );
  7617. terminal.input?.("\u001b[B");
  7618. terminal.input?.("\r");
  7619. await vi.waitFor(() =>
  7620. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7621. kind: "feature",
  7622. id: "session-mutation:rewind-confirm",
  7623. }),
  7624. );
  7625. terminal.input?.("\r");
  7626. await vi.waitFor(() =>
  7627. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  7628. );
  7629. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7630. kind: "feature",
  7631. id: "session-mutation:rewind-confirm",
  7632. });
  7633. terminal.input?.("\r");
  7634. await vi.waitFor(() =>
  7635. expect(runtime.rewindSession).toHaveBeenCalledTimes(2),
  7636. );
  7637. const ids = vi
  7638. .mocked(runtime.rewindSession)
  7639. .mock.calls.map(([input]) => input.clientRequestId);
  7640. expect(ids[0]).toBe(ids[1]);
  7641. await app.stop();
  7642. });
  7643. it.each([
  7644. [
  7645. "terminal busy failure",
  7646. "CONVERSATION_MUTATION_BUSY",
  7647. "Stop the running response and try again.",
  7648. false,
  7649. ],
  7650. [
  7651. "pending display publication",
  7652. "REWIND_DISPLAY_COMMIT_FAILED",
  7653. "retry with the same operation id",
  7654. true,
  7655. ],
  7656. ] as const)(
  7657. "keeps a failed conversation rewind open and retries %s with the correct operation id",
  7658. async (_label, errorCode, expectedCopy, reuseOperationId) => {
  7659. const terminal = new FakeTerminal();
  7660. const runtime = createRuntime();
  7661. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7662. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 0 },
  7663. ]);
  7664. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7665. turns: [],
  7666. });
  7667. vi.mocked(runtime.rewindSession)
  7668. .mockRejectedValueOnce(
  7669. Object.assign(new Error("rewind failed"), { key: errorCode }),
  7670. )
  7671. .mockResolvedValueOnce({ rewound: true });
  7672. const app = createTuiApp({
  7673. runtime,
  7674. terminal,
  7675. version: "0.1.0",
  7676. workspaceDir: "/workspace",
  7677. });
  7678. app.start();
  7679. await app.ready;
  7680. await app.submit("Seed rewind session");
  7681. await app.submit("/rewind");
  7682. await vi.waitFor(() =>
  7683. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7684. kind: "feature",
  7685. id: "session-mutation:history",
  7686. }),
  7687. );
  7688. terminal.input?.("\r");
  7689. await vi.waitFor(() =>
  7690. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7691. kind: "feature",
  7692. id: "session-mutation:rewind-preview",
  7693. }),
  7694. );
  7695. terminal.input?.("\r");
  7696. await vi.waitFor(() =>
  7697. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7698. kind: "feature",
  7699. id: "session-mutation:scope",
  7700. }),
  7701. );
  7702. terminal.input?.("\r");
  7703. await vi.waitFor(() =>
  7704. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7705. kind: "feature",
  7706. id: "session-mutation:rewind-confirm",
  7707. }),
  7708. );
  7709. terminal.input?.("\r");
  7710. await vi.waitFor(() =>
  7711. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  7712. );
  7713. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7714. kind: "feature",
  7715. id: "session-mutation:rewind-confirm",
  7716. });
  7717. expect(renderTerminalViewport(app, terminal)).toContain(expectedCopy);
  7718. terminal.input?.("\r");
  7719. await vi.waitFor(() =>
  7720. expect(runtime.rewindSession).toHaveBeenCalledTimes(2),
  7721. );
  7722. const ids = vi
  7723. .mocked(runtime.rewindSession)
  7724. .mock.calls.map(([input]) => input.clientRequestId);
  7725. if (reuseOperationId) expect(ids[0]).toBe(ids[1]);
  7726. else expect(ids[0]).not.toBe(ids[1]);
  7727. await app.stop();
  7728. },
  7729. );
  7730. it.each([
  7731. [
  7732. "failed-after-rewind",
  7733. {
  7734. status: "failed-after-rewind",
  7735. revertedTurnIds: ["turn-1"],
  7736. errorCode: "conflict",
  7737. },
  7738. ],
  7739. ["empty-reverted-ids", { status: "rewound", revertedTurnIds: [] }],
  7740. [
  7741. "unknown-status",
  7742. { status: "future-runtime-status", revertedTurnIds: ["turn-1"] },
  7743. ],
  7744. ] as const)(
  7745. "does not report %s as a successful file rewind",
  7746. async (_label, turnDiffRewind) => {
  7747. const terminal = new FakeTerminal();
  7748. const runtime = createRuntime();
  7749. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7750. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7751. ]);
  7752. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7753. turns: [
  7754. {
  7755. turnId: "turn-1",
  7756. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7757. },
  7758. ],
  7759. });
  7760. vi.mocked(runtime.rewindSession).mockResolvedValue({
  7761. rewound: true,
  7762. turnDiffRewind,
  7763. });
  7764. const app = createTuiApp({
  7765. runtime,
  7766. terminal,
  7767. version: "0.1.0",
  7768. workspaceDir: "/workspace",
  7769. });
  7770. app.start();
  7771. await app.ready;
  7772. await app.submit("Seed rewind session");
  7773. await app.submit("/rewind");
  7774. await vi.waitFor(() =>
  7775. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7776. kind: "feature",
  7777. id: "session-mutation:history",
  7778. }),
  7779. );
  7780. terminal.input?.("\r");
  7781. await vi.waitFor(() =>
  7782. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7783. kind: "feature",
  7784. id: "session-mutation:rewind-preview",
  7785. }),
  7786. );
  7787. terminal.input?.("\r");
  7788. await vi.waitFor(() =>
  7789. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7790. kind: "feature",
  7791. id: "session-mutation:scope",
  7792. }),
  7793. );
  7794. terminal.input?.("\u001b[B");
  7795. terminal.input?.("\r");
  7796. await vi.waitFor(() =>
  7797. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7798. kind: "feature",
  7799. id: "session-mutation:rewind-confirm",
  7800. }),
  7801. );
  7802. terminal.input?.("\r");
  7803. await vi.waitFor(() =>
  7804. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  7805. );
  7806. await vi.waitFor(() =>
  7807. expect(app.transcript.snapshot().at(-1)?.content).toMatch(
  7808. /did not complete|No file changes/,
  7809. ),
  7810. );
  7811. expect(app.transcript.snapshot().at(-1)?.content).not.toContain(
  7812. "Files rewound; conversation history was kept.",
  7813. );
  7814. await app.stop();
  7815. },
  7816. );
  7817. it.each([
  7818. [
  7819. "MESSAGE_BOUNDARY_INVALID",
  7820. "This conversation point is no longer available.",
  7821. ],
  7822. [
  7823. "CONVERSATION_MUTATION_REQUEST_CONFLICT",
  7824. "This action was already submitted or became stale.",
  7825. ],
  7826. ["CONVERSATION_MUTATION_BUSY", "Stop the running response and try again."],
  7827. ] as const)(
  7828. "maps rewind Runtime error %s to stable copy",
  7829. async (code, expected) => {
  7830. const terminal = new FakeTerminal();
  7831. const runtime = createRuntime();
  7832. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7833. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7834. ]);
  7835. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7836. turns: [
  7837. {
  7838. turnId: "turn-1",
  7839. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7840. },
  7841. ],
  7842. });
  7843. vi.mocked(runtime.rewindSession).mockRejectedValue(
  7844. Object.assign(new Error("raw prompt token=secret"), { key: code }),
  7845. );
  7846. const app = createTuiApp({
  7847. runtime,
  7848. terminal,
  7849. version: "0.1.0",
  7850. workspaceDir: "/workspace",
  7851. });
  7852. app.start();
  7853. await app.ready;
  7854. await app.submit("Seed rewind session");
  7855. await app.submit("/rewind");
  7856. await vi.waitFor(() =>
  7857. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7858. kind: "feature",
  7859. id: "session-mutation:history",
  7860. }),
  7861. );
  7862. terminal.input?.("\r");
  7863. await vi.waitFor(() =>
  7864. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7865. kind: "feature",
  7866. id: "session-mutation:rewind-preview",
  7867. }),
  7868. );
  7869. terminal.input?.("\r");
  7870. await vi.waitFor(() =>
  7871. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7872. kind: "feature",
  7873. id: "session-mutation:scope",
  7874. }),
  7875. );
  7876. terminal.input?.("\u001b[B");
  7877. terminal.input?.("\r");
  7878. await vi.waitFor(() =>
  7879. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7880. kind: "feature",
  7881. id: "session-mutation:rewind-confirm",
  7882. }),
  7883. );
  7884. terminal.input?.("\r");
  7885. await vi.waitFor(() =>
  7886. expect(
  7887. app.transcript.snapshot().some((cell) => cell.content === expected),
  7888. ),
  7889. );
  7890. expect(
  7891. app.transcript
  7892. .snapshot()
  7893. .some((cell) => cell.content.includes("raw prompt token")),
  7894. ).toBe(false);
  7895. await app.stop();
  7896. },
  7897. );
  7898. it("reports refresh failure without unhandled rejection after conversation-and-files rewind", async () => {
  7899. const terminal = new FakeTerminal();
  7900. const runtime = createRuntime();
  7901. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7902. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7903. ]);
  7904. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7905. turns: [
  7906. {
  7907. turnId: "turn-1",
  7908. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7909. },
  7910. ],
  7911. });
  7912. vi.mocked(runtime.rewindSession).mockResolvedValue({
  7913. rewound: true,
  7914. turnDiffRewind: { status: "rewound", revertedTurnIds: ["turn-1"] },
  7915. });
  7916. vi.mocked(runtime.getMessages).mockRejectedValueOnce(
  7917. new Error("refresh unavailable"),
  7918. );
  7919. const app = createTuiApp({
  7920. runtime,
  7921. terminal,
  7922. version: "0.1.0",
  7923. workspaceDir: "/workspace",
  7924. });
  7925. app.start();
  7926. await app.ready;
  7927. await app.submit("Seed rewind session");
  7928. await app.submit("/rewind");
  7929. await vi.waitFor(() =>
  7930. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7931. kind: "feature",
  7932. id: "session-mutation:history",
  7933. }),
  7934. );
  7935. terminal.input?.("\r");
  7936. await vi.waitFor(() =>
  7937. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7938. kind: "feature",
  7939. id: "session-mutation:rewind-preview",
  7940. }),
  7941. );
  7942. terminal.input?.("\r");
  7943. await vi.waitFor(() =>
  7944. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7945. kind: "feature",
  7946. id: "session-mutation:scope",
  7947. }),
  7948. );
  7949. terminal.input?.("\u001b[B");
  7950. terminal.input?.("\r");
  7951. await vi.waitFor(() =>
  7952. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7953. kind: "feature",
  7954. id: "session-mutation:rewind-confirm",
  7955. }),
  7956. );
  7957. terminal.input?.("\r");
  7958. await vi.waitFor(() =>
  7959. expect(
  7960. app.transcript
  7961. .snapshot()
  7962. .some((cell) => cell.content.includes("could not be refreshed")),
  7963. ),
  7964. );
  7965. await app.stop();
  7966. });
  7967. it("does not apply a pending rewind refresh result after switching sessions", async () => {
  7968. const terminal = new FakeTerminal();
  7969. const runtime = createRuntime();
  7970. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7971. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7972. ]);
  7973. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7974. turns: [
  7975. {
  7976. turnId: "turn-1",
  7977. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7978. },
  7979. ],
  7980. });
  7981. vi.mocked(runtime.rewindSession).mockResolvedValue({
  7982. rewound: true,
  7983. turnDiffRewind: { status: "rewound", revertedTurnIds: ["turn-1"] },
  7984. });
  7985. let resolveRefresh!: (messages: readonly TuiMessage[]) => void;
  7986. const refreshPromise = new Promise<readonly TuiMessage[]>((resolve) => {
  7987. resolveRefresh = resolve;
  7988. });
  7989. const app = createTuiApp({
  7990. runtime,
  7991. terminal,
  7992. version: "0.1.0",
  7993. workspaceDir: "/workspace",
  7994. });
  7995. app.start();
  7996. await app.ready;
  7997. await app.submit("Seed rewind session");
  7998. vi.mocked(runtime.getMessages).mockImplementationOnce(() => refreshPromise);
  7999. await app.submit("/rewind");
  8000. await vi.waitFor(() =>
  8001. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8002. kind: "feature",
  8003. id: "session-mutation:history",
  8004. }),
  8005. );
  8006. terminal.input?.("\r");
  8007. await vi.waitFor(() =>
  8008. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8009. kind: "feature",
  8010. id: "session-mutation:rewind-preview",
  8011. }),
  8012. );
  8013. terminal.input?.("\r");
  8014. await vi.waitFor(() =>
  8015. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8016. kind: "feature",
  8017. id: "session-mutation:scope",
  8018. }),
  8019. );
  8020. terminal.input?.("\u001b[B");
  8021. terminal.input?.("\r");
  8022. await vi.waitFor(() =>
  8023. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8024. kind: "feature",
  8025. id: "session-mutation:rewind-confirm",
  8026. }),
  8027. );
  8028. terminal.input?.("\r");
  8029. await vi.waitFor(() =>
  8030. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  8031. );
  8032. const other = {
  8033. sessionId: "session-other",
  8034. title: "Other",
  8035. workspaceDir: "/workspace",
  8036. };
  8037. vi.mocked(runtime.getSession).mockResolvedValue(other);
  8038. vi.mocked(runtime.getMessages).mockResolvedValue([]);
  8039. const open = app.openSession(other.sessionId);
  8040. resolveRefresh([
  8041. {
  8042. id: "stale-message",
  8043. role: "assistant",
  8044. content: "stale",
  8045. timestamp: 3,
  8046. },
  8047. ]);
  8048. await open;
  8049. expect(app.controller.snapshot().session?.sessionId).toBe(other.sessionId);
  8050. expect(
  8051. app.transcript
  8052. .snapshot()
  8053. .some((cell) => cell.content.includes("Files rewound")),
  8054. ).toBe(false);
  8055. await app.stop();
  8056. });
  8057. it("redirects a hidden task child to its parent before rendering", async () => {
  8058. const runtime = createRuntime();
  8059. const parent = {
  8060. sessionId: "session-parent",
  8061. title: "CLI integration",
  8062. workspaceDir: "/workspace",
  8063. };
  8064. const child = {
  8065. sessionId: "session-child",
  8066. parentSessionId: parent.sessionId,
  8067. title: "Review recent CLI changes",
  8068. workspaceDir: "/workspace",
  8069. sessionType: "branch",
  8070. sessionKind: "task",
  8071. visibility: "hidden",
  8072. purpose: "local-task:turn-1:tool-1",
  8073. agentName: "verifier",
  8074. };
  8075. vi.mocked(runtime.listSessions).mockResolvedValue([parent]);
  8076. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  8077. sessionId === child.sessionId ? child : parent,
  8078. );
  8079. const app = createTuiApp({
  8080. runtime,
  8081. terminal: new FakeTerminal(),
  8082. version: "0.1.0",
  8083. workspaceDir: "/workspace",
  8084. });
  8085. await app.ready;
  8086. await app.openSession(child.sessionId);
  8087. expect(runtime.getSession).toHaveBeenLastCalledWith(parent.sessionId);
  8088. expect(app.controller.snapshot().session?.sessionId).toBe(parent.sessionId);
  8089. expect(app.tui.render(140).join("\n")).not.toContain("Sub: verifier");
  8090. expect(app.transcript.snapshot().at(-1)?.content).toBe(
  8091. "Sub-agent Sessions are internal. Opened the parent Session instead.",
  8092. );
  8093. await app.stop();
  8094. });
  8095. it("shows compact Agent Team status without exposing child details or commands", async () => {
  8096. const terminal = new FakeTerminal();
  8097. terminal.rows = 24;
  8098. const runtime = createRuntime();
  8099. const parent = {
  8100. sessionId: "session-parent",
  8101. title: "Agent Team parent",
  8102. workspaceDir: "/workspace",
  8103. };
  8104. const child = {
  8105. sessionId: "session-child",
  8106. parentSessionId: parent.sessionId,
  8107. title: "Verify the TUI",
  8108. workspaceDir: "/workspace",
  8109. sessionType: "branch" as const,
  8110. sessionKind: "task",
  8111. visibility: "hidden" as const,
  8112. purpose: "local-task:turn-1:tool-1",
  8113. agentName: "verifier",
  8114. status: "finished",
  8115. };
  8116. vi.mocked(runtime.listSessions).mockResolvedValue([parent]);
  8117. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  8118. sessionId === child.sessionId ? child : parent,
  8119. );
  8120. vi.mocked(runtime.getDelegationSnapshot).mockResolvedValue({
  8121. schemaVersion: 1,
  8122. rootSessionId: parent.sessionId,
  8123. members: [
  8124. {
  8125. sessionId: child.sessionId,
  8126. parentSessionId: parent.sessionId,
  8127. agentName: child.agentName,
  8128. task: child.title,
  8129. status: "running",
  8130. createdAtMs: 100,
  8131. updatedAtMs: 200,
  8132. },
  8133. ],
  8134. });
  8135. vi.mocked(runtime.getMessages).mockImplementation(async (sessionId) =>
  8136. sessionId === child.sessionId
  8137. ? [
  8138. {
  8139. id: "child-answer",
  8140. turnId: "turn-child",
  8141. role: "assistant",
  8142. content: "Child verification result",
  8143. timestamp: 200,
  8144. },
  8145. ]
  8146. : [],
  8147. );
  8148. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
  8149. schemaVersion: 1,
  8150. sessionId,
  8151. state: sessionId === child.sessionId ? "running" : "idle",
  8152. ...(sessionId === child.sessionId ? { turnId: "turn-child" } : {}),
  8153. actions: { steer: false },
  8154. }));
  8155. const app = createTuiApp({
  8156. runtime,
  8157. terminal,
  8158. version: "0.1.0",
  8159. workspaceDir: "/workspace",
  8160. });
  8161. await app.ready;
  8162. await app.openSession(parent.sessionId);
  8163. app.start();
  8164. const summary = app.tui.render(100).join("\n");
  8165. expect(summary).toContain("Tasks · 1 agent active · /tasks details");
  8166. expect(summary).not.toContain("verifier");
  8167. expect(summary).not.toContain("/agents");
  8168. expect(
  8169. app.transcript.snapshot().some((cell) => cell.kind === "agent-team"),
  8170. ).toBe(false);
  8171. await app.submit("/agents");
  8172. await app.submit("/team");
  8173. expect(app.controller.snapshot().session?.sessionId).toBe(parent.sessionId);
  8174. expect(app.tui.hasOverlay()).toBe(false);
  8175. expect(app.interaction.isActive()).toBe(false);
  8176. expect(app.tui.render(100).join("\n")).not.toContain(
  8177. "Child verification result",
  8178. );
  8179. expect(
  8180. vi
  8181. .mocked(runtime.sendMessage)
  8182. .mock.calls.map(([request]) => request.content),
  8183. ).toEqual(["/agents", "/team"]);
  8184. await app.stop();
  8185. });
  8186. it("allocates enough standard-terminal space for ten session choices", async () => {
  8187. const terminal = new FakeTerminal();
  8188. terminal.rows = 24;
  8189. const runtime = createRuntime();
  8190. vi.mocked(runtime.listSessionPage).mockResolvedValue({
  8191. sessions: Array.from({ length: 12 }, (_, index) => ({
  8192. sessionId: `session-${String(index + 1).padStart(2, "0")}`,
  8193. title: `Session ${String(index + 1).padStart(2, "0")}`,
  8194. workspaceDir: "/workspace",
  8195. updatedAt: 12 - index,
  8196. })),
  8197. hasMore: false,
  8198. });
  8199. const app = createTuiApp({
  8200. runtime,
  8201. terminal,
  8202. version: "0.1.0",
  8203. workspaceDir: "/workspace",
  8204. });
  8205. await app.submit("/sessions");
  8206. const lines = app.interaction.current()?.render(80) ?? [];
  8207. const rendered = lines.join("\n");
  8208. expect(lines.length).toBeLessThanOrEqual(terminal.rows);
  8209. expect(rendered).toContain("Session 10");
  8210. expect(rendered).not.toContain("Session 11");
  8211. });
  8212. it("switches, restores, and resumes archived Desktop sessions from the session manager", async () => {
  8213. const terminal = new FakeTerminal();
  8214. const runtime = createRuntime();
  8215. let archived = true;
  8216. const activeSession = {
  8217. sessionId: "session-active",
  8218. title: "Active session",
  8219. workspaceDir: "/workspace",
  8220. updatedAt: 200,
  8221. };
  8222. const archivedSession = {
  8223. sessionId: "session-archived",
  8224. title: "Archived session",
  8225. workspaceDir: "/workspace",
  8226. updatedAt: 100,
  8227. archived: true,
  8228. };
  8229. vi.mocked(runtime.listSessions).mockResolvedValue([activeSession]);
  8230. vi.mocked(runtime.listSessionPage).mockResolvedValue({
  8231. sessions: [activeSession, archivedSession],
  8232. hasMore: false,
  8233. });
  8234. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) => ({
  8235. ...(sessionId === archivedSession.sessionId
  8236. ? archivedSession
  8237. : activeSession),
  8238. archived: sessionId === archivedSession.sessionId ? archived : false,
  8239. }));
  8240. vi.mocked(runtime.archiveSession).mockImplementation(
  8241. async (_sessionId, value) => {
  8242. archived = value;
  8243. },
  8244. );
  8245. const app = createTuiApp({
  8246. runtime,
  8247. terminal,
  8248. version: "0.1.0",
  8249. workspaceDir: "/workspace",
  8250. });
  8251. app.start();
  8252. await app.ready;
  8253. await app.submit("/sessions");
  8254. expect(runtime.listSessionPage).toHaveBeenCalledWith({
  8255. allAgents: true,
  8256. workspaceDir: "/workspace",
  8257. limit: 50,
  8258. includeArchived: true,
  8259. includeHidden: true,
  8260. });
  8261. expect(app.tui.hasOverlay()).toBe(false);
  8262. expect(app.interaction.isActive()).toBe(true);
  8263. terminal.input?.("\t");
  8264. terminal.input?.("\r");
  8265. await vi.waitFor(() =>
  8266. expect(runtime.archiveSession).toHaveBeenCalledWith(
  8267. "session-archived",
  8268. false,
  8269. ),
  8270. );
  8271. await vi.waitFor(() =>
  8272. expect(runtime.getMessages).toHaveBeenCalledWith("session-archived"),
  8273. );
  8274. expect(app.getSurface()).toBe("conversation");
  8275. expect(app.controller.snapshot().session?.sessionId).toBe(
  8276. "session-archived",
  8277. );
  8278. expect(app.tui.hasOverlay()).toBe(false);
  8279. await app.stop();
  8280. });
  8281. it("uses the resume alias to search every Desktop session page", async () => {
  8282. const terminal = new FakeTerminal();
  8283. const runtime = createRuntime();
  8284. vi.mocked(runtime.listSessionPage)
  8285. .mockResolvedValueOnce({
  8286. sessions: [
  8287. {
  8288. sessionId: "session-page-1",
  8289. title: "First page",
  8290. workspaceDir: "/workspace",
  8291. updatedAt: 200,
  8292. },
  8293. ],
  8294. hasMore: true,
  8295. nextCursor: "session-page-1",
  8296. })
  8297. .mockResolvedValueOnce({
  8298. sessions: [
  8299. {
  8300. sessionId: "session-page-2",
  8301. title: "Second page",
  8302. workspaceDir: "/workspace",
  8303. updatedAt: 100,
  8304. },
  8305. ],
  8306. hasMore: false,
  8307. });
  8308. const app = createTuiApp({
  8309. runtime,
  8310. terminal,
  8311. version: "0.1.0",
  8312. workspaceDir: "/workspace",
  8313. });
  8314. app.start();
  8315. await app.ready;
  8316. await app.submit("/resume Second page");
  8317. await vi.waitFor(() =>
  8318. expect(runtime.listSessionPage).toHaveBeenNthCalledWith(2, {
  8319. allAgents: true,
  8320. workspaceDir: "/workspace",
  8321. limit: 50,
  8322. cursor: "session-page-1",
  8323. includeArchived: true,
  8324. includeHidden: true,
  8325. }),
  8326. );
  8327. expect(app.tui.hasOverlay()).toBe(false);
  8328. expect(app.interaction.isActive()).toBe(true);
  8329. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8330. "Second page",
  8331. );
  8332. await app.stop();
  8333. });
  8334. it("queries the current workspace first and reloads the global catalog on Ctrl+A", async () => {
  8335. const terminal = new FakeTerminal();
  8336. const runtime = createRuntime();
  8337. vi.mocked(runtime.listSessionPage).mockImplementation(
  8338. async (input = {}) => {
  8339. if (input.cursor === "all-page-2") {
  8340. return {
  8341. sessions: [
  8342. {
  8343. sessionId: "session-other-older",
  8344. title: "Older session elsewhere",
  8345. workspaceDir: "/other-workspace",
  8346. updatedAt: 50,
  8347. },
  8348. ],
  8349. hasMore: false,
  8350. };
  8351. }
  8352. return input.workspaceDir
  8353. ? {
  8354. sessions: [
  8355. {
  8356. sessionId: "session-workspace-old",
  8357. title: "Older workspace session",
  8358. workspaceDir: "/workspace",
  8359. updatedAt: 100,
  8360. },
  8361. ],
  8362. hasMore: false,
  8363. }
  8364. : {
  8365. sessions: [
  8366. {
  8367. sessionId: "session-other-new",
  8368. title: "Newer session elsewhere",
  8369. workspaceDir: "/other-workspace",
  8370. updatedAt: 200,
  8371. },
  8372. {
  8373. sessionId: "session-workspace-old",
  8374. title: "Older workspace session",
  8375. workspaceDir: "/workspace",
  8376. updatedAt: 100,
  8377. },
  8378. ],
  8379. hasMore: true,
  8380. nextCursor: "all-page-2",
  8381. };
  8382. },
  8383. );
  8384. const app = createTuiApp({
  8385. runtime,
  8386. terminal,
  8387. version: "0.1.0",
  8388. workspaceDir: "/workspace",
  8389. });
  8390. app.start();
  8391. await app.ready;
  8392. await app.submit("/sessions");
  8393. expect(runtime.listSessionPage).toHaveBeenNthCalledWith(1, {
  8394. allAgents: true,
  8395. workspaceDir: "/workspace",
  8396. limit: 50,
  8397. includeArchived: true,
  8398. includeHidden: true,
  8399. });
  8400. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8401. "Older workspace session",
  8402. );
  8403. terminal.input?.("\x01");
  8404. await vi.waitFor(() =>
  8405. expect(runtime.listSessionPage).toHaveBeenNthCalledWith(2, {
  8406. allAgents: true,
  8407. limit: 50,
  8408. includeArchived: true,
  8409. includeHidden: true,
  8410. }),
  8411. );
  8412. await vi.waitFor(() =>
  8413. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8414. "Newer session elsewhere",
  8415. ),
  8416. );
  8417. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8418. "All sessions",
  8419. );
  8420. terminal.input?.("\x0c");
  8421. await vi.waitFor(() =>
  8422. expect(runtime.listSessionPage).toHaveBeenNthCalledWith(3, {
  8423. allAgents: true,
  8424. limit: 50,
  8425. cursor: "all-page-2",
  8426. includeArchived: true,
  8427. includeHidden: true,
  8428. }),
  8429. );
  8430. await vi.waitFor(() =>
  8431. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8432. "Older session elsewhere",
  8433. ),
  8434. );
  8435. await app.stop();
  8436. });
  8437. it("shows account status and resolves pending permission and questionnaire decisions", async () => {
  8438. const terminal = new FakeTerminal();
  8439. const runtime = createRuntime();
  8440. vi.mocked(runtime.listSessions).mockResolvedValue([
  8441. {
  8442. sessionId: "session-existing",
  8443. title: "Existing session",
  8444. workspaceDir: "/workspace",
  8445. },
  8446. ]);
  8447. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  8448. {
  8449. requestId: "permission-1",
  8450. sessionId: "session-existing",
  8451. agentName: "mavis",
  8452. toolName: "bash",
  8453. reason: "Run tests",
  8454. allowAlwaysSupported: true,
  8455. },
  8456. ]);
  8457. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8458. id: "question-1",
  8459. title: "Choose",
  8460. steps: [
  8461. {
  8462. id: "step-1",
  8463. question: "Proceed?",
  8464. selectionMode: "single",
  8465. options: [
  8466. { id: "yes", label: "Yes" },
  8467. { id: "no", label: "No" },
  8468. ],
  8469. },
  8470. ],
  8471. });
  8472. const app = createTuiApp({
  8473. runtime,
  8474. terminal,
  8475. version: "0.1.0",
  8476. workspaceDir: "/workspace",
  8477. });
  8478. await app.ready;
  8479. await app.submit("/resume session-existing");
  8480. expect(app.transcript.snapshot()).toEqual(
  8481. expect.arrayContaining([
  8482. expect.objectContaining({ kind: "permission", status: "blocked" }),
  8483. expect.objectContaining({ kind: "question", status: "blocked" }),
  8484. ]),
  8485. );
  8486. expect(app.transcript.get("permission:permission-1")).toMatchObject({
  8487. title: "bash",
  8488. content: "Run tests",
  8489. });
  8490. expect(
  8491. app.transcript.get("permission:permission-1")?.content,
  8492. ).not.toContain("decision panel");
  8493. expect(app.transcript.get("permission:permission-1")?.content).not.toMatch(
  8494. /\/(?:allow|always|deny)\b/u,
  8495. );
  8496. expect(app.transcript.get("question:question-1")?.content).toBe("");
  8497. await app.submit("/q1 1");
  8498. expect(runtime.replyQuestionnaire).not.toHaveBeenCalled();
  8499. expect(app.tui.hasOverlay()).toBe(false);
  8500. expect(app.interaction.isActive()).toBe(true);
  8501. expect(terminal.mouseTracking).toBe(false);
  8502. await app.submit("/allow");
  8503. await app.submit("/q1 1");
  8504. await app.submit("/status");
  8505. expect(runtime.replyPermission).toHaveBeenCalledWith(
  8506. "mavis",
  8507. "permission-1",
  8508. "allowOnce",
  8509. );
  8510. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  8511. "mavis",
  8512. "question-1",
  8513. [
  8514. {
  8515. stepId: "step-1",
  8516. selectedOptionIds: ["yes"],
  8517. selectedOther: false,
  8518. },
  8519. ],
  8520. );
  8521. expect(terminal.mouseTracking).toBe(false);
  8522. expect(app.transcript.get("question:question-1")).toMatchObject({
  8523. status: "resolved",
  8524. title: "Answers sent",
  8525. content: "Proceed? Yes",
  8526. });
  8527. expect(app.interaction.current()).toBeDefined();
  8528. expect(app.tui.render(80).join("\n")).toContain("MCode status");
  8529. expect(app.transcript.snapshot()).not.toEqual(
  8530. expect.arrayContaining([
  8531. expect.objectContaining({
  8532. kind: "inspection",
  8533. inspection: expect.objectContaining({
  8534. visualization: { kind: "status" },
  8535. }),
  8536. }),
  8537. ]),
  8538. );
  8539. });
  8540. it("does not let a stale permission response hide a newer decision surface", async () => {
  8541. const terminal = new FakeTerminal();
  8542. const runtime = createRuntime();
  8543. vi.mocked(runtime.listSessions).mockResolvedValue([
  8544. {
  8545. sessionId: "session-race",
  8546. title: "Decision race",
  8547. workspaceDir: "/workspace",
  8548. },
  8549. ]);
  8550. const firstPermission = {
  8551. requestId: "permission-first",
  8552. sessionId: "session-race",
  8553. agentName: "mavis",
  8554. toolName: "bash",
  8555. reason: "First request",
  8556. allowAlwaysSupported: true,
  8557. };
  8558. const secondPermission = {
  8559. requestId: "permission-second",
  8560. sessionId: "session-race",
  8561. agentName: "mavis",
  8562. toolName: "write_file",
  8563. reason: "Newer request",
  8564. allowAlwaysSupported: false,
  8565. };
  8566. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  8567. firstPermission,
  8568. ]);
  8569. let finishReply: ((value: boolean) => void) | undefined;
  8570. vi.mocked(runtime.replyPermission).mockImplementation(
  8571. async () =>
  8572. await new Promise<boolean>((resolve) => {
  8573. finishReply = resolve;
  8574. }),
  8575. );
  8576. let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  8577. vi.mocked(runtime.watchEvents).mockImplementation(
  8578. async function* watchEvents(signal) {
  8579. const event = await new Promise<TuiRuntimeEvent | undefined>(
  8580. (resolve) => {
  8581. emitEvent = resolve;
  8582. signal.addEventListener("abort", () => resolve(undefined), {
  8583. once: true,
  8584. });
  8585. },
  8586. );
  8587. if (event) yield event;
  8588. await new Promise<void>((resolve) => {
  8589. signal.addEventListener("abort", resolve, { once: true });
  8590. });
  8591. },
  8592. );
  8593. const app = createTuiApp({
  8594. runtime,
  8595. terminal,
  8596. version: "0.1.0",
  8597. workspaceDir: "/workspace",
  8598. });
  8599. app.start();
  8600. await app.ready;
  8601. await app.submit("/resume session-race");
  8602. const resolving = app.submit("/allow");
  8603. await vi.waitFor(() => expect(runtime.replyPermission).toHaveBeenCalled());
  8604. await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
  8605. emitEvent?.(
  8606. runtimeEvent({
  8607. type: "permission.ask",
  8608. timestamp: Date.now(),
  8609. source: "test",
  8610. payload: secondPermission,
  8611. }),
  8612. );
  8613. await vi.waitFor(() =>
  8614. expect(app.tui.render(80).join("\n")).toContain("Newer request"),
  8615. );
  8616. finishReply?.(true);
  8617. await resolving;
  8618. const rendered = app.tui.render(80).join("\n");
  8619. expect(rendered).toContain("Write file");
  8620. expect(rendered).toContain("Newer request");
  8621. expect(runtime.replyPermission).toHaveBeenCalledTimes(1);
  8622. await app.stop();
  8623. });
  8624. it("closes a permission that another surface resolved before the reply arrived", async () => {
  8625. const terminal = new FakeTerminal();
  8626. const runtime = createRuntime();
  8627. const permission = {
  8628. requestId: "permission-stale",
  8629. sessionId: "session-permission-stale",
  8630. agentName: "mavis",
  8631. toolName: "bash",
  8632. reason: "Run tests",
  8633. allowAlwaysSupported: true,
  8634. };
  8635. vi.mocked(runtime.listSessions).mockResolvedValue([
  8636. {
  8637. sessionId: "session-permission-stale",
  8638. title: "Permission race",
  8639. workspaceDir: "/workspace",
  8640. },
  8641. ]);
  8642. vi.mocked(runtime.listPendingPermissions)
  8643. .mockResolvedValueOnce([permission])
  8644. .mockResolvedValue([]);
  8645. vi.mocked(runtime.replyPermission).mockResolvedValue(false);
  8646. const app = createTuiApp({
  8647. runtime,
  8648. terminal,
  8649. version: "0.1.0",
  8650. workspaceDir: "/workspace",
  8651. });
  8652. await app.ready;
  8653. await app.submit("/resume session-permission-stale");
  8654. await app.submit("/allow");
  8655. expect(app.transcript.get("permission:permission-stale")).toMatchObject({
  8656. status: "resolved",
  8657. detail: "Resolved on another surface.",
  8658. });
  8659. expect(app.interaction.isActive()).toBe(false);
  8660. });
  8661. it("keeps an option-only questionnaire pending after an invalid slash answer", async () => {
  8662. const terminal = new FakeTerminal();
  8663. const runtime = createRuntime();
  8664. vi.mocked(runtime.listSessions).mockResolvedValue([
  8665. {
  8666. sessionId: "session-questionnaire",
  8667. title: "Questionnaire session",
  8668. workspaceDir: "/workspace",
  8669. },
  8670. ]);
  8671. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8672. id: "question-options-only",
  8673. title: "Choose",
  8674. steps: [
  8675. {
  8676. id: "channel",
  8677. question: "Choose a release channel",
  8678. selectionMode: "single",
  8679. options: [
  8680. { id: "preview", label: "Preview" },
  8681. { id: "stable", label: "Stable" },
  8682. ],
  8683. allowOther: false,
  8684. },
  8685. ],
  8686. });
  8687. const app = createTuiApp({
  8688. runtime,
  8689. terminal,
  8690. version: "0.1.0",
  8691. workspaceDir: "/workspace",
  8692. });
  8693. await app.ready;
  8694. await app.submit("/resume session-questionnaire");
  8695. await app.submit("/q1 nightly");
  8696. expect(runtime.replyQuestionnaire).not.toHaveBeenCalled();
  8697. expect(app.transcript.get("question:question-options-only")).toMatchObject({
  8698. status: "blocked",
  8699. });
  8700. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  8701. kind: "warning",
  8702. content:
  8703. "/q1 accepts only listed options. Use an option number, ID, or label.",
  8704. });
  8705. await app.submit("/q1 1");
  8706. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  8707. "mavis",
  8708. "question-options-only",
  8709. [
  8710. {
  8711. stepId: "channel",
  8712. selectedOptionIds: ["preview"],
  8713. selectedOther: false,
  8714. },
  8715. ],
  8716. );
  8717. });
  8718. it("shows the first AskUser answer immediately while later questions remain pending", async () => {
  8719. const terminal = new FakeTerminal();
  8720. const runtime = createRuntime();
  8721. vi.mocked(runtime.listSessions).mockResolvedValue([
  8722. {
  8723. sessionId: "session-multi-question",
  8724. title: "Multi question",
  8725. workspaceDir: "/workspace",
  8726. },
  8727. ]);
  8728. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8729. id: "question-multi-step",
  8730. title: "Preferences",
  8731. steps: [
  8732. {
  8733. id: "animal",
  8734. question: "Favorite animal?",
  8735. selectionMode: "single",
  8736. options: [
  8737. { id: "cat", label: "Cat" },
  8738. { id: "dog", label: "Dog" },
  8739. ],
  8740. },
  8741. {
  8742. id: "color",
  8743. question: "Favorite color?",
  8744. selectionMode: "single",
  8745. options: [
  8746. { id: "blue", label: "Blue" },
  8747. { id: "green", label: "Green" },
  8748. ],
  8749. },
  8750. ],
  8751. });
  8752. const app = createTuiApp({
  8753. runtime,
  8754. terminal,
  8755. version: "0.1.0",
  8756. workspaceDir: "/workspace",
  8757. });
  8758. await app.ready;
  8759. app.start();
  8760. await app.submit("/resume session-multi-question");
  8761. const picker = app.interaction.current();
  8762. expect(picker).toBeDefined();
  8763. terminal.input?.("1");
  8764. expect(runtime.replyQuestionnaire).not.toHaveBeenCalled();
  8765. expect(app.interaction.current()).toBe(picker);
  8766. expect(app.transcript.get("question:question-multi-step")).toMatchObject({
  8767. status: "blocked",
  8768. content: "Favorite animal? Cat",
  8769. detail: "1 of 2 answered",
  8770. });
  8771. const rendered = app.tui.render(80).join("\n");
  8772. expect(rendered).toContain("Answers so far");
  8773. expect(rendered).toContain("Favorite animal? Cat");
  8774. expect(rendered).toContain("Favorite color?");
  8775. terminal.input?.("\u001B[B");
  8776. expect(app.tui.render(80).join("\n")).toContain("› 2 Green");
  8777. terminal.input?.("\r");
  8778. await vi.waitFor(() => {
  8779. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  8780. "mavis",
  8781. "question-multi-step",
  8782. [
  8783. {
  8784. stepId: "animal",
  8785. selectedOptionIds: ["cat"],
  8786. selectedOther: false,
  8787. },
  8788. {
  8789. stepId: "color",
  8790. selectedOptionIds: ["green"],
  8791. selectedOther: false,
  8792. },
  8793. ],
  8794. );
  8795. });
  8796. await app.stop();
  8797. });
  8798. it("sends the selected answer immediately and refreshes the Agent continuation", async () => {
  8799. const terminal = new FakeTerminal();
  8800. const runtime = createRuntime();
  8801. vi.mocked(runtime.listSessions).mockResolvedValue([
  8802. {
  8803. sessionId: "session-review",
  8804. title: "Questionnaire review",
  8805. workspaceDir: "/workspace",
  8806. },
  8807. ]);
  8808. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8809. id: "question-review",
  8810. title: "Release setup",
  8811. steps: [
  8812. {
  8813. id: "channel",
  8814. question: "Choose a channel",
  8815. selectionMode: "single",
  8816. options: [
  8817. { id: "preview", label: "Preview" },
  8818. { id: "stable", label: "Stable" },
  8819. ],
  8820. },
  8821. ],
  8822. });
  8823. const previousMessages = [
  8824. {
  8825. id: "previous-question-answer",
  8826. role: "user" as const,
  8827. content: [
  8828. "<questionnaire-response>",
  8829. " <requestId>question-previous</requestId>",
  8830. " <answers />",
  8831. "</questionnaire-response>",
  8832. "",
  8833. "Q: Choose a channel",
  8834. "A: Preview",
  8835. ].join("\n"),
  8836. },
  8837. ];
  8838. vi.mocked(runtime.getMessages).mockResolvedValue(previousMessages);
  8839. const app = createTuiApp({
  8840. runtime,
  8841. terminal,
  8842. version: "0.1.0",
  8843. workspaceDir: "/workspace",
  8844. });
  8845. let releaseReply: ((result: boolean) => void) | undefined;
  8846. let releaseContinuation: (() => void) | undefined;
  8847. vi.mocked(runtime.replyQuestionnaire).mockImplementation(
  8848. async () =>
  8849. await new Promise<boolean>((resolve) => {
  8850. releaseReply = resolve;
  8851. }),
  8852. );
  8853. vi.mocked(runtime.watchEvents).mockImplementation(
  8854. async function* watchEvents(signal) {
  8855. await new Promise<void>((resolve) => {
  8856. releaseContinuation = resolve;
  8857. signal.addEventListener("abort", resolve, { once: true });
  8858. });
  8859. if (signal.aborted) return;
  8860. yield runtimeEvent({
  8861. type: "session.start",
  8862. timestamp: Date.now(),
  8863. source: "runtime",
  8864. payload: {
  8865. sessionId: "session-review",
  8866. turnId: "turn-questionnaire-continuation",
  8867. },
  8868. });
  8869. yield runtimeEvent({
  8870. type: "session.finish",
  8871. timestamp: Date.now(),
  8872. source: "runtime",
  8873. payload: {
  8874. sessionId: "session-review",
  8875. turnId: "turn-questionnaire-continuation",
  8876. },
  8877. });
  8878. },
  8879. );
  8880. app.start();
  8881. await app.ready;
  8882. await app.submit("/resume session-review");
  8883. expect(app.tui.hasOverlay()).toBe(false);
  8884. expect(app.interaction.isActive()).toBe(true);
  8885. terminal.input?.("2");
  8886. await vi.waitFor(() =>
  8887. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  8888. "mavis",
  8889. "question-review",
  8890. [
  8891. {
  8892. stepId: "channel",
  8893. selectedOptionIds: ["stable"],
  8894. selectedOther: false,
  8895. },
  8896. ],
  8897. ),
  8898. );
  8899. expect(app.tui.hasOverlay()).toBe(false);
  8900. expect(app.transcript.get("question:question-review")).toMatchObject({
  8901. status: "pending",
  8902. detail: "Sending your answer…",
  8903. });
  8904. releaseReply?.(true);
  8905. await vi.waitFor(() =>
  8906. expect(app.transcript.get("question:question-review")).toMatchObject({
  8907. status: "resolved",
  8908. detail: "Answer sent · MCode is continuing…",
  8909. }),
  8910. );
  8911. vi.mocked(runtime.getMessages).mockResolvedValue([
  8912. ...previousMessages,
  8913. {
  8914. id: "assistant-after-question",
  8915. role: "assistant",
  8916. content: "Agent continued after your answer.",
  8917. },
  8918. ]);
  8919. releaseContinuation?.();
  8920. await vi.waitFor(() =>
  8921. expect(
  8922. app.transcript
  8923. .snapshot()
  8924. .map((cell) => cell.content)
  8925. .join("\n"),
  8926. ).toContain("Agent continued after your answer."),
  8927. );
  8928. expect(app.transcript.get("question:question-review")).toMatchObject({
  8929. kind: "question",
  8930. status: "resolved",
  8931. title: "Answers sent",
  8932. content: "Choose a channel Stable",
  8933. detail: undefined,
  8934. });
  8935. expect(
  8936. app.transcript
  8937. .snapshot()
  8938. .filter((cell) => cell.kind === "question")
  8939. .map((cell) => cell.content),
  8940. ).toEqual(["Choose a channel Preview", "Choose a channel Stable"]);
  8941. expect(app.tui.render(80).join("\n")).not.toContain("Thinking · Message");
  8942. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
  8943. await app.stop();
  8944. });
  8945. it("redraws after a delayed questionnaire reply resolves", async () => {
  8946. const terminal = new FakeTerminal();
  8947. const runtime = createRuntime();
  8948. vi.mocked(runtime.listSessions).mockResolvedValue([
  8949. {
  8950. sessionId: "session-delayed-reply",
  8951. title: "Delayed questionnaire reply",
  8952. workspaceDir: "/workspace",
  8953. },
  8954. ]);
  8955. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8956. id: "question-delayed-reply",
  8957. steps: [
  8958. {
  8959. id: "channel",
  8960. question: "Choose a channel",
  8961. selectionMode: "single",
  8962. options: [{ id: "preview", label: "Preview" }],
  8963. },
  8964. ],
  8965. });
  8966. let finishReply: ((result: boolean) => void) | undefined;
  8967. vi.mocked(runtime.replyQuestionnaire).mockImplementation(
  8968. async () =>
  8969. await new Promise<boolean>((resolve) => {
  8970. finishReply = resolve;
  8971. }),
  8972. );
  8973. const app = createTuiApp({
  8974. runtime,
  8975. terminal,
  8976. version: "0.1.0",
  8977. workspaceDir: "/workspace",
  8978. });
  8979. app.start();
  8980. await app.ready;
  8981. await app.submit("/resume session-delayed-reply");
  8982. terminal.input?.("1");
  8983. await vi.waitFor(() =>
  8984. expect(runtime.replyQuestionnaire).toHaveBeenCalledTimes(1),
  8985. );
  8986. expect(app.tui.hasOverlay()).toBe(false);
  8987. const writesBeforeResolution = terminal.writes.length;
  8988. finishReply?.(true);
  8989. await vi.waitFor(() =>
  8990. expect(
  8991. app.transcript.get("question:question-delayed-reply"),
  8992. ).toMatchObject({
  8993. status: "resolved",
  8994. detail: "Answer sent · MCode is continuing…",
  8995. }),
  8996. );
  8997. await vi.waitFor(() =>
  8998. expect(terminal.writes.length).toBeGreaterThan(writesBeforeResolution),
  8999. );
  9000. await app.stop();
  9001. });
  9002. it("keeps the questionnaire interactive when the Runtime cannot start its continuation", async () => {
  9003. const terminal = new FakeTerminal();
  9004. const runtime = createRuntime();
  9005. vi.mocked(runtime.listSessions).mockResolvedValue([
  9006. {
  9007. sessionId: "session-retry-questionnaire",
  9008. title: "Retry questionnaire",
  9009. workspaceDir: "/workspace",
  9010. },
  9011. ]);
  9012. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9013. id: "question-retry",
  9014. title: "Choose a channel",
  9015. steps: [
  9016. {
  9017. id: "channel",
  9018. question: "Choose a channel",
  9019. selectionMode: "single",
  9020. options: [{ id: "preview", label: "Preview" }],
  9021. },
  9022. ],
  9023. });
  9024. vi.mocked(runtime.replyQuestionnaire).mockRejectedValue(
  9025. new Error(
  9026. "Questionnaire answer was saved, but the continuation could not start.",
  9027. ),
  9028. );
  9029. const app = createTuiApp({
  9030. runtime,
  9031. terminal,
  9032. version: "0.1.0",
  9033. workspaceDir: "/workspace",
  9034. });
  9035. app.start();
  9036. app.start();
  9037. await app.ready;
  9038. await app.submit("/resume session-retry-questionnaire");
  9039. terminal.input?.("1");
  9040. await vi.waitFor(() =>
  9041. expect(app.transcript.get("question:question-retry")).toMatchObject({
  9042. status: "blocked",
  9043. title: "Choose a channel",
  9044. detail: "Answer could not be sent · retry",
  9045. }),
  9046. );
  9047. expect(app.interaction.isActive()).toBe(true);
  9048. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  9049. kind: "error",
  9050. content:
  9051. "Couldn't send your answers: Questionnaire answer was saved, but the continuation could not start. Retry. The question remains open.",
  9052. });
  9053. await app.stop();
  9054. });
  9055. it("redraws after a delayed questionnaire dismissal resolves", async () => {
  9056. const terminal = new FakeTerminal();
  9057. const runtime = createRuntime();
  9058. vi.mocked(runtime.listSessions).mockResolvedValue([
  9059. {
  9060. sessionId: "session-delayed-dismiss",
  9061. title: "Delayed questionnaire dismissal",
  9062. workspaceDir: "/workspace",
  9063. },
  9064. ]);
  9065. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9066. id: "question-delayed-dismiss",
  9067. steps: [{ id: "confirmation", question: "Continue?" }],
  9068. });
  9069. let finishDismiss: ((result: boolean) => void) | undefined;
  9070. vi.mocked(runtime.dismissQuestionnaire).mockImplementation(
  9071. async () =>
  9072. await new Promise<boolean>((resolve) => {
  9073. finishDismiss = resolve;
  9074. }),
  9075. );
  9076. const app = createTuiApp({
  9077. runtime,
  9078. terminal,
  9079. version: "0.1.0",
  9080. workspaceDir: "/workspace",
  9081. });
  9082. app.start();
  9083. await app.ready;
  9084. await app.submit("/resume session-delayed-dismiss");
  9085. const dismissing = app.submit("/ask-cancel");
  9086. await vi.waitFor(() =>
  9087. expect(runtime.dismissQuestionnaire).toHaveBeenCalledTimes(1),
  9088. );
  9089. const writesBeforeResolution = terminal.writes.length;
  9090. finishDismiss?.(true);
  9091. await dismissing;
  9092. expect(
  9093. app.transcript.get("question:question-delayed-dismiss"),
  9094. ).toMatchObject({
  9095. status: "resolved",
  9096. title: "Question dismissed",
  9097. content: "",
  9098. detail: undefined,
  9099. });
  9100. await vi.waitFor(() =>
  9101. expect(terminal.writes.length).toBeGreaterThan(writesBeforeResolution),
  9102. );
  9103. await app.stop();
  9104. });
  9105. it.each([
  9106. { keyName: "Escape", input: "\x1b" },
  9107. { keyName: "Ctrl-C", input: "\x03" },
  9108. ])(
  9109. "keeps AskUser focused while $keyName dismisses the pending questionnaire",
  9110. async ({ input }) => {
  9111. const terminal = new FakeTerminal();
  9112. const runtime = createRuntime();
  9113. vi.mocked(runtime.listSessions).mockResolvedValue([
  9114. {
  9115. sessionId: "session-escape-dismiss",
  9116. title: "Escape questionnaire dismissal",
  9117. workspaceDir: "/workspace",
  9118. },
  9119. ]);
  9120. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9121. id: "question-escape-dismiss",
  9122. steps: [
  9123. {
  9124. id: "channel",
  9125. question: "Choose a channel",
  9126. selectionMode: "single",
  9127. options: [{ id: "preview", label: "Preview" }],
  9128. },
  9129. ],
  9130. });
  9131. let finishDismiss: ((result: boolean) => void) | undefined;
  9132. vi.mocked(runtime.dismissQuestionnaire).mockImplementation(
  9133. async () =>
  9134. await new Promise<boolean>((resolve) => {
  9135. finishDismiss = resolve;
  9136. }),
  9137. );
  9138. const app = createTuiApp({
  9139. runtime,
  9140. terminal,
  9141. version: "0.1.0",
  9142. workspaceDir: "/workspace",
  9143. });
  9144. app.start();
  9145. await app.ready;
  9146. await app.submit("/resume session-escape-dismiss");
  9147. terminal.input?.(input);
  9148. if (input === "\x1b") {
  9149. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9150. "Cancel this question?",
  9151. );
  9152. terminal.input?.("\r");
  9153. }
  9154. await vi.waitFor(() =>
  9155. expect(runtime.dismissQuestionnaire).toHaveBeenCalledWith(
  9156. "mavis",
  9157. "question-escape-dismiss",
  9158. ),
  9159. );
  9160. expect(app.interaction.isActive()).toBe(true);
  9161. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9162. "Closing question",
  9163. );
  9164. expect(
  9165. app.state.snapshot().sessions.get("session-escape-dismiss")?.attention
  9166. .question,
  9167. ).toBe(true);
  9168. finishDismiss?.(true);
  9169. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  9170. expect(
  9171. app.transcript.get("question:question-escape-dismiss"),
  9172. ).toMatchObject({
  9173. status: "resolved",
  9174. title: "Question dismissed",
  9175. });
  9176. expect(
  9177. app.state.snapshot().sessions.get("session-escape-dismiss")?.attention
  9178. .question,
  9179. ).toBe(false);
  9180. expect(app.tui.render(80).join("\n")).not.toContain("Reply required");
  9181. await app.stop();
  9182. },
  9183. );
  9184. it("denies a pending permission explicitly and releases the blocked interaction", async () => {
  9185. const terminal = new FakeTerminal();
  9186. const runtime = createRuntime();
  9187. vi.mocked(runtime.listSessions).mockResolvedValue([
  9188. {
  9189. sessionId: "session-pending",
  9190. title: "Pending permission",
  9191. workspaceDir: "/workspace",
  9192. },
  9193. ]);
  9194. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  9195. {
  9196. requestId: "permission-pending",
  9197. sessionId: "session-pending",
  9198. agentName: "mavis",
  9199. toolName: "bash",
  9200. toolInput: "pnpm test",
  9201. ruleContents: ["Bash(pnpm test:*)"],
  9202. allowAlwaysSupported: true,
  9203. },
  9204. ]);
  9205. const app = createTuiApp({
  9206. runtime,
  9207. terminal,
  9208. version: "0.1.0",
  9209. workspaceDir: "/workspace",
  9210. });
  9211. app.start();
  9212. await app.ready;
  9213. await app.submit("/resume session-pending");
  9214. expect(app.tui.hasOverlay()).toBe(false);
  9215. expect(app.interaction.isActive()).toBe(true);
  9216. terminal.input?.("3");
  9217. terminal.input?.("\r");
  9218. await vi.waitFor(() =>
  9219. expect(runtime.replyPermission).toHaveBeenCalledWith(
  9220. "mavis",
  9221. "permission-pending",
  9222. "deny",
  9223. ),
  9224. );
  9225. expect(app.tui.hasOverlay()).toBe(false);
  9226. expect(app.interaction.isActive()).toBe(false);
  9227. expect(app.transcript.get("permission:permission-pending")).toMatchObject({
  9228. status: "resolved",
  9229. detail: "Denied · bash",
  9230. });
  9231. expect(app.tui.render(80).join("\n")).not.toContain("Approval required");
  9232. await app.stop();
  9233. });
  9234. it("resolves a regular inline permission without clearing the terminal viewport", async () => {
  9235. const terminal = new FakeTerminal();
  9236. terminal.rows = 8;
  9237. const runtime = createRuntime();
  9238. vi.mocked(runtime.listSessions).mockResolvedValue([
  9239. {
  9240. sessionId: "session-permission-render",
  9241. title: "Permission render",
  9242. workspaceDir: "/workspace",
  9243. },
  9244. ]);
  9245. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  9246. {
  9247. requestId: "permission-render",
  9248. sessionId: "session-permission-render",
  9249. agentName: "mavis",
  9250. toolName: "bash",
  9251. toolInput: "pnpm test",
  9252. reason: "Run focused tests",
  9253. allowAlwaysSupported: true,
  9254. },
  9255. ]);
  9256. const app = createTuiApp({
  9257. runtime,
  9258. terminal,
  9259. version: "0.2.6",
  9260. workspaceDir: "/workspace",
  9261. tuiMode: "regular",
  9262. });
  9263. app.start();
  9264. await app.ready;
  9265. await app.submit("/resume session-permission-render");
  9266. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  9267. app.tui.renderNow();
  9268. terminal.writes.length = 0;
  9269. terminal.input?.("\r");
  9270. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  9271. await vi.waitFor(() => expect(terminal.writes.length).toBeGreaterThan(0));
  9272. expect(runtime.replyPermission).toHaveBeenCalledWith(
  9273. "mavis",
  9274. "permission-render",
  9275. "allowOnce",
  9276. );
  9277. expect(app.transcript.get("permission:permission-render")).toMatchObject({
  9278. status: "resolved",
  9279. detail: "Allowed for this conversation · bash",
  9280. });
  9281. expect(terminal.writes.join("")).not.toContain("\x1b[2J");
  9282. expect(terminal.writes.join("")).not.toContain("\x1b[3J");
  9283. await app.stop();
  9284. });
  9285. it("keeps a submission retryable when a pending decision blocks admission", async () => {
  9286. const terminal = new FakeTerminal();
  9287. const runtime = createRuntime();
  9288. vi.mocked(runtime.listSessions).mockResolvedValue([
  9289. {
  9290. sessionId: "session-draft-blocked",
  9291. title: "Pending decision",
  9292. workspaceDir: "/workspace",
  9293. },
  9294. ]);
  9295. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  9296. {
  9297. requestId: "permission-draft-blocked",
  9298. sessionId: "session-draft-blocked",
  9299. agentName: "mavis",
  9300. toolName: "bash",
  9301. allowAlwaysSupported: true,
  9302. },
  9303. ]);
  9304. const app = createTuiApp({
  9305. runtime,
  9306. terminal,
  9307. version: "0.1.0",
  9308. workspaceDir: "/workspace",
  9309. });
  9310. app.start();
  9311. await app.ready;
  9312. await app.submit("/resume session-draft-blocked");
  9313. app.editor.setText("Keep this draft for later");
  9314. app.editor.handleInput("\r");
  9315. await vi.waitFor(() => expect(app.editor.getText()).toBe(""));
  9316. expect(runtime.sendMessage).not.toHaveBeenCalled();
  9317. expect(app.tui.render(80).join("\n")).toContain("Approval required");
  9318. expect(app.tui.render(80).join("\n")).not.toContain("Message · Enter");
  9319. await app.stop();
  9320. });
  9321. it("keeps a pending questionnaire when Runtime rejects dismissal", async () => {
  9322. const terminal = new FakeTerminal();
  9323. const runtime = createRuntime();
  9324. vi.mocked(runtime.listSessions).mockResolvedValue([
  9325. {
  9326. sessionId: "session-existing",
  9327. title: "Existing session",
  9328. workspaceDir: "/workspace",
  9329. },
  9330. ]);
  9331. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9332. id: "question-rejected",
  9333. steps: [{ id: "step-1", question: "Proceed?" }],
  9334. });
  9335. vi.mocked(runtime.dismissQuestionnaire).mockResolvedValue(false);
  9336. const app = createTuiApp({
  9337. runtime,
  9338. terminal,
  9339. version: "0.1.0",
  9340. workspaceDir: "/workspace",
  9341. });
  9342. await app.ready;
  9343. await app.submit("/resume session-existing");
  9344. await app.submit("/ask-cancel");
  9345. expect(app.transcript.get("question:question-rejected")).toMatchObject({
  9346. status: "blocked",
  9347. });
  9348. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  9349. kind: "error",
  9350. content: "Couldn't dismiss this question. It remains open; retry.",
  9351. });
  9352. });
  9353. it("restores the questionnaire panel when an Escape dismissal request fails", async () => {
  9354. const runtime = createRuntime();
  9355. vi.mocked(runtime.listSessions).mockResolvedValue([
  9356. {
  9357. sessionId: "session-dismiss-retry",
  9358. title: "Dismiss retry",
  9359. workspaceDir: "/workspace",
  9360. },
  9361. ]);
  9362. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9363. id: "question-dismiss-retry",
  9364. steps: [
  9365. {
  9366. id: "step-1",
  9367. question: "Proceed?",
  9368. selectionMode: "single",
  9369. options: [{ id: "yes", label: "Yes" }],
  9370. },
  9371. ],
  9372. });
  9373. vi.mocked(runtime.dismissQuestionnaire).mockRejectedValue(
  9374. new Error("connection lost"),
  9375. );
  9376. const app = createTuiApp({
  9377. runtime,
  9378. terminal: new FakeTerminal(),
  9379. version: "0.1.0",
  9380. workspaceDir: "/workspace",
  9381. });
  9382. await app.ready;
  9383. await app.submit("/resume session-dismiss-retry");
  9384. app.interaction.current()?.handleInput("\u001b");
  9385. app.interaction.current()?.handleInput("\r");
  9386. await vi.waitFor(() =>
  9387. expect(runtime.dismissQuestionnaire).toHaveBeenCalledOnce(),
  9388. );
  9389. await vi.waitFor(() => {
  9390. const panel = app.interaction.current();
  9391. expect(panel).toBeDefined();
  9392. expect(panel?.render(80).join("\n")).toContain("Ask");
  9393. });
  9394. expect(app.transcript.get("question:question-dismiss-retry")).toMatchObject(
  9395. {
  9396. status: "blocked",
  9397. },
  9398. );
  9399. });
  9400. it("settles a questionnaire dismissal that already reached a terminal Runtime state", async () => {
  9401. const terminal = new FakeTerminal();
  9402. const runtime = createRuntime();
  9403. vi.mocked(runtime.listSessions).mockResolvedValue([
  9404. {
  9405. sessionId: "session-terminal-dismiss",
  9406. title: "Terminal dismissal",
  9407. workspaceDir: "/workspace",
  9408. },
  9409. ]);
  9410. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9411. id: "question-terminal-dismiss",
  9412. steps: [{ id: "step-1", question: "Proceed?" }],
  9413. });
  9414. vi.mocked(runtime.dismissQuestionnaire).mockRejectedValue(
  9415. Object.assign(new Error("already superseded"), {
  9416. status: 410,
  9417. code: "QUESTIONNAIRE_NOT_PENDING",
  9418. }),
  9419. );
  9420. const app = createTuiApp({
  9421. runtime,
  9422. terminal,
  9423. version: "0.1.0",
  9424. workspaceDir: "/workspace",
  9425. });
  9426. await app.ready;
  9427. await app.submit("/resume session-terminal-dismiss");
  9428. await app.submit("/ask-cancel");
  9429. expect(
  9430. app.transcript.get("question:question-terminal-dismiss"),
  9431. ).toMatchObject({
  9432. status: "resolved",
  9433. title: "Question closed",
  9434. detail: "Question is no longer pending.",
  9435. });
  9436. expect(app.interaction.isActive()).toBe(false);
  9437. });
  9438. it("projects live Desktop permission events into the transcript", async () => {
  9439. const terminal = new FakeTerminal();
  9440. const runtime = createRuntime();
  9441. vi.mocked(runtime.watchEvents).mockImplementation(
  9442. async function* watchEvents() {
  9443. yield runtimeEvent({
  9444. type: "permission.ask",
  9445. timestamp: 100,
  9446. source: "runtime",
  9447. payload: {
  9448. requestId: "permission-live",
  9449. sessionId: "session-1",
  9450. agentName: "mavis",
  9451. toolName: "bash",
  9452. toolDescription: "Run a shell command",
  9453. reason: "Run checks",
  9454. ruleContents: ["Bash(pnpm test:*)"],
  9455. allowAlwaysSupported: true,
  9456. },
  9457. });
  9458. },
  9459. );
  9460. const app = createTuiApp({
  9461. runtime,
  9462. terminal,
  9463. version: "0.1.0",
  9464. workspaceDir: "/workspace",
  9465. });
  9466. await app.ready;
  9467. await app.submit("Start the current session");
  9468. await app.submit("/transcript");
  9469. expect(app.surfaceHost.getActiveSurface()).toEqual({
  9470. kind: "feature",
  9471. id: "transcript",
  9472. });
  9473. app.start();
  9474. await vi.waitFor(() =>
  9475. expect(app.transcript.get("permission:permission-live")).toMatchObject({
  9476. kind: "permission",
  9477. status: "blocked",
  9478. content: expect.stringContaining("Run checks"),
  9479. }),
  9480. );
  9481. expect(app.transcript.get("permission:permission-live")).toMatchObject({
  9482. title: "bash",
  9483. content: "Run checks",
  9484. });
  9485. expect(
  9486. app.transcript.get("permission:permission-live")?.content,
  9487. ).not.toContain("Rules:");
  9488. expect(app.surfaceHost.getActiveSurface()).toEqual({
  9489. kind: "chat",
  9490. id: "chat",
  9491. });
  9492. await app.submit("/allow");
  9493. expect(app.surfaceHost.getActiveSurface()).toEqual({
  9494. kind: "feature",
  9495. id: "transcript",
  9496. });
  9497. await app.stop();
  9498. });
  9499. it("ignores Desktop interaction events until their session is active", async () => {
  9500. const terminal = new FakeTerminal();
  9501. const runtime = createRuntime();
  9502. let resolveEventsDelivered: (() => void) | undefined;
  9503. const eventsDelivered = new Promise<void>((resolve) => {
  9504. resolveEventsDelivered = resolve;
  9505. });
  9506. vi.mocked(runtime.watchEvents).mockImplementation(
  9507. async function* watchEvents(signal) {
  9508. yield runtimeEvent({
  9509. type: "permission.ask",
  9510. timestamp: 100,
  9511. source: "runtime",
  9512. payload: {
  9513. requestId: "permission-other-session",
  9514. sessionId: "session-other",
  9515. agentName: "mavis",
  9516. toolName: "bash",
  9517. },
  9518. });
  9519. yield runtimeEvent({
  9520. type: "questionnaire.ask",
  9521. timestamp: 101,
  9522. source: "runtime",
  9523. payload: {
  9524. sessionId: "session-other",
  9525. agentName: "mavis",
  9526. request: {
  9527. id: "question-other-session",
  9528. steps: [
  9529. { id: "step-1", question: "Proceed?", selectionMode: "single" },
  9530. ],
  9531. },
  9532. },
  9533. });
  9534. resolveEventsDelivered?.();
  9535. await new Promise<void>((resolve) => {
  9536. signal.addEventListener("abort", () => resolve(), { once: true });
  9537. });
  9538. },
  9539. );
  9540. const app = createTuiApp({
  9541. runtime,
  9542. terminal,
  9543. version: "0.1.0",
  9544. workspaceDir: "/workspace",
  9545. });
  9546. app.start();
  9547. await app.ready;
  9548. await eventsDelivered;
  9549. expect(
  9550. app.transcript.get("permission:permission-other-session"),
  9551. ).toBeUndefined();
  9552. expect(
  9553. app.transcript.get("question:question-other-session"),
  9554. ).toBeUndefined();
  9555. expect(
  9556. app.state.snapshot().sessions.get("session-other")?.interactions
  9557. .permission?.requestId,
  9558. ).toBe("permission-other-session");
  9559. expect(
  9560. app.state.snapshot().sessions.get("session-other")?.interactions
  9561. .questionnaire?.request.id,
  9562. ).toBe("question-other-session");
  9563. await app.stop();
  9564. });
  9565. it("surfaces only descendant permissions while keeping explicit Deny separate from Stop", async () => {
  9566. const terminal = new FakeTerminal();
  9567. const runtime = createRuntime();
  9568. const rootSession = {
  9569. sessionId: "session-root",
  9570. title: "Root session",
  9571. workspaceDir: "/workspace",
  9572. status: "started",
  9573. };
  9574. vi.mocked(runtime.listSessions).mockResolvedValue([rootSession]);
  9575. vi.mocked(runtime.getSession).mockResolvedValue(rootSession);
  9576. vi.mocked(runtime.getDelegationSnapshot).mockResolvedValue({
  9577. schemaVersion: 1,
  9578. rootSessionId: "session-root",
  9579. members: [
  9580. {
  9581. sessionId: "session-child",
  9582. parentSessionId: "session-root",
  9583. agentName: "worker",
  9584. task: "Delegate nested work",
  9585. status: "running",
  9586. },
  9587. {
  9588. sessionId: "session-grandchild",
  9589. parentSessionId: "session-child",
  9590. agentName: "verifier",
  9591. task: "Verify the result",
  9592. status: "running",
  9593. },
  9594. ],
  9595. });
  9596. vi.mocked(runtime.getActiveRun).mockImplementation(
  9597. async (sessionId: string) => ({
  9598. schemaVersion: 1,
  9599. sessionId,
  9600. state:
  9601. sessionId === rootSession.sessionId ? "decision-blocked" : "running",
  9602. turnId:
  9603. sessionId === rootSession.sessionId
  9604. ? "turn-root"
  9605. : `turn-${sessionId}`,
  9606. actions: { steer: false },
  9607. }),
  9608. );
  9609. const deniedPermissionIds = new Set<string>();
  9610. vi.mocked(runtime.replyPermission).mockImplementation(
  9611. async (_agentName, requestId) => {
  9612. deniedPermissionIds.add(requestId);
  9613. return true;
  9614. },
  9615. );
  9616. vi.mocked(runtime.listPendingPermissions).mockImplementation(async () =>
  9617. deniedPermissionIds.has("permission-grandchild")
  9618. ? [
  9619. {
  9620. requestId: "permission-unrelated-next",
  9621. sessionId: "session-unrelated",
  9622. agentName: "worker",
  9623. toolName: "bash",
  9624. reason: "Must remain hidden",
  9625. },
  9626. {
  9627. requestId: deniedPermissionIds.has("permission-child-next")
  9628. ? "permission-child-stop"
  9629. : "permission-child-next",
  9630. sessionId: "session-child",
  9631. agentName: "worker",
  9632. toolName: "read",
  9633. reason: deniedPermissionIds.has("permission-child-next")
  9634. ? "Wait for an explicit Stop"
  9635. : "Inspect the delegated output",
  9636. },
  9637. ]
  9638. : [],
  9639. );
  9640. vi.mocked(runtime.watchEvents).mockImplementation(
  9641. async function* watchEvents(signal) {
  9642. yield runtimeEvent({
  9643. type: "permission.ask",
  9644. timestamp: 100,
  9645. source: "runtime",
  9646. payload: {
  9647. requestId: "permission-unrelated",
  9648. sessionId: "session-unrelated",
  9649. agentName: "worker",
  9650. toolName: "bash",
  9651. reason: "Must stay hidden",
  9652. },
  9653. });
  9654. yield runtimeEvent({
  9655. type: "permission.ask",
  9656. timestamp: 101,
  9657. source: "runtime",
  9658. payload: {
  9659. requestId: "permission-grandchild",
  9660. sessionId: "session-grandchild",
  9661. agentName: "verifier",
  9662. toolName: "write",
  9663. reason: "Update the verification report",
  9664. allowAlwaysSupported: true,
  9665. },
  9666. });
  9667. await new Promise<void>((resolve) => {
  9668. signal.addEventListener("abort", resolve, { once: true });
  9669. });
  9670. },
  9671. );
  9672. const app = createTuiApp({
  9673. runtime,
  9674. terminal,
  9675. version: "0.1.0",
  9676. workspaceDir: "/workspace",
  9677. });
  9678. await app.ready;
  9679. await app.submit("/resume session-root");
  9680. vi.mocked(runtime.abortSession).mockClear();
  9681. vi.mocked(runtime.stopDelegation).mockClear();
  9682. app.start();
  9683. await vi.waitFor(() =>
  9684. expect(
  9685. app.transcript.get("permission:permission-grandchild"),
  9686. ).toMatchObject({
  9687. kind: "permission",
  9688. status: "blocked",
  9689. }),
  9690. );
  9691. expect(
  9692. app.transcript.get("permission:permission-unrelated"),
  9693. ).toBeUndefined();
  9694. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9695. "Update the verification report",
  9696. );
  9697. app.interaction.current()?.handleInput?.("3");
  9698. app.interaction.current()?.handleInput?.("\r");
  9699. await vi.waitFor(() =>
  9700. expect(runtime.replyPermission).toHaveBeenCalledWith(
  9701. "verifier",
  9702. "permission-grandchild",
  9703. "deny",
  9704. ),
  9705. );
  9706. expect(runtime.stopDelegation).not.toHaveBeenCalled();
  9707. expect(runtime.abortSession).not.toHaveBeenCalled();
  9708. await vi.waitFor(() =>
  9709. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9710. "Inspect the delegated output",
  9711. ),
  9712. );
  9713. expect(
  9714. app.transcript.get("permission:permission-unrelated-next"),
  9715. ).toBeUndefined();
  9716. terminal.input?.("\x1b");
  9717. await vi.waitFor(() =>
  9718. expect(runtime.replyPermission).toHaveBeenCalledWith(
  9719. "worker",
  9720. "permission-child-next",
  9721. "deny",
  9722. ),
  9723. );
  9724. expect(runtime.abortSession).not.toHaveBeenCalled();
  9725. expect(runtime.stopDelegation).not.toHaveBeenCalled();
  9726. await vi.waitFor(() =>
  9727. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9728. "Wait for an explicit Stop",
  9729. ),
  9730. );
  9731. terminal.input?.("\x03");
  9732. await vi.waitFor(() =>
  9733. expect(runtime.abortSession).toHaveBeenCalledWith({
  9734. id: rootSession.sessionId,
  9735. turnId: "turn-root",
  9736. reason: "user_stop",
  9737. }),
  9738. );
  9739. expect(runtime.stopDelegation).toHaveBeenCalledOnce();
  9740. expect(runtime.stopDelegation).toHaveBeenCalledWith(rootSession.sessionId);
  9741. expect(runtime.replyPermission).not.toHaveBeenCalledWith(
  9742. "worker",
  9743. "permission-child-stop",
  9744. "deny",
  9745. );
  9746. await app.stop();
  9747. });
  9748. it("recovers a descendant permission from the Runtime pending list without leaking unrelated requests", async () => {
  9749. const runtime = createRuntime();
  9750. const rootSession = {
  9751. sessionId: "session-recovery-root",
  9752. title: "Recovery root",
  9753. workspaceDir: "/workspace",
  9754. };
  9755. vi.mocked(runtime.listSessions).mockResolvedValue([rootSession]);
  9756. vi.mocked(runtime.getSession).mockResolvedValue(rootSession);
  9757. vi.mocked(runtime.getDelegationSnapshot).mockResolvedValue({
  9758. schemaVersion: 1,
  9759. rootSessionId: rootSession.sessionId,
  9760. members: [
  9761. {
  9762. sessionId: "session-recovery-child",
  9763. parentSessionId: rootSession.sessionId,
  9764. agentName: "worker",
  9765. task: "Resume delegated work",
  9766. status: "running",
  9767. },
  9768. ],
  9769. });
  9770. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  9771. {
  9772. requestId: "permission-recovery-unrelated",
  9773. sessionId: "session-other-root",
  9774. agentName: "worker",
  9775. toolName: "bash",
  9776. reason: "Do not show this request",
  9777. },
  9778. {
  9779. requestId: "permission-recovery-child",
  9780. sessionId: "session-recovery-child",
  9781. agentName: "worker",
  9782. toolName: "write",
  9783. reason: "Resume the child request",
  9784. },
  9785. ]);
  9786. const app = createTuiApp({
  9787. runtime,
  9788. terminal: new FakeTerminal(),
  9789. version: "0.1.0",
  9790. workspaceDir: "/workspace",
  9791. });
  9792. await app.ready;
  9793. await app.submit("/resume session-recovery-root");
  9794. expect(
  9795. app.transcript.get("permission:permission-recovery-child"),
  9796. ).toMatchObject({
  9797. kind: "permission",
  9798. status: "blocked",
  9799. });
  9800. expect(
  9801. app.transcript.get("permission:permission-recovery-unrelated"),
  9802. ).toBeUndefined();
  9803. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9804. "Resume the child request",
  9805. );
  9806. await app.stop();
  9807. });
  9808. it("reconnects the Runtime event stream after a transient disconnect", async () => {
  9809. const terminal = new FakeTerminal();
  9810. const runtime = createRuntime();
  9811. const observability = createObservability();
  9812. let attempt = 0;
  9813. vi.mocked(runtime.watchEvents).mockImplementation(
  9814. async function* watchEvents() {
  9815. attempt += 1;
  9816. if (attempt === 1) throw new Error("connection reset");
  9817. yield runtimeEvent({
  9818. type: "permission.ask",
  9819. timestamp: 101,
  9820. source: "runtime",
  9821. payload: {
  9822. requestId: "permission-after-reconnect",
  9823. sessionId: "session-1",
  9824. toolName: "read",
  9825. },
  9826. });
  9827. },
  9828. );
  9829. const app = createTuiApp({
  9830. runtime,
  9831. terminal,
  9832. version: "0.1.0",
  9833. workspaceDir: "/workspace",
  9834. observability,
  9835. });
  9836. await app.ready;
  9837. await app.submit("Start the current session");
  9838. app.start();
  9839. await vi.waitFor(
  9840. () =>
  9841. expect(
  9842. app.transcript.get("permission:permission-after-reconnect"),
  9843. ).toMatchObject({
  9844. status: "blocked",
  9845. }),
  9846. { timeout: 1500 },
  9847. );
  9848. expect(runtime.watchEvents).toHaveBeenCalledTimes(2);
  9849. expect(observability.recordEventStream).toHaveBeenCalledWith(
  9850. expect.objectContaining({
  9851. state: "retry-scheduled",
  9852. attempt: 1,
  9853. retryDelayMs: 250,
  9854. errorKind: "Error",
  9855. }),
  9856. );
  9857. expect(observability.recordEventStream).toHaveBeenCalledWith(
  9858. expect.objectContaining({
  9859. state: "reconnected",
  9860. attempt: 1,
  9861. downtimeMs: expect.any(Number),
  9862. }),
  9863. );
  9864. expect(app.transcript.snapshot()).not.toEqual(
  9865. expect.arrayContaining([
  9866. expect.objectContaining({
  9867. kind: "warning",
  9868. content: expect.stringContaining("Runtime event stream"),
  9869. }),
  9870. ]),
  9871. );
  9872. await app.stop();
  9873. });
  9874. it("sends pasted local attachments and restores failed sends to the Composer", async () => {
  9875. const terminal = new FakeTerminal();
  9876. const runtime = createRuntime();
  9877. const readClipboardImage = vi.fn(async () => ({
  9878. attachment: {
  9879. type: "image" as const,
  9880. filePath: "/tmp/minimax-code-clipboard/diagram.png",
  9881. fileName: "diagram.png",
  9882. mimeType: "image/png",
  9883. sizeBytes: 2048,
  9884. },
  9885. dispose: vi.fn(async () => undefined),
  9886. }));
  9887. const app = createTuiApp({
  9888. runtime,
  9889. terminal,
  9890. version: "0.1.0",
  9891. workspaceDir: "/workspace",
  9892. readClipboardImage,
  9893. readClipboardText: async () => null,
  9894. });
  9895. app.start();
  9896. await app.ready;
  9897. terminal.input?.("\u001bv");
  9898. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(1));
  9899. await app.submit("Inspect the diagram");
  9900. expect(runtime.sendMessage).toHaveBeenCalledWith(
  9901. expect.objectContaining({
  9902. id: "session-1",
  9903. content: "Inspect the diagram",
  9904. attachments: [
  9905. expect.objectContaining({
  9906. local: { filePath: "/tmp/minimax-code-clipboard/diagram.png" },
  9907. meta: expect.objectContaining({ mimeType: "image/png" }),
  9908. }),
  9909. ],
  9910. }),
  9911. expect.any(AbortSignal),
  9912. );
  9913. expect(app.tui.render(80).join("\n")).not.toContain("[Image #1]");
  9914. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  9915. async function* sendMessage() {
  9916. yield { type: "error", message: "provider unavailable" };
  9917. },
  9918. );
  9919. terminal.input?.("\x16");
  9920. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(2));
  9921. app.editor.setText("Try again");
  9922. app.editor.handleInput("\r");
  9923. await vi.waitFor(() => expect(app.editor.getText()).toContain("Try again"));
  9924. expect(app.tui.render(80).join("\n")).toContain(
  9925. "Error The model provider is temporarily unavailable.",
  9926. );
  9927. expect(app.tui.render(80).join("\n")).not.toContain("Request failed");
  9928. expect(app.editor.getText()).toContain("[Image #1]");
  9929. expect(app.tui.render(80).join("\n")).not.toContain(
  9930. "Message kept under Failed",
  9931. );
  9932. await app.submit("/retry");
  9933. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  9934. expect.objectContaining({
  9935. content: "Try again",
  9936. attachments: [
  9937. expect.objectContaining({
  9938. local: { filePath: "/tmp/minimax-code-clipboard/diagram.png" },
  9939. }),
  9940. ],
  9941. }),
  9942. expect.any(AbortSignal),
  9943. );
  9944. await app.submit("A fresh turn");
  9945. expect(app.tui.render(80).join("\n")).not.toContain("Couldn't send");
  9946. await app.stop();
  9947. });
  9948. it("restores a content-review retraction to the Composer without a failed Queue item", async () => {
  9949. const terminal = new FakeTerminal();
  9950. const runtime = createRuntime();
  9951. const busEvents: TuiRuntimeEvent[] = [];
  9952. let wakeBus: (() => void) | undefined;
  9953. vi.mocked(runtime.watchEvents).mockImplementation(
  9954. async function* watchEvents(signal) {
  9955. while (!signal.aborted) {
  9956. if (busEvents.length === 0) {
  9957. await new Promise<void>((resolve) => {
  9958. wakeBus = resolve;
  9959. signal.addEventListener("abort", resolve, { once: true });
  9960. });
  9961. }
  9962. const event = busEvents.shift();
  9963. if (event) yield event;
  9964. }
  9965. },
  9966. );
  9967. let releaseTurn: (() => void) | undefined;
  9968. vi.mocked(runtime.sendMessage).mockImplementation(
  9969. async function* sendMessage() {
  9970. await new Promise<void>((resolve) => {
  9971. releaseTurn = resolve;
  9972. });
  9973. yield { type: "done" };
  9974. },
  9975. );
  9976. const app = createTuiApp({
  9977. runtime,
  9978. terminal,
  9979. version: "0.1.0",
  9980. workspaceDir: "/workspace",
  9981. });
  9982. app.start();
  9983. await app.ready;
  9984. terminal.input?.("review this response");
  9985. terminal.input?.("\r");
  9986. await vi.waitFor(() =>
  9987. expect(app.controller.snapshot().activeTurnId).toBeTruthy(),
  9988. );
  9989. busEvents.push(
  9990. runtimeEvent({
  9991. type: "content.retry.exceeded",
  9992. timestamp: 100,
  9993. source: "runtime-v2",
  9994. payload: { sessionId: "session-1", variant: "content" },
  9995. }),
  9996. runtimeEvent({
  9997. type: "message.rewind",
  9998. timestamp: 101,
  9999. source: "runtime-v2",
  10000. payload: { sessionId: "session-1", contextReset: true },
  10001. }),
  10002. );
  10003. wakeBus?.();
  10004. releaseTurn?.();
  10005. await vi.waitFor(() =>
  10006. expect(app.editor.getText()).toBe("review this response"),
  10007. );
  10008. const rendered = app.tui.render(100).join("\n");
  10009. expect(rendered).toContain(
  10010. "Content review withdrew this response. Rephrase your request, then retry.",
  10011. );
  10012. expect(rendered).not.toContain("Message kept under Failed");
  10013. await app.submit("/queue");
  10014. expect(app.interaction.current()).toBeUndefined();
  10015. await app.stop();
  10016. });
  10017. it("sends editable @directory/ input as ordinary text", async () => {
  10018. const terminal = new FakeTerminal();
  10019. const runtime = createRuntime();
  10020. const app = createTuiApp({
  10021. runtime,
  10022. terminal,
  10023. version: "0.1.0",
  10024. workspaceDir: "/workspace",
  10025. });
  10026. await app.submit("Review @src/");
  10027. expect(runtime.sendMessage).toHaveBeenCalledWith(
  10028. { id: "session-1", content: "Review @src/", turnId: expect.any(String) },
  10029. expect.any(AbortSignal),
  10030. );
  10031. await expect(app.submit("Review @generated/")).resolves.toBeUndefined();
  10032. expect(runtime.sendMessage).toHaveBeenCalledTimes(2);
  10033. });
  10034. it("pastes a clipboard image without replacing the text draft and cleans it after send", async () => {
  10035. const terminal = new FakeTerminal();
  10036. const runtime = createRuntime();
  10037. const dispose = vi.fn(async () => undefined);
  10038. const readClipboardImage = vi.fn(async () => ({
  10039. attachment: {
  10040. type: "image" as const,
  10041. filePath: "/tmp/minimax-code-clipboard/clipboard-1.png",
  10042. fileName: "clipboard-1.png",
  10043. mimeType: "image/png",
  10044. sizeBytes: 4096,
  10045. },
  10046. dispose,
  10047. }));
  10048. const app = createTuiApp({
  10049. runtime,
  10050. terminal,
  10051. version: "0.1.0",
  10052. workspaceDir: "/workspace",
  10053. readClipboardImage,
  10054. readClipboardText: async () => null,
  10055. });
  10056. app.start();
  10057. await app.ready;
  10058. app.editor.setText("Keep this draft");
  10059. terminal.input?.("\u001B[118;9u");
  10060. terminal.input?.("\u001B[118;9:3u");
  10061. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledOnce());
  10062. await vi.waitFor(() =>
  10063. expect(app.editor.getText()).toContain("[Image #1]"),
  10064. );
  10065. expect(app.editor.getText()).toBe("Keep this draft [Image #1] ");
  10066. expect(app.tui.render(100).join("\n")).not.toContain(
  10067. "A clipboard media paste is already in progress.",
  10068. );
  10069. await app.submit("Keep this draft");
  10070. expect(runtime.sendMessage).toHaveBeenCalledWith(
  10071. expect.objectContaining({
  10072. id: "session-1",
  10073. content: "Keep this draft",
  10074. attachments: [
  10075. expect.objectContaining({
  10076. local: { filePath: "/tmp/minimax-code-clipboard/clipboard-1.png" },
  10077. meta: expect.objectContaining({ mimeType: "image/png" }),
  10078. }),
  10079. ],
  10080. }),
  10081. expect.any(AbortSignal),
  10082. );
  10083. expect(dispose).toHaveBeenCalledOnce();
  10084. await app.stop();
  10085. });
  10086. it("retains existing draft state when clipboard read or send fails", async () => {
  10087. const terminal = new FakeTerminal();
  10088. const runtime = createRuntime();
  10089. const dispose = vi.fn(async () => undefined);
  10090. const readClipboardImage = vi
  10091. .fn()
  10092. .mockResolvedValueOnce({
  10093. attachment: {
  10094. type: "image" as const,
  10095. filePath: "/tmp/minimax-code-clipboard/clipboard-2.png",
  10096. fileName: "clipboard-2.png",
  10097. mimeType: "image/png",
  10098. sizeBytes: 1024,
  10099. },
  10100. dispose,
  10101. })
  10102. .mockRejectedValueOnce(new Error("clipboard has no image"));
  10103. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  10104. async function* sendMessage() {
  10105. yield { type: "error", message: "provider unavailable" };
  10106. },
  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("Do not clear me");
  10119. terminal.input?.("\x16");
  10120. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(1));
  10121. terminal.input?.("\x16");
  10122. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(2));
  10123. expect(app.editor.getText()).toBe("Do not clear me [Image #1] ");
  10124. await app.submit("Try the image");
  10125. expect(dispose).not.toHaveBeenCalled();
  10126. expect(app.tui.render(80).join("\n")).toContain("[Image #1]");
  10127. terminal.input?.("\x7f");
  10128. expect(app.tui.render(80).join("\n")).not.toContain("[Image #1]");
  10129. expect(dispose).not.toHaveBeenCalled();
  10130. await app.stop();
  10131. expect(dispose).toHaveBeenCalledOnce();
  10132. });
  10133. it("cancels an in-flight clipboard read with Ctrl+C and keeps the draft", async () => {
  10134. const terminal = new FakeTerminal();
  10135. const runtime = createRuntime();
  10136. let observedSignal: AbortSignal | undefined;
  10137. const readClipboardImage = vi.fn(
  10138. async (signal?: AbortSignal) =>
  10139. await new Promise<never>((_resolve, reject) => {
  10140. observedSignal = signal;
  10141. signal?.addEventListener(
  10142. "abort",
  10143. () => reject(new Error("cancelled")),
  10144. { once: true },
  10145. );
  10146. }),
  10147. );
  10148. const app = createTuiApp({
  10149. runtime,
  10150. terminal,
  10151. version: "0.1.0",
  10152. workspaceDir: "/workspace",
  10153. readClipboardImage,
  10154. readClipboardText: async () => null,
  10155. });
  10156. app.start();
  10157. await app.ready;
  10158. app.editor.setText("Draft survives");
  10159. terminal.input?.("\x16");
  10160. await vi.waitFor(() => expect(observedSignal).toBeDefined());
  10161. terminal.input?.("\x03");
  10162. await vi.waitFor(() => expect(observedSignal?.aborted).toBe(true));
  10163. expect(app.editor.getText()).toBe("Draft survives");
  10164. await app.stop();
  10165. });
  10166. it("keeps queued clipboard files alive until the Runtime reports a terminal queue state", async () => {
  10167. const terminal = new FakeTerminal();
  10168. const runtime = createRuntime();
  10169. const dispose = vi.fn(async () => undefined);
  10170. let finishTurn: (() => void) | undefined;
  10171. let deliverQueueEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  10172. vi.mocked(runtime.sendMessage).mockImplementation(
  10173. async function* sendMessage() {
  10174. await new Promise<void>((resolve) => {
  10175. finishTurn = resolve;
  10176. });
  10177. yield { type: "done" };
  10178. },
  10179. );
  10180. vi.mocked(runtime.watchEvents).mockImplementation(
  10181. async function* watchEvents() {
  10182. const event = await new Promise<TuiRuntimeEvent>((resolve) => {
  10183. deliverQueueEvent = resolve;
  10184. });
  10185. yield event;
  10186. },
  10187. );
  10188. const readClipboardImage = vi.fn(async () => ({
  10189. attachment: {
  10190. type: "image" as const,
  10191. filePath: "/tmp/minimax-code-clipboard/clipboard-queue.png",
  10192. fileName: "clipboard-queue.png",
  10193. mimeType: "image/png",
  10194. sizeBytes: 2048,
  10195. },
  10196. dispose,
  10197. }));
  10198. const app = createTuiApp({
  10199. runtime,
  10200. terminal,
  10201. version: "0.1.0",
  10202. workspaceDir: "/workspace",
  10203. productFeatures: { queue: true },
  10204. readClipboardImage,
  10205. });
  10206. app.start();
  10207. await app.ready;
  10208. const first = app.submit("First turn");
  10209. await vi.waitFor(() =>
  10210. expect(app.controller.snapshot().status).toBe("running"),
  10211. );
  10212. terminal.input?.("\x16");
  10213. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledOnce());
  10214. await app.submit("Queued with image");
  10215. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  10216. "session-1",
  10217. "Queued with image",
  10218. expect.objectContaining({
  10219. attachments: [
  10220. expect.objectContaining({ fileName: "clipboard-queue.png" }),
  10221. ],
  10222. }),
  10223. );
  10224. expect(dispose).not.toHaveBeenCalled();
  10225. deliverQueueEvent?.(
  10226. runtimeEvent({
  10227. type: "session.queue.updated",
  10228. timestamp: Date.now(),
  10229. source: "runtime",
  10230. payload: {
  10231. sessionId: "session-1",
  10232. itemId: "queue-1",
  10233. status: "completed",
  10234. queuedCount: 0,
  10235. },
  10236. }),
  10237. );
  10238. await vi.waitFor(() => expect(dispose).toHaveBeenCalledOnce());
  10239. finishTurn?.();
  10240. await first;
  10241. await app.stop();
  10242. });
  10243. it("opens the Desktop model picker and applies the selected session model", async () => {
  10244. const terminal = new FakeTerminal();
  10245. const runtime = createRuntime();
  10246. vi.mocked(runtime.listModels).mockResolvedValue([
  10247. {
  10248. providerId: "minimax",
  10249. modelId: "MiniMax-M3",
  10250. displayName: "MiniMax M3",
  10251. variant: "thinking",
  10252. thinkingConfig: { mode: "switchable", defaultValue: "true" },
  10253. providerKind: "minimax-managed",
  10254. selected: true,
  10255. },
  10256. ]);
  10257. const app = createTuiApp({
  10258. runtime,
  10259. terminal,
  10260. version: "0.1.0",
  10261. workspaceDir: "/workspace",
  10262. });
  10263. app.start();
  10264. await app.ready;
  10265. await app.submit("Create a session");
  10266. await app.submit("/model");
  10267. expect(app.tui.hasOverlay()).toBe(false);
  10268. expect(app.interaction.isActive()).toBe(true);
  10269. terminal.input?.("\x1b");
  10270. expect(app.tui.hasOverlay()).toBe(false);
  10271. await app.submit("/model");
  10272. terminal.input?.("\r");
  10273. await vi.waitFor(() =>
  10274. expect(runtime.selectModel).toHaveBeenCalledWith(
  10275. expect.objectContaining({
  10276. providerId: "minimax",
  10277. modelId: "MiniMax-M3",
  10278. variant: "thinking",
  10279. }),
  10280. "session-1",
  10281. ),
  10282. );
  10283. await vi.waitFor(() => {
  10284. const rendered = app.tui.render(120).join("\n");
  10285. expect(rendered).toContain("✦ MiniMax M3");
  10286. expect(rendered).toContain("Thinking On");
  10287. expect(rendered).not.toContain("MiniMax M3#thinking");
  10288. });
  10289. await app.stop();
  10290. });
  10291. it("queues a thinking-on model with the configured effort even when the Session stored none", async () => {
  10292. const terminal = new FakeTerminal();
  10293. const runtime = createRuntime();
  10294. let finishTurn: (() => void) | undefined;
  10295. vi.mocked(runtime.listModels).mockResolvedValue([
  10296. {
  10297. providerId: "minimax",
  10298. modelId: "deep-reasoner-1",
  10299. displayName: "deep-reasoner-1",
  10300. selected: true,
  10301. variant: "thinking",
  10302. thinkingConfig: { mode: "switchable", defaultValue: "true" },
  10303. effortOptions: ["xhigh"],
  10304. },
  10305. ]);
  10306. vi.mocked(runtime.sendMessage).mockImplementation(
  10307. async function* sendMessage() {
  10308. await new Promise<void>((resolve) => {
  10309. finishTurn = resolve;
  10310. });
  10311. yield { type: "done" };
  10312. },
  10313. );
  10314. const app = createTuiApp({
  10315. runtime,
  10316. terminal,
  10317. version: "0.1.0",
  10318. workspaceDir: "/workspace",
  10319. productFeatures: { queue: true },
  10320. });
  10321. app.start();
  10322. await app.ready;
  10323. const first = app.submit("First turn");
  10324. await vi.waitFor(() =>
  10325. expect(app.controller.snapshot().status).toBe("running"),
  10326. );
  10327. await app.submit("Queued turn");
  10328. // The Session echo carries no stored effort, so the per-Turn selection has to
  10329. // resolve the configured level. Sending only `variant: thinking` makes Runtime
  10330. // drop the effort and the provider apply its own default.
  10331. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  10332. "session-1",
  10333. "Queued turn",
  10334. expect.objectContaining({
  10335. model: expect.objectContaining({
  10336. providerId: "minimax",
  10337. modelId: "deep-reasoner-1",
  10338. variant: "thinking",
  10339. thinking: { effort: "xhigh" },
  10340. }),
  10341. }),
  10342. );
  10343. finishTurn?.();
  10344. await first;
  10345. await app.stop();
  10346. });
  10347. it("applies a welcome-screen effort to the new Session before sending its first message", async () => {
  10348. const terminal = new FakeTerminal();
  10349. const runtime = createRuntime();
  10350. vi.mocked(runtime.listModels).mockResolvedValue([
  10351. {
  10352. providerId: "custom_provider:byok",
  10353. modelId: "byok-large-5",
  10354. displayName: "BYOK Large 5",
  10355. selected: true,
  10356. variant: "",
  10357. thinkingConfig: { mode: "switchable", defaultValue: "false" },
  10358. effortOptions: ["low", "medium", "high"],
  10359. },
  10360. ]);
  10361. let releaseDefaultSelection: ((selected: boolean) => void) | undefined;
  10362. let releaseSessionSelection: ((selected: boolean) => void) | undefined;
  10363. vi.mocked(runtime.selectModel)
  10364. .mockImplementationOnce(
  10365. async () =>
  10366. await new Promise<boolean>((resolve) => {
  10367. releaseDefaultSelection = resolve;
  10368. }),
  10369. )
  10370. .mockImplementationOnce(
  10371. async () =>
  10372. await new Promise<boolean>((resolve) => {
  10373. releaseSessionSelection = resolve;
  10374. }),
  10375. );
  10376. const app = createTuiApp({
  10377. runtime,
  10378. terminal,
  10379. version: "0.1.0",
  10380. workspaceDir: "/workspace",
  10381. });
  10382. app.start();
  10383. await app.ready;
  10384. await app.submit("/model");
  10385. terminal.input?.("\u001b[C");
  10386. terminal.input?.("\r");
  10387. const firstTurn = app.submit("First turn");
  10388. await vi.waitFor(() =>
  10389. expect(runtime.selectModel).toHaveBeenNthCalledWith(
  10390. 1,
  10391. expect.objectContaining({ thinking: { effort: "high" }, variant: "" }),
  10392. undefined,
  10393. ),
  10394. );
  10395. expect(runtime.selectModel).toHaveBeenCalledOnce();
  10396. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10397. releaseDefaultSelection?.(true);
  10398. await vi.waitFor(() =>
  10399. expect(runtime.selectModel).toHaveBeenNthCalledWith(
  10400. 2,
  10401. expect.objectContaining({ thinking: { effort: "high" }, variant: "" }),
  10402. "session-1",
  10403. ),
  10404. );
  10405. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10406. releaseSessionSelection?.(true);
  10407. await firstTurn;
  10408. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  10409. expect(runtime.selectModel.mock.invocationCallOrder[1]).toBeLessThan(
  10410. runtime.sendMessage.mock.invocationCallOrder[0] ??
  10411. Number.POSITIVE_INFINITY,
  10412. );
  10413. await app.stop();
  10414. });
  10415. it("does not send the first message when Runtime rejects its pending effort", async () => {
  10416. const terminal = new FakeTerminal();
  10417. const runtime = createRuntime();
  10418. vi.mocked(runtime.listModels).mockResolvedValue([
  10419. {
  10420. providerId: "custom_provider:byok",
  10421. modelId: "byok-large-5",
  10422. displayName: "BYOK Large 5",
  10423. selected: true,
  10424. effortOptions: ["low", "medium", "high"],
  10425. },
  10426. ]);
  10427. vi.mocked(runtime.selectModel)
  10428. .mockResolvedValueOnce(true)
  10429. .mockResolvedValueOnce(false);
  10430. const app = createTuiApp({
  10431. runtime,
  10432. terminal,
  10433. version: "0.1.0",
  10434. workspaceDir: "/workspace",
  10435. });
  10436. app.start();
  10437. await app.ready;
  10438. await app.submit("/model");
  10439. terminal.input?.("\r");
  10440. await vi.waitFor(() => expect(runtime.selectModel).toHaveBeenCalledOnce());
  10441. await app.submit("First turn");
  10442. expect(runtime.selectModel).toHaveBeenCalledTimes(2);
  10443. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10444. await app.stop();
  10445. });
  10446. it("lets Escape cancel the first turn while Desktop is creating its session", async () => {
  10447. const terminal = new FakeTerminal();
  10448. const runtime = createRuntime();
  10449. let finishSessionCreation:
  10450. | ((session: { sessionId: string; workspaceDir: string }) => void)
  10451. | undefined;
  10452. vi.mocked(runtime.createSession).mockImplementation(
  10453. async () =>
  10454. await new Promise<{ sessionId: string; workspaceDir: string }>(
  10455. (resolve) => {
  10456. finishSessionCreation = resolve;
  10457. },
  10458. ),
  10459. );
  10460. const app = createTuiApp({
  10461. runtime,
  10462. terminal,
  10463. version: "0.1.0",
  10464. workspaceDir: "/workspace",
  10465. });
  10466. app.start();
  10467. await app.ready;
  10468. const submitting = app.submit("Wait for the session");
  10469. await vi.waitFor(() =>
  10470. expect(app.controller.snapshot()).toMatchObject({
  10471. status: "starting",
  10472. activeTurnId: expect.any(String),
  10473. }),
  10474. );
  10475. expect(app.tui.render(80).join("\n")).toContain("Loading");
  10476. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  10477. expect(app.tui.render(80).join("\n")).not.toContain("MCode ·");
  10478. terminal.input?.("\x1b");
  10479. await vi.waitFor(() =>
  10480. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  10481. );
  10482. finishSessionCreation?.({
  10483. sessionId: "session-created",
  10484. workspaceDir: "/workspace",
  10485. });
  10486. await submitting;
  10487. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10488. expect(app.transcript.snapshot()).toEqual(
  10489. expect.arrayContaining([
  10490. expect.objectContaining({ kind: "assistant", status: "cancelled" }),
  10491. ]),
  10492. );
  10493. await app.stop();
  10494. });
  10495. it("restores a submission attempted while the previous cancellation fence is active", async () => {
  10496. const terminal = new FakeTerminal();
  10497. const runtime = createRuntime();
  10498. let releaseCancelledStream: (() => void) | undefined;
  10499. let sendCount = 0;
  10500. vi.mocked(runtime.sendMessage).mockImplementation(
  10501. async function* sendMessage(_req: SendMessageReq, signal?: AbortSignal) {
  10502. sendCount += 1;
  10503. if (sendCount === 1) {
  10504. await new Promise<void>((resolve) => {
  10505. signal?.addEventListener("abort", resolve, { once: true });
  10506. });
  10507. await new Promise<void>((resolve) => {
  10508. releaseCancelledStream = resolve;
  10509. });
  10510. } else {
  10511. yield { type: "delta", content: "Second response" };
  10512. }
  10513. yield { type: "done" };
  10514. },
  10515. );
  10516. vi.mocked(runtime.abortSession).mockImplementation(async () => {
  10517. setTimeout(() => releaseCancelledStream?.(), 10);
  10518. return true;
  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. terminal.input?.("First request");
  10529. terminal.input?.("\r");
  10530. await vi.waitFor(() =>
  10531. expect(app.controller.snapshot().status).toBe("running"),
  10532. );
  10533. terminal.input?.("\x1b");
  10534. await vi.waitFor(() =>
  10535. expect(app.controller.snapshot().cancelling).toBe(true),
  10536. );
  10537. terminal.input?.("Second request");
  10538. terminal.input?.("\r");
  10539. await vi.waitFor(() => expect(app.editor.getText()).toBe("Second request"));
  10540. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  10541. await vi.waitFor(() =>
  10542. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  10543. );
  10544. await vi.waitFor(() =>
  10545. expect(app.controller.snapshot().retiringTurnId).toBeUndefined(),
  10546. );
  10547. expect(app.controller.snapshot().cancelling).toBe(false);
  10548. expect(app.tui.render(80).join("\n")).not.toContain(
  10549. "Stopping the current response",
  10550. );
  10551. app.editor.handleInput("\r");
  10552. await vi.waitFor(() =>
  10553. expect(runtime.sendMessage).toHaveBeenCalledTimes(2),
  10554. );
  10555. expect(runtime.sendMessage).toHaveBeenCalledTimes(2);
  10556. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  10557. expect(app.transcript.snapshot()).toEqual(
  10558. expect.arrayContaining([
  10559. expect.objectContaining({ kind: "assistant", status: "cancelled" }),
  10560. ]),
  10561. );
  10562. await app.stop();
  10563. });
  10564. it("restores a failed submission before text typed while cancellation is retiring", async () => {
  10565. const terminal = new FakeTerminal();
  10566. const runtime = createRuntime();
  10567. let releaseRuntimeOwnership: (() => void) | undefined;
  10568. const runtimeOwnershipReleased = new Promise<void>((resolve) => {
  10569. releaseRuntimeOwnership = resolve;
  10570. });
  10571. vi.mocked(runtime.sendMessage).mockImplementation(
  10572. async function* sendMessage(_req: SendMessageReq, signal?: AbortSignal) {
  10573. await new Promise<void>((resolve) => {
  10574. signal?.addEventListener("abort", resolve, { once: true });
  10575. });
  10576. await runtimeOwnershipReleased;
  10577. yield { type: "done" };
  10578. },
  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().retiringTurnId).toBeTruthy(),
  10596. {
  10597. timeout: 2_000,
  10598. },
  10599. );
  10600. expect(app.controller.snapshot()).toMatchObject({
  10601. status: "idle",
  10602. activeTurnId: undefined,
  10603. cancelling: false,
  10604. });
  10605. terminal.input?.("Second request");
  10606. terminal.input?.("\r");
  10607. terminal.input?.("extra detail");
  10608. await vi.waitFor(() => expect(app.editor.getText()).toBe("extra detail"));
  10609. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  10610. await vi.waitFor(() =>
  10611. expect(app.tui.render(160).join("\n")).toContain("Second request"),
  10612. );
  10613. expect(app.editor.getText()).toBe("Second request\nextra detail");
  10614. releaseRuntimeOwnership?.();
  10615. await vi.waitFor(() =>
  10616. expect(app.controller.snapshot().retiringTurnId).toBeUndefined(),
  10617. );
  10618. expect(app.tui.render(160).join("\n")).not.toContain(
  10619. "Runtime is still stopping; your draft is preserved",
  10620. );
  10621. await app.stop();
  10622. });
  10623. it("aborts session creation when the TUI stops during its first turn", async () => {
  10624. const terminal = new FakeTerminal();
  10625. const runtime = createRuntime();
  10626. let finishSessionCreation:
  10627. | ((session: { sessionId: string; workspaceDir: string }) => void)
  10628. | undefined;
  10629. vi.mocked(runtime.createSession).mockImplementation(
  10630. async () =>
  10631. await new Promise<{ sessionId: string; workspaceDir: string }>(
  10632. (resolve) => {
  10633. finishSessionCreation = resolve;
  10634. },
  10635. ),
  10636. );
  10637. const app = createTuiApp({
  10638. runtime,
  10639. terminal,
  10640. version: "0.1.0",
  10641. workspaceDir: "/workspace",
  10642. });
  10643. app.start();
  10644. await app.ready;
  10645. const submitting = app.submit("Wait for the session");
  10646. await vi.waitFor(() =>
  10647. expect(app.controller.snapshot().activeTurnId).toEqual(
  10648. expect.any(String),
  10649. ),
  10650. );
  10651. const stopping = app.stop();
  10652. finishSessionCreation?.({
  10653. sessionId: "session-created",
  10654. workspaceDir: "/workspace",
  10655. });
  10656. await Promise.all([submitting, stopping]);
  10657. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10658. expect(app.transcript.snapshot()).toEqual(
  10659. expect.arrayContaining([
  10660. expect.objectContaining({ kind: "assistant", status: "cancelled" }),
  10661. ]),
  10662. );
  10663. expect(terminal.stopped).toBe(true);
  10664. });
  10665. it.each(["minimax", "custom_provider:work"])(
  10666. "hydrates the Runtime-selected startup model for %s",
  10667. async (providerId) => {
  10668. const runtime = createRuntime();
  10669. vi.mocked(runtime.listModels).mockResolvedValue([
  10670. { providerId, modelId: "MiniMax-M3", selected: true },
  10671. ]);
  10672. const app = createTuiApp({
  10673. runtime,
  10674. terminal: new FakeTerminal(),
  10675. version: "0.1.0",
  10676. workspaceDir: "/workspace",
  10677. });
  10678. try {
  10679. await app.ready;
  10680. expect(runtime.listModels).toHaveBeenCalled();
  10681. expect(runtime.selectModel).not.toHaveBeenCalled();
  10682. await app.submit("/model");
  10683. expect(runtime.selectModel).not.toHaveBeenCalled();
  10684. } finally {
  10685. await app.stop();
  10686. }
  10687. },
  10688. );
  10689. it("offers provider onboarding when Desktop has no models", async () => {
  10690. const terminal = new FakeTerminal();
  10691. const runtime = createRuntime();
  10692. vi.mocked(runtime.listModels).mockResolvedValue([]);
  10693. const app = createTuiApp({
  10694. runtime,
  10695. terminal,
  10696. version: "0.1.0",
  10697. workspaceDir: "/workspace",
  10698. });
  10699. await app.ready;
  10700. await app.submit("/model unavailable");
  10701. expect(app.tui.hasOverlay()).toBe(false);
  10702. expect(app.interaction.isActive()).toBe(true);
  10703. const rendered = app.tui.render(120).join("\n");
  10704. expect(rendered).toContain("No matching models");
  10705. expect(rendered).toContain("Add 3rd-party provider");
  10706. terminal.input?.("\x1b");
  10707. await app.stop();
  10708. });
  10709. it("keeps the TUI usable when the Runtime model catalog fails to load", async () => {
  10710. const terminal = new FakeTerminal();
  10711. const runtime = createRuntime();
  10712. vi.mocked(runtime.listModels).mockRejectedValue(
  10713. new Error("catalog unavailable"),
  10714. );
  10715. const app = createTuiApp({
  10716. runtime,
  10717. terminal,
  10718. version: "0.1.0",
  10719. workspaceDir: "/workspace",
  10720. });
  10721. await app.ready;
  10722. await expect(app.submit("/model")).resolves.toBeUndefined();
  10723. expect(app.tui.hasOverlay()).toBe(false);
  10724. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  10725. kind: "warning",
  10726. content: "Couldn't load models: catalog unavailable. Retry /model.",
  10727. });
  10728. });
  10729. it("shows a follow-up as queued while Runtime admission is pending", async () => {
  10730. const terminal = new FakeTerminal();
  10731. const runtime = createRuntime();
  10732. let finishFirstTurn: (() => void) | undefined;
  10733. let finishEnqueue: (() => void) | undefined;
  10734. let admitted = false;
  10735. vi.mocked(runtime.sendMessage).mockImplementation(
  10736. async function* sendMessage() {
  10737. await new Promise<void>((resolve) => {
  10738. finishFirstTurn = resolve;
  10739. });
  10740. yield { type: "done" };
  10741. },
  10742. );
  10743. vi.mocked(runtime.enqueueMessage).mockImplementation(async () => {
  10744. await new Promise<void>((resolve) => {
  10745. finishEnqueue = resolve;
  10746. });
  10747. admitted = true;
  10748. return { itemId: "queue-pending-1", status: "queued", position: 1 };
  10749. });
  10750. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () =>
  10751. admitted
  10752. ? [
  10753. {
  10754. itemId: "queue-pending-1",
  10755. sessionId: "session-1",
  10756. status: "queued",
  10757. content: "Second turn",
  10758. },
  10759. ]
  10760. : [],
  10761. );
  10762. const app = createTuiApp({
  10763. runtime,
  10764. terminal,
  10765. version: "0.1.0",
  10766. workspaceDir: "/workspace",
  10767. });
  10768. app.start();
  10769. await app.ready;
  10770. const first = app.submit("First turn");
  10771. await vi.waitFor(() =>
  10772. expect(app.controller.snapshot().activeTurnId).toEqual(
  10773. expect.any(String),
  10774. ),
  10775. );
  10776. terminal.input?.("Second turn");
  10777. terminal.input?.("\x1b\r");
  10778. await vi.waitFor(() =>
  10779. expect(runtime.enqueueMessage).toHaveBeenCalledOnce(),
  10780. );
  10781. try {
  10782. expect(
  10783. app.transcript
  10784. .snapshot()
  10785. .find((cell) => cell.content.includes("Second turn")),
  10786. ).toBeUndefined();
  10787. const rendered = app.tui.render(100).join("\n");
  10788. expect(rendered).not.toContain("Adding to Queue");
  10789. expect(rendered).toContain("Next · after current response");
  10790. expect(rendered).toContain("Second turn");
  10791. finishEnqueue?.();
  10792. await vi.waitFor(() => {
  10793. const confirmed = app.tui.render(100).join("\n");
  10794. expect(confirmed).not.toContain("Adding to Queue");
  10795. expect(confirmed).toContain("Next · after current response");
  10796. expect(confirmed).toContain("Second turn");
  10797. });
  10798. } finally {
  10799. finishEnqueue?.();
  10800. finishFirstTurn?.();
  10801. await first;
  10802. await app.stop();
  10803. }
  10804. });
  10805. it("removes the local Queue admission and restores the Draft when Runtime rejects it", async () => {
  10806. const terminal = new FakeTerminal();
  10807. const runtime = createRuntime();
  10808. let finishFirstTurn: (() => void) | undefined;
  10809. let rejectEnqueue: ((error: Error) => void) | undefined;
  10810. vi.mocked(runtime.sendMessage).mockImplementation(
  10811. async function* sendMessage() {
  10812. await new Promise<void>((resolve) => {
  10813. finishFirstTurn = resolve;
  10814. });
  10815. yield { type: "done" };
  10816. },
  10817. );
  10818. vi.mocked(runtime.enqueueMessage).mockImplementation(
  10819. async () =>
  10820. await new Promise<never>((_resolve, reject) => {
  10821. rejectEnqueue = reject;
  10822. }),
  10823. );
  10824. const app = createTuiApp({
  10825. runtime,
  10826. terminal,
  10827. version: "0.1.0",
  10828. workspaceDir: "/workspace",
  10829. });
  10830. app.start();
  10831. await app.ready;
  10832. const first = app.submit("First turn");
  10833. await vi.waitFor(() =>
  10834. expect(app.controller.snapshot().activeTurnId).toEqual(
  10835. expect.any(String),
  10836. ),
  10837. );
  10838. terminal.input?.("Keep this Draft");
  10839. terminal.input?.("\x1b\r");
  10840. await vi.waitFor(() =>
  10841. expect(app.tui.render(100).join("\n")).toContain(
  10842. "Next · after current response",
  10843. ),
  10844. );
  10845. await vi.waitFor(() =>
  10846. expect(runtime.enqueueMessage).toHaveBeenCalledOnce(),
  10847. );
  10848. rejectEnqueue?.(new Error("queue unavailable"));
  10849. await vi.waitFor(() =>
  10850. expect(app.editor.getText()).toBe("Keep this Draft"),
  10851. );
  10852. const rendered = app.tui.render(100).join("\n");
  10853. expect(rendered).not.toContain("Next · after current response");
  10854. expect(rendered).toContain("Couldn't add this message to the Queue");
  10855. finishFirstTurn?.();
  10856. await first;
  10857. await app.stop();
  10858. });
  10859. it("shows every rapid follow-up as queued while Runtime admissions are serialized", async () => {
  10860. const terminal = new FakeTerminal();
  10861. const runtime = createRuntime();
  10862. let finishFirstTurn: (() => void) | undefined;
  10863. const releaseAdmissions: Array<() => void> = [];
  10864. const queued: TuiQueuedMessage[] = [];
  10865. vi.mocked(runtime.sendMessage).mockImplementation(
  10866. async function* sendMessage() {
  10867. await new Promise<void>((resolve) => {
  10868. finishFirstTurn = resolve;
  10869. });
  10870. yield { type: "done" };
  10871. },
  10872. );
  10873. vi.mocked(runtime.enqueueMessage).mockImplementation(
  10874. async (sessionId, content) => {
  10875. await new Promise<void>((resolve) => releaseAdmissions.push(resolve));
  10876. const item = {
  10877. itemId: `queue-rapid-${String(queued.length + 1)}`,
  10878. sessionId,
  10879. status: "queued",
  10880. content,
  10881. } satisfies TuiQueuedMessage;
  10882. queued.push(item);
  10883. return {
  10884. itemId: item.itemId,
  10885. status: item.status,
  10886. position: queued.length,
  10887. };
  10888. },
  10889. );
  10890. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  10891. ...queued,
  10892. ]);
  10893. const app = createTuiApp({
  10894. runtime,
  10895. terminal,
  10896. version: "0.1.0",
  10897. workspaceDir: "/workspace",
  10898. });
  10899. app.start();
  10900. await app.ready;
  10901. const first = app.submit("First turn");
  10902. await vi.waitFor(() =>
  10903. expect(app.controller.snapshot().activeTurnId).toEqual(
  10904. expect.any(String),
  10905. ),
  10906. );
  10907. terminal.input?.("Second turn");
  10908. terminal.input?.("\x1b\r");
  10909. terminal.input?.("Third turn");
  10910. terminal.input?.("\x1b\r");
  10911. await vi.waitFor(() => {
  10912. const rendered = app.tui.render(100).join("\n");
  10913. expect(rendered).not.toContain("Adding");
  10914. expect(rendered).toContain("Queue · 2 next");
  10915. expect(rendered).toContain("Second turn");
  10916. expect(rendered).toContain("Third turn");
  10917. });
  10918. expect(
  10919. app.transcript
  10920. .snapshot()
  10921. .filter(
  10922. (cell) =>
  10923. cell.content.includes("Second turn") ||
  10924. cell.content.includes("Third turn"),
  10925. ),
  10926. ).toEqual([]);
  10927. await vi.waitFor(() =>
  10928. expect(runtime.enqueueMessage).toHaveBeenCalledOnce(),
  10929. );
  10930. releaseAdmissions[0]?.();
  10931. await vi.waitFor(() =>
  10932. expect(runtime.enqueueMessage).toHaveBeenCalledTimes(2),
  10933. );
  10934. const partiallyConfirmed = app.tui.render(100).join("\n");
  10935. expect(partiallyConfirmed).toContain("Queue · 2 next");
  10936. expect(partiallyConfirmed.indexOf("Second turn")).toBeLessThan(
  10937. partiallyConfirmed.indexOf("Third turn"),
  10938. );
  10939. releaseAdmissions[1]?.();
  10940. await vi.waitFor(() =>
  10941. expect(app.tui.render(100).join("\n")).toContain("Queue · 2 next"),
  10942. );
  10943. finishFirstTurn?.();
  10944. await first;
  10945. await app.stop();
  10946. });
  10947. it("submits follow-ups to the runtime-owned queue and never drains them in the CLI", async () => {
  10948. const terminal = new FakeTerminal();
  10949. const runtime = createRuntime();
  10950. let finishFirstTurn: (() => void) | undefined;
  10951. vi.mocked(runtime.sendMessage).mockImplementation(
  10952. async function* sendMessage(req: SendMessageReq) {
  10953. const content = req.content ?? "";
  10954. if (content === "First turn") {
  10955. await new Promise<void>((resolve) => {
  10956. finishFirstTurn = resolve;
  10957. });
  10958. }
  10959. yield { type: "delta", content: `Reply to ${content || "attachment"}` };
  10960. yield { type: "done" };
  10961. },
  10962. );
  10963. const attachment = {
  10964. type: "file" as const,
  10965. filePath: "/workspace/notes.md",
  10966. fileName: "notes.md",
  10967. mimeType: "text/markdown",
  10968. sizeBytes: 32,
  10969. };
  10970. const queued: Array<{
  10971. itemId: string;
  10972. sessionId: string;
  10973. status: string;
  10974. content: string;
  10975. }> = [];
  10976. vi.mocked(runtime.enqueueMessage).mockImplementation(
  10977. async (sessionId, content) => {
  10978. const item = {
  10979. itemId: `queue-${queued.length + 1}`,
  10980. sessionId,
  10981. status: "queued",
  10982. content,
  10983. };
  10984. queued.push(item);
  10985. return {
  10986. itemId: item.itemId,
  10987. status: item.status,
  10988. position: queued.length,
  10989. };
  10990. },
  10991. );
  10992. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  10993. ...queued,
  10994. ]);
  10995. vi.mocked(runtime.deleteQueuedMessage).mockImplementation(
  10996. async (_sessionId, itemId) => {
  10997. const index = queued.findIndex((item) => item.itemId === itemId);
  10998. if (index < 0) return undefined;
  10999. return queued.splice(index, 1)[0];
  11000. },
  11001. );
  11002. const readClipboardImage = vi.fn(async () => ({
  11003. attachment,
  11004. dispose: vi.fn(async () => undefined),
  11005. }));
  11006. const app = createTuiApp({
  11007. runtime,
  11008. terminal,
  11009. version: "0.1.0",
  11010. workspaceDir: "/workspace",
  11011. readClipboardImage,
  11012. });
  11013. app.start();
  11014. await app.ready;
  11015. const first = app.submit("First turn");
  11016. await vi.waitFor(() =>
  11017. expect(app.controller.snapshot().activeTurnId).toEqual(
  11018. expect.any(String),
  11019. ),
  11020. );
  11021. terminal.input?.("\x16");
  11022. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledOnce());
  11023. await app.submit("Second turn");
  11024. await app.submit("Third turn");
  11025. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  11026. expect(runtime.enqueueMessage).toHaveBeenNthCalledWith(
  11027. 1,
  11028. "session-1",
  11029. "Second turn",
  11030. {
  11031. attachments: [attachment],
  11032. model: { providerId: "minimax", modelId: "MiniMax-M2.7" },
  11033. },
  11034. );
  11035. expect(runtime.enqueueMessage).toHaveBeenNthCalledWith(
  11036. 2,
  11037. "session-1",
  11038. "Third turn",
  11039. {
  11040. attachments: [],
  11041. model: { providerId: "minimax", modelId: "MiniMax-M2.7" },
  11042. },
  11043. );
  11044. expect(app.transcript.get("queue:queue-1")).toBeUndefined();
  11045. expect(app.transcript.get("queue:queue-2")).toBeUndefined();
  11046. const queuedUi = app.tui.render(80).join("\n");
  11047. expect(queuedUi).toContain("Queue · 2 next");
  11048. expect(queuedUi).toContain("after current response");
  11049. expect(queuedUi).toContain("Second turn");
  11050. expect(queuedUi).toContain("Third turn");
  11051. expect(queuedUi).toContain("/queue manage");
  11052. await app.submit("/queue");
  11053. expect(app.interaction.render(80).join("\n")).toContain("Queue");
  11054. expect(app.interaction.render(80).join("\n")).toContain("2 next");
  11055. expect(app.interaction.render(80).join("\n")).toContain("› 2. Third turn");
  11056. expect(app.editor.getText()).toBe("");
  11057. terminal.input?.("d");
  11058. expect(app.interaction.render(80).join("\n")).toContain(
  11059. "Remove this next message?",
  11060. );
  11061. terminal.input?.("\r");
  11062. await vi.waitFor(() =>
  11063. expect(runtime.deleteQueuedMessage).toHaveBeenCalledWith(
  11064. "session-1",
  11065. "queue-2",
  11066. ),
  11067. );
  11068. await vi.waitFor(() =>
  11069. expect(app.tui.render(80).join("\n")).not.toContain("Third turn"),
  11070. );
  11071. expect(app.tui.render(80).join("\n")).toContain("Second turn");
  11072. terminal.input?.("\x1b");
  11073. finishFirstTurn?.();
  11074. await first;
  11075. expect(
  11076. vi.mocked(runtime.sendMessage).mock.calls.map((call) => call[0].content),
  11077. ).toEqual(["First turn"]);
  11078. expect(app.tui.render(80).join("\n")).toContain(
  11079. "Next · after current response",
  11080. );
  11081. expect(app.tui.render(80).join("\n")).toContain("Second turn");
  11082. expect(app.tui.render(80).join("\n")).not.toContain("Sending next");
  11083. await app.stop();
  11084. });
  11085. it("uses the Runtime queue when a resumed started session is active before queue/model hydration finishes", async () => {
  11086. const terminal = new FakeTerminal();
  11087. const runtime = createRuntime();
  11088. let releaseQueue: ((items: TuiQueuedMessage[]) => void) | undefined;
  11089. const slowQueue = new Promise<TuiQueuedMessage[]>((resolve) => {
  11090. releaseQueue = resolve;
  11091. });
  11092. let releaseModels: ((models: TuiModel[]) => void) | undefined;
  11093. const slowModels = new Promise<TuiModel[]>((resolve) => {
  11094. releaseModels = resolve;
  11095. });
  11096. const session = {
  11097. sessionId: "session-running",
  11098. title: "Running session",
  11099. workspaceDir: "/workspace",
  11100. status: "started",
  11101. };
  11102. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11103. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11104. vi.mocked(runtime.getActiveRun).mockResolvedValue({
  11105. schemaVersion: 1,
  11106. sessionId: "session-running",
  11107. state: "running",
  11108. turnId: "turn-running",
  11109. actions: { steer: true },
  11110. });
  11111. vi.mocked(runtime.listQueuedMessages).mockImplementation(
  11112. async () => slowQueue,
  11113. );
  11114. vi.mocked(runtime.listModels).mockImplementation(async (sessionId) =>
  11115. sessionId ? slowModels : [],
  11116. );
  11117. vi.mocked(runtime.enqueueMessage).mockResolvedValue({
  11118. itemId: "queue-running-1",
  11119. status: "queued",
  11120. position: 1,
  11121. });
  11122. const app = createTuiApp({
  11123. runtime,
  11124. terminal,
  11125. version: "0.1.0",
  11126. workspaceDir: "/workspace",
  11127. productFeatures: { queue: true },
  11128. });
  11129. await app.ready;
  11130. const resuming = app.submit("/resume session-running");
  11131. await vi.waitFor(() =>
  11132. expect(app.tui.render(80).join("\n")).toContain("Loading"),
  11133. );
  11134. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  11135. const followUp = app.submit("Send this through the Runtime queue");
  11136. await vi.waitFor(() =>
  11137. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  11138. "session-running",
  11139. "Send this through the Runtime queue",
  11140. { attachments: [] },
  11141. ),
  11142. );
  11143. expect(runtime.sendMessage).not.toHaveBeenCalled();
  11144. releaseQueue?.([]);
  11145. releaseModels?.([]);
  11146. await Promise.all([resuming, followUp]);
  11147. await app.stop();
  11148. });
  11149. it("does not recover a terminal session as an active turn", async () => {
  11150. const terminal = new FakeTerminal();
  11151. const runtime = createRuntime();
  11152. const session = {
  11153. sessionId: "session-finished",
  11154. title: "Finished session",
  11155. workspaceDir: "/workspace",
  11156. status: "finished",
  11157. };
  11158. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11159. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11160. const app = createTuiApp({
  11161. runtime,
  11162. terminal,
  11163. version: "0.1.0",
  11164. workspaceDir: "/workspace",
  11165. });
  11166. await app.ready;
  11167. await app.submit("/resume session-finished");
  11168. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
  11169. expect(app.tui.render(80).join("\n")).toContain("Message · Enter send");
  11170. await app.stop();
  11171. });
  11172. it("does not recover a stale started Session when Runtime is already idle", async () => {
  11173. const terminal = new FakeTerminal();
  11174. const runtime = createRuntime();
  11175. const session = {
  11176. sessionId: "session-stale",
  11177. title: "Stale session",
  11178. workspaceDir: "/workspace",
  11179. status: "started",
  11180. };
  11181. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11182. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11183. const app = createTuiApp({
  11184. runtime,
  11185. terminal,
  11186. version: "0.1.0",
  11187. workspaceDir: "/workspace",
  11188. });
  11189. app.start();
  11190. await app.ready;
  11191. await app.submit("/resume session-stale");
  11192. await vi.waitFor(() =>
  11193. expect(app.tui.render(80).join("\n")).not.toContain("Loading"),
  11194. );
  11195. const rendered = app.tui.render(80).join("\n");
  11196. expect(rendered).not.toContain("Thinking");
  11197. expect(rendered).not.toContain("Stopping response");
  11198. expect(rendered).not.toContain("Stopping the current response");
  11199. expect(rendered).toContain("Message · Enter send");
  11200. await app.stop();
  11201. });
  11202. it("stops a recovered Runtime turn with /stop and Escape through abortSession", async () => {
  11203. const terminal = new FakeTerminal();
  11204. const runtime = createRuntime();
  11205. const session = {
  11206. sessionId: "session-running",
  11207. title: "Running session",
  11208. workspaceDir: "/workspace",
  11209. status: "started",
  11210. };
  11211. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11212. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11213. vi.mocked(runtime.getActiveRun).mockResolvedValue({
  11214. schemaVersion: 1,
  11215. sessionId: "session-running",
  11216. state: "running",
  11217. turnId: "turn-running",
  11218. actions: { steer: true },
  11219. });
  11220. vi.mocked(runtime.abortSession).mockResolvedValue(true);
  11221. const app = createTuiApp({
  11222. runtime,
  11223. terminal,
  11224. version: "0.1.0",
  11225. workspaceDir: "/workspace",
  11226. });
  11227. app.start();
  11228. await app.ready;
  11229. await app.submit("/resume session-running");
  11230. await app.submit("/stop");
  11231. expect(runtime.abortSession).toHaveBeenCalledWith(
  11232. expect.objectContaining({ id: "session-running" }),
  11233. );
  11234. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
  11235. vi.mocked(runtime.abortSession).mockClear();
  11236. await app.submit("/resume session-running");
  11237. terminal.input?.("\x1b");
  11238. await vi.waitFor(() =>
  11239. expect(runtime.abortSession).toHaveBeenCalledWith(
  11240. expect.objectContaining({ id: "session-running" }),
  11241. ),
  11242. );
  11243. await vi.waitFor(() =>
  11244. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt"),
  11245. );
  11246. expect(app.tui.render(80).join("\n")).not.toMatch(
  11247. /Stopped after|Interrupted after/u,
  11248. );
  11249. await app.stop();
  11250. });
  11251. it.each([
  11252. [
  11253. "rejects the abort",
  11254. async () => false,
  11255. "Runtime did not confirm that the active response stopped.",
  11256. ],
  11257. [
  11258. "fails the abort request",
  11259. async () => Promise.reject(new Error("connection lost")),
  11260. "Couldn't stop the current response:",
  11261. ],
  11262. ])(
  11263. "clears the recovered foreground projection and reports when Runtime %s",
  11264. async (_label, abort, expectedError) => {
  11265. const terminal = new FakeTerminal();
  11266. const runtime = createRuntime();
  11267. const session = {
  11268. sessionId: "session-running",
  11269. title: "Running session",
  11270. workspaceDir: "/workspace",
  11271. status: "started",
  11272. };
  11273. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11274. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11275. vi.mocked(runtime.getActiveRun).mockResolvedValue({
  11276. schemaVersion: 1,
  11277. sessionId: "session-running",
  11278. state: "running",
  11279. turnId: "turn-running",
  11280. actions: { steer: false },
  11281. });
  11282. vi.mocked(runtime.abortSession).mockImplementation(abort);
  11283. const app = createTuiApp({
  11284. runtime,
  11285. terminal,
  11286. version: "0.1.0",
  11287. workspaceDir: "/workspace",
  11288. });
  11289. app.start();
  11290. await app.ready;
  11291. await app.submit("/resume session-running");
  11292. terminal.input?.("\x1b");
  11293. await vi.waitFor(() =>
  11294. expect(runtime.abortSession).toHaveBeenCalledWith(
  11295. expect.objectContaining({ id: "session-running" }),
  11296. ),
  11297. );
  11298. await vi.waitFor(() =>
  11299. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt"),
  11300. );
  11301. await vi.waitFor(() =>
  11302. expect(app.tui.render(80).join("\n")).toContain(expectedError),
  11303. );
  11304. await app.stop();
  11305. },
  11306. );
  11307. it("keeps Request failed visible when Runtime still has queued follow-ups", async () => {
  11308. const terminal = new FakeTerminal();
  11309. const runtime = createRuntime();
  11310. let finishTurn: (() => void) | undefined;
  11311. const queued = [
  11312. {
  11313. itemId: "queue-after-error",
  11314. sessionId: "session-1",
  11315. status: "queued",
  11316. content: "Continue after failure",
  11317. },
  11318. ];
  11319. vi.mocked(runtime.listQueuedMessages).mockResolvedValue(queued);
  11320. vi.mocked(runtime.enqueueMessage).mockResolvedValue({
  11321. itemId: "queue-after-error",
  11322. status: "queued",
  11323. position: 1,
  11324. });
  11325. vi.mocked(runtime.sendMessage).mockImplementation(
  11326. async function* sendMessage() {
  11327. await new Promise<void>((resolve) => {
  11328. finishTurn = resolve;
  11329. });
  11330. yield { type: "error", message: "provider unavailable" };
  11331. },
  11332. );
  11333. const app = createTuiApp({
  11334. runtime,
  11335. terminal,
  11336. version: "0.1.0",
  11337. workspaceDir: "/workspace",
  11338. productFeatures: { queue: true },
  11339. });
  11340. await app.ready;
  11341. const first = app.submit("First turn");
  11342. await vi.waitFor(() =>
  11343. expect(app.controller.snapshot().activeTurnId).toEqual(
  11344. expect.any(String),
  11345. ),
  11346. );
  11347. await app.submit("Continue after failure");
  11348. finishTurn?.();
  11349. await first;
  11350. expect(app.tui.render(80).join("\n")).toContain(
  11351. "Error The model provider is temporarily unavailable.",
  11352. );
  11353. expect(app.tui.render(80).join("\n")).not.toContain("Request failed");
  11354. await app.stop();
  11355. });
  11356. it("converges a recovered running state after the Runtime emits a terminal event", async () => {
  11357. const terminal = new FakeTerminal();
  11358. const runtime = createRuntime();
  11359. const session = {
  11360. sessionId: "session-recovered",
  11361. title: "Recovered session",
  11362. workspaceDir: "/workspace",
  11363. status: "started",
  11364. };
  11365. const busEvents: TuiRuntimeEvent[] = [];
  11366. let wakeBus: (() => void) | undefined;
  11367. const waitForNextBusEvent = (signal: AbortSignal) =>
  11368. new Promise<void>((resolve) => {
  11369. wakeBus = resolve;
  11370. signal.addEventListener("abort", resolve, { once: true });
  11371. });
  11372. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11373. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11374. let activeRecoveredTurn = true;
  11375. vi.mocked(runtime.getActiveRun).mockImplementation(async () =>
  11376. activeRecoveredTurn
  11377. ? {
  11378. schemaVersion: 1,
  11379. sessionId: "session-recovered",
  11380. state: "running",
  11381. turnId: "turn-recovered",
  11382. actions: { steer: true },
  11383. }
  11384. : {
  11385. schemaVersion: 1,
  11386. sessionId: "session-recovered",
  11387. state: "terminal",
  11388. turnId: "turn-recovered",
  11389. actions: { steer: false },
  11390. },
  11391. );
  11392. let durableMessages: Awaited<ReturnType<TuiRuntime["getMessages"]>> = [];
  11393. vi.mocked(runtime.getMessages).mockImplementation(
  11394. async () => durableMessages,
  11395. );
  11396. vi.mocked(runtime.watchEvents).mockImplementation(
  11397. async function* watchEvents(signal) {
  11398. while (!signal.aborted) {
  11399. if (busEvents.length === 0) await waitForNextBusEvent(signal);
  11400. if (signal.aborted) return;
  11401. const event = busEvents.shift();
  11402. if (event) yield event;
  11403. }
  11404. },
  11405. );
  11406. const app = createTuiApp({
  11407. runtime,
  11408. terminal,
  11409. version: "0.1.0",
  11410. workspaceDir: "/workspace",
  11411. });
  11412. app.start();
  11413. await app.ready;
  11414. await app.submit("/resume session-recovered");
  11415. expect(app.tui.render(80).join("\n")).toContain("Loading");
  11416. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  11417. await vi.waitFor(() =>
  11418. expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
  11419. "session-recovered",
  11420. "turn-recovered",
  11421. expect.any(AbortSignal),
  11422. ),
  11423. );
  11424. activeRecoveredTurn = false;
  11425. const historyCallsBeforeTerminal = vi.mocked(runtime.getMessages).mock.calls
  11426. .length;
  11427. durableMessages = [
  11428. {
  11429. id: "message-recovered-assistant",
  11430. turnId: "turn-recovered",
  11431. role: "assistant",
  11432. content: "Recovered answer",
  11433. timestamp: 101,
  11434. },
  11435. ];
  11436. busEvents.push(
  11437. runtimeEvent({
  11438. type: "session.finish",
  11439. timestamp: 101,
  11440. source: "runtime",
  11441. payload: {
  11442. sessionId: "session-recovered",
  11443. turnId: "turn-recovered",
  11444. status: "finished",
  11445. },
  11446. }),
  11447. );
  11448. wakeBus?.();
  11449. wakeBus = undefined;
  11450. await vi.waitFor(() =>
  11451. expect(vi.mocked(runtime.getMessages).mock.calls.length).toBeGreaterThan(
  11452. historyCallsBeforeTerminal,
  11453. ),
  11454. );
  11455. await vi.waitFor(() => {
  11456. const rendered = app.tui.render(80).join("\n");
  11457. expect(rendered).not.toContain("Esc to interrupt");
  11458. expect(app.transcript.snapshot()).toEqual(
  11459. expect.arrayContaining([
  11460. expect.objectContaining({
  11461. kind: "assistant",
  11462. content: "Recovered answer",
  11463. }),
  11464. ]),
  11465. );
  11466. });
  11467. await app.stop();
  11468. });
  11469. it("clears a recovered decision block when switching to a session without a pending decision", async () => {
  11470. const terminal = new FakeTerminal();
  11471. const runtime = createRuntime();
  11472. let controllerSessionId = "";
  11473. const firstSession = {
  11474. sessionId: "session-blocked",
  11475. title: "Blocked session",
  11476. workspaceDir: "/workspace",
  11477. status: "started",
  11478. };
  11479. const secondSession = {
  11480. sessionId: "session-clear",
  11481. title: "Clear session",
  11482. workspaceDir: "/workspace",
  11483. status: "finished",
  11484. };
  11485. vi.mocked(runtime.listSessions).mockResolvedValue([
  11486. firstSession,
  11487. secondSession,
  11488. ]);
  11489. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  11490. sessionId === firstSession.sessionId ? firstSession : secondSession,
  11491. );
  11492. vi.mocked(runtime.listPendingPermissions).mockImplementation(async () =>
  11493. controllerSessionId === firstSession.sessionId
  11494. ? [
  11495. {
  11496. requestId: "permission-blocked",
  11497. sessionId: firstSession.sessionId,
  11498. agentName: "mavis",
  11499. toolName: "bash",
  11500. reason: "Run checks",
  11501. allowAlwaysSupported: true,
  11502. },
  11503. ]
  11504. : [],
  11505. );
  11506. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue(undefined);
  11507. const app = createTuiApp({
  11508. runtime,
  11509. terminal,
  11510. version: "0.1.0",
  11511. workspaceDir: "/workspace",
  11512. });
  11513. await app.ready;
  11514. controllerSessionId = firstSession.sessionId;
  11515. await app.submit("/resume session-blocked");
  11516. expect(app.tui.hasOverlay()).toBe(false);
  11517. expect(app.interaction.isActive()).toBe(true);
  11518. expect(app.tui.render(80).join("\n")).toContain("Approval required");
  11519. controllerSessionId = secondSession.sessionId;
  11520. await app.submit("/resume session-clear");
  11521. expect(app.tui.hasOverlay()).toBe(false);
  11522. const rendered = app.tui.render(80).join("\n");
  11523. expect(rendered).not.toContain("Approval required");
  11524. expect(rendered).not.toContain("Reply required");
  11525. await app.stop();
  11526. });
  11527. it("moves a sending follow-up from the Composer area into the user transcript", async () => {
  11528. const terminal = new FakeTerminal();
  11529. const runtime = createRuntime();
  11530. const busEvents: TuiRuntimeEvent[] = [];
  11531. let wakeBus: (() => void) | undefined;
  11532. const waitForNextBusEvent = (signal: AbortSignal) =>
  11533. new Promise<void>((resolve) => {
  11534. wakeBus = resolve;
  11535. signal.addEventListener("abort", resolve, { once: true });
  11536. });
  11537. vi.mocked(runtime.listSessions).mockResolvedValue([
  11538. {
  11539. sessionId: "session-existing",
  11540. title: "Existing",
  11541. workspaceDir: "/workspace",
  11542. },
  11543. ]);
  11544. vi.mocked(runtime.listQueuedMessages).mockResolvedValue([
  11545. {
  11546. itemId: "queue-with-attachment",
  11547. sessionId: "session-existing",
  11548. status: "queued",
  11549. content: "Review the attached plan",
  11550. attachments: [
  11551. {
  11552. meta: {
  11553. attachmentType: "file",
  11554. fileName: "plan.md",
  11555. mimeType: "text/markdown",
  11556. sizeBytes: 42,
  11557. },
  11558. local: { filePath: "/workspace/plan.md" },
  11559. },
  11560. ],
  11561. },
  11562. {
  11563. itemId: "queue-that-fails",
  11564. sessionId: "session-existing",
  11565. status: "queued",
  11566. content: "Run the failing follow-up",
  11567. },
  11568. ]);
  11569. vi.mocked(runtime.watchEvents).mockImplementation(
  11570. async function* watchEvents(signal) {
  11571. while (!signal.aborted) {
  11572. if (busEvents.length === 0) await waitForNextBusEvent(signal);
  11573. if (signal.aborted) return;
  11574. const event = busEvents.shift();
  11575. if (event) yield event;
  11576. }
  11577. },
  11578. );
  11579. const emitQueueStatus = (
  11580. itemId: string,
  11581. status: string,
  11582. failedReason?: string,
  11583. ) => {
  11584. busEvents.push(
  11585. runtimeEvent({
  11586. type: "session.queue.updated",
  11587. timestamp: Date.now(),
  11588. source: "runtime",
  11589. payload: {
  11590. sessionId: "session-existing",
  11591. itemId,
  11592. status,
  11593. queuedCount: status === "queued" ? 1 : 0,
  11594. ...(failedReason ? { failedReason } : {}),
  11595. },
  11596. }),
  11597. );
  11598. wakeBus?.();
  11599. wakeBus = undefined;
  11600. };
  11601. const app = createTuiApp({
  11602. runtime,
  11603. terminal,
  11604. version: "0.1.0",
  11605. workspaceDir: "/workspace",
  11606. productFeatures: { queue: true },
  11607. });
  11608. app.start();
  11609. await app.ready;
  11610. await app.submit("/resume session-existing");
  11611. expect(app.tui.render(80).join("\n")).toContain("Queue · 2 next");
  11612. expect(app.tui.render(80).join("\n")).toContain("Review the attached plan");
  11613. expect(app.transcript.get("queue:queue-with-attachment")).toBeUndefined();
  11614. emitQueueStatus("queue-with-attachment", "running");
  11615. await vi.waitFor(() =>
  11616. expect(app.transcript.get("queue:queue-with-attachment")).toMatchObject({
  11617. kind: "user",
  11618. status: "succeeded",
  11619. content: expect.stringContaining("Review the attached plan"),
  11620. }),
  11621. );
  11622. expect(app.tui.render(80).join("\n")).not.toContain("SENDING");
  11623. expect(app.tui.render(80).join("\n")).toContain(
  11624. "Next · after current response",
  11625. );
  11626. expect(app.tui.render(80).join("\n")).toContain(
  11627. "Run the failing follow-up",
  11628. );
  11629. expect(
  11630. app.transcript.get("queue:queue-with-attachment")?.attachments,
  11631. ).toEqual([
  11632. expect.objectContaining({
  11633. fileName: "plan.md",
  11634. mimeType: "text/markdown",
  11635. sizeBytes: 42,
  11636. }),
  11637. ]);
  11638. emitQueueStatus("queue-with-attachment", "completed");
  11639. await vi.waitFor(() =>
  11640. expect(app.transcript.get("queue:queue-with-attachment")).toMatchObject({
  11641. kind: "user",
  11642. status: "succeeded",
  11643. content: expect.stringContaining("Review the attached plan"),
  11644. }),
  11645. );
  11646. emitQueueStatus("queue-that-fails", "running");
  11647. await vi.waitFor(() =>
  11648. expect(app.transcript.get("queue:queue-that-fails")).toMatchObject({
  11649. kind: "user",
  11650. status: "succeeded",
  11651. }),
  11652. );
  11653. emitQueueStatus(
  11654. "queue-that-fails",
  11655. "admission-rejected",
  11656. "provider unavailable",
  11657. );
  11658. await vi.waitFor(() =>
  11659. expect(app.editor.getText()).toBe("Run the failing follow-up"),
  11660. );
  11661. expect(app.tui.render(80).join("\n")).toContain(
  11662. "Error Message was not added to the Queue: provider unavailable.",
  11663. );
  11664. expect(app.transcript.get("queue:queue-that-fails")).toMatchObject({
  11665. kind: "user",
  11666. status: "succeeded",
  11667. });
  11668. expect(app.tui.render(80).join("\n")).toContain(
  11669. "Run the failing follow-up",
  11670. );
  11671. await app.stop();
  11672. });
  11673. it("refreshes history when Desktop Runtime finishes an auto-drained queued turn", async () => {
  11674. const terminal = new FakeTerminal();
  11675. const runtime = createRuntime();
  11676. const busEvents: TuiRuntimeEvent[] = [];
  11677. let wakeBus: (() => void) | undefined;
  11678. const waitForNextBusEvent = (signal: AbortSignal) =>
  11679. new Promise<void>((resolve) => {
  11680. wakeBus = resolve;
  11681. signal.addEventListener("abort", resolve, { once: true });
  11682. });
  11683. vi.mocked(runtime.listSessions).mockResolvedValue([
  11684. {
  11685. sessionId: "session-existing",
  11686. title: "Existing",
  11687. workspaceDir: "/workspace",
  11688. },
  11689. ]);
  11690. vi.mocked(runtime.getMessages)
  11691. .mockResolvedValueOnce([])
  11692. .mockResolvedValue([
  11693. {
  11694. id: "message-user-queued",
  11695. turnId: "turn-queued",
  11696. role: "user",
  11697. content: "Runtime follow-up",
  11698. timestamp: 100,
  11699. },
  11700. {
  11701. id: "message-assistant-queued",
  11702. turnId: "turn-queued",
  11703. role: "assistant",
  11704. content: "Runtime follow-up answer",
  11705. timestamp: 101,
  11706. },
  11707. ]);
  11708. vi.mocked(runtime.watchEvents).mockImplementation(
  11709. async function* watchEvents(signal) {
  11710. while (!signal.aborted) {
  11711. if (busEvents.length === 0) {
  11712. await waitForNextBusEvent(signal);
  11713. }
  11714. if (signal.aborted) return;
  11715. const event = busEvents.shift();
  11716. if (event) yield event;
  11717. }
  11718. },
  11719. );
  11720. const emit = (event: RawTuiRuntimeEvent) => {
  11721. busEvents.push(runtimeEvent(event));
  11722. wakeBus?.();
  11723. wakeBus = undefined;
  11724. };
  11725. const app = createTuiApp({
  11726. runtime,
  11727. terminal,
  11728. version: "0.1.0",
  11729. workspaceDir: "/workspace",
  11730. });
  11731. app.start();
  11732. await app.ready;
  11733. await app.submit("/resume session-existing");
  11734. emit({
  11735. type: "session.start",
  11736. timestamp: 100,
  11737. source: "runtime",
  11738. payload: {
  11739. sessionId: "session-existing",
  11740. turnId: "turn-queued",
  11741. source: "queued-drain",
  11742. queueItemIds: ["queue-1"],
  11743. },
  11744. });
  11745. await vi.waitFor(() =>
  11746. expect(app.tui.render(80).join("\n")).toContain("Loading"),
  11747. );
  11748. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  11749. expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
  11750. "session-existing",
  11751. "turn-queued",
  11752. expect.any(AbortSignal),
  11753. );
  11754. emit({
  11755. type: "session.finish",
  11756. timestamp: 101,
  11757. source: "runtime",
  11758. payload: {
  11759. sessionId: "session-existing",
  11760. turnId: "turn-queued",
  11761. status: "finished",
  11762. },
  11763. });
  11764. await vi.waitFor(() =>
  11765. expect(app.transcript.snapshot()).toEqual(
  11766. expect.arrayContaining([
  11767. expect.objectContaining({
  11768. kind: "assistant",
  11769. content: "Runtime follow-up answer",
  11770. }),
  11771. ]),
  11772. ),
  11773. );
  11774. const historyProjectionCalls = vi
  11775. .mocked(runtime.getMessages)
  11776. .mock.calls.filter(
  11777. ([sessionId, limit]) =>
  11778. sessionId === "session-existing" && limit === undefined,
  11779. );
  11780. expect(historyProjectionCalls).toHaveLength(2);
  11781. await app.stop();
  11782. });
  11783. it("writes one structured result when an auto-drained queued turn finishes", async () => {
  11784. const dataDir = await mkdtemp(join(tmpdir(), "mcode-queued-result-"));
  11785. const resultPath = join(dataDir, "results.jsonl");
  11786. const terminal = new FakeTerminal();
  11787. const runtime = createRuntime();
  11788. const busEvents: TuiRuntimeEvent[] = [];
  11789. let wakeBus: (() => void) | undefined;
  11790. let durableMessages: Awaited<ReturnType<TuiRuntime["getMessages"]>> = [];
  11791. vi.mocked(runtime.listSessions).mockResolvedValue([
  11792. {
  11793. sessionId: "session-existing",
  11794. title: "Existing",
  11795. workspaceDir: "/workspace",
  11796. },
  11797. ]);
  11798. vi.mocked(runtime.getMessages).mockImplementation(
  11799. async () => durableMessages,
  11800. );
  11801. const waitForBusEvent = (signal: AbortSignal) =>
  11802. new Promise<void>((resolve) => {
  11803. wakeBus = resolve;
  11804. signal.addEventListener("abort", resolve, { once: true });
  11805. });
  11806. vi.mocked(runtime.watchEvents).mockImplementation(
  11807. async function* watchEvents(signal) {
  11808. while (!signal.aborted) {
  11809. if (busEvents.length === 0) await waitForBusEvent(signal);
  11810. if (signal.aborted) return;
  11811. const event = busEvents.shift();
  11812. if (event) yield event;
  11813. }
  11814. },
  11815. );
  11816. const emit = (event: RawTuiRuntimeEvent) => {
  11817. busEvents.push(runtimeEvent(event));
  11818. wakeBus?.();
  11819. wakeBus = undefined;
  11820. };
  11821. const app = createTuiApp({
  11822. runtime,
  11823. terminal,
  11824. version: "0.1.0",
  11825. workspaceDir: "/workspace",
  11826. statusLineItems: ["build-mode"],
  11827. automationResultPath: resultPath,
  11828. });
  11829. try {
  11830. app.start();
  11831. await app.ready;
  11832. await app.submit("/resume session-existing");
  11833. emit({
  11834. type: "session.start",
  11835. timestamp: 100,
  11836. source: "runtime",
  11837. payload: {
  11838. sessionId: "session-existing",
  11839. turnId: "turn-queued-result",
  11840. source: "queued-drain",
  11841. queueItemIds: ["queue-result"],
  11842. },
  11843. });
  11844. await vi.waitFor(() =>
  11845. expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
  11846. "session-existing",
  11847. "turn-queued-result",
  11848. expect.any(AbortSignal),
  11849. ),
  11850. );
  11851. durableMessages = [
  11852. {
  11853. id: "message-user-result",
  11854. turnId: "turn-queued-result",
  11855. role: "user",
  11856. content: "Queued request",
  11857. timestamp: 101,
  11858. },
  11859. {
  11860. id: "message-assistant-result",
  11861. turnId: "turn-queued-result",
  11862. role: "assistant",
  11863. content: "Queued structured answer",
  11864. timestamp: 102,
  11865. },
  11866. ];
  11867. emit({
  11868. type: "session.finish",
  11869. timestamp: 103,
  11870. source: "runtime",
  11871. payload: {
  11872. sessionId: "session-existing",
  11873. turnId: "turn-queued-result",
  11874. status: "finished",
  11875. },
  11876. });
  11877. await vi.waitFor(async () => {
  11878. const records = (await readFile(resultPath, "utf8"))
  11879. .trim()
  11880. .split("\n")
  11881. .map(JSON.parse);
  11882. expect(records).toEqual([
  11883. expect.objectContaining({
  11884. type: "exec.result",
  11885. sessionId: "session-existing",
  11886. turnId: "turn-queued-result",
  11887. status: "succeeded",
  11888. answer: "Queued structured answer",
  11889. }),
  11890. ]);
  11891. });
  11892. expect(app.controller.snapshot().lastSettledTurn).toEqual({
  11893. sessionId: "session-existing",
  11894. turnId: "turn-queued-result",
  11895. status: "succeeded",
  11896. });
  11897. } finally {
  11898. await app.stop();
  11899. await rm(dataDir, { recursive: true, force: true });
  11900. }
  11901. });
  11902. it("settles an auto-drained follow-up once and replaces waiting state with run duration", async () => {
  11903. const terminal = new FakeTerminal();
  11904. const runtime = createRuntime();
  11905. const busEvents: TuiRuntimeEvent[] = [];
  11906. const queuedItems: TuiQueuedMessage[] = [];
  11907. let wakeBus: (() => void) | undefined;
  11908. let finishFirstTurn: (() => void) | undefined;
  11909. let finishQueuedStream: (() => void) | undefined;
  11910. const queuedStreamClosed = vi.fn();
  11911. let durableMessages: Awaited<ReturnType<TuiRuntime["getMessages"]>> = [];
  11912. const waitForNextBusEvent = (signal: AbortSignal) =>
  11913. new Promise<void>((resolve) => {
  11914. wakeBus = resolve;
  11915. signal.addEventListener("abort", resolve, { once: true });
  11916. });
  11917. vi.mocked(runtime.sendMessage).mockImplementation(
  11918. async function* sendMessage() {
  11919. await new Promise<void>((resolve) => {
  11920. finishFirstTurn = resolve;
  11921. });
  11922. yield { type: "delta", content: "First answer" };
  11923. yield { type: "done" };
  11924. },
  11925. );
  11926. vi.mocked(runtime.watchSessionTurn).mockImplementation(
  11927. async function* watchSessionTurn() {
  11928. try {
  11929. await new Promise<void>((resolve) => {
  11930. finishQueuedStream = resolve;
  11931. });
  11932. yield { type: "delta", content: "Queued answer" };
  11933. yield { type: "done" };
  11934. } finally {
  11935. queuedStreamClosed();
  11936. }
  11937. },
  11938. );
  11939. vi.mocked(runtime.enqueueMessage).mockImplementation(
  11940. async (sessionId, content) => {
  11941. const item: TuiQueuedMessage = {
  11942. itemId: "queue-b",
  11943. sessionId,
  11944. status: "queued",
  11945. content,
  11946. };
  11947. queuedItems.push(item);
  11948. return { itemId: item.itemId, status: item.status, position: 1 };
  11949. },
  11950. );
  11951. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  11952. ...queuedItems,
  11953. ]);
  11954. vi.mocked(runtime.getMessages).mockImplementation(
  11955. async () => durableMessages,
  11956. );
  11957. vi.mocked(runtime.watchEvents).mockImplementation(
  11958. async function* watchEvents(signal) {
  11959. while (!signal.aborted) {
  11960. if (busEvents.length === 0) await waitForNextBusEvent(signal);
  11961. if (signal.aborted) return;
  11962. const event = busEvents.shift();
  11963. if (event) yield event;
  11964. }
  11965. },
  11966. );
  11967. const emit = (event: RawTuiRuntimeEvent) => {
  11968. busEvents.push(runtimeEvent(event));
  11969. wakeBus?.();
  11970. wakeBus = undefined;
  11971. };
  11972. const app = createTuiApp({
  11973. runtime,
  11974. terminal,
  11975. version: "0.1.0",
  11976. workspaceDir: "/workspace",
  11977. productFeatures: { queue: true },
  11978. });
  11979. app.start();
  11980. await app.ready;
  11981. const first = app.submit("A");
  11982. await vi.waitFor(() =>
  11983. expect(app.controller.snapshot().activeTurnId).toBeDefined(),
  11984. );
  11985. await app.submit("B");
  11986. expect(app.tui.render(80).join("\n")).toContain(
  11987. "Next · after current response",
  11988. );
  11989. expect(app.tui.render(80).join("\n")).toContain("B");
  11990. finishFirstTurn?.();
  11991. await first;
  11992. const queuedItem = queuedItems[0];
  11993. expect(queuedItem).toBeDefined();
  11994. if (!queuedItem) throw new Error("Expected B to be queued.");
  11995. queuedItems[0] = { ...queuedItem, status: "running" };
  11996. emit({
  11997. type: "session.queue.updated",
  11998. timestamp: 200,
  11999. source: "runtime",
  12000. payload: {
  12001. sessionId: "session-1",
  12002. itemId: "queue-b",
  12003. status: "running",
  12004. queuedCount: 0,
  12005. },
  12006. });
  12007. emit({
  12008. type: "session.start",
  12009. timestamp: 201,
  12010. source: "runtime",
  12011. payload: {
  12012. sessionId: "session-1",
  12013. turnId: "turn_queue_b",
  12014. source: "queued-drain",
  12015. queueItemIds: ["queue-b"],
  12016. },
  12017. });
  12018. await vi.waitFor(() =>
  12019. expect(app.tui.render(80).join("\n")).toContain("Loading"),
  12020. );
  12021. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  12022. queuedItems.length = 0;
  12023. durableMessages = [
  12024. {
  12025. id: "history-user-b",
  12026. turnId: "turn_queue_b",
  12027. role: "user",
  12028. content: "B",
  12029. timestamp: 202,
  12030. },
  12031. {
  12032. id: "history-assistant-b",
  12033. turnId: "turn_queue_b",
  12034. role: "assistant",
  12035. content: "Queued answer",
  12036. timestamp: 203,
  12037. },
  12038. ];
  12039. finishQueuedStream?.();
  12040. await vi.waitFor(() => expect(queuedStreamClosed).toHaveBeenCalledOnce());
  12041. emit({
  12042. type: "session.finish",
  12043. timestamp: 3_201,
  12044. source: "runtime",
  12045. payload: {
  12046. sessionId: "session-1",
  12047. turnId: "turn_queue_b",
  12048. status: "finished",
  12049. },
  12050. });
  12051. await vi.waitFor(() =>
  12052. expect(
  12053. app.transcript
  12054. .snapshot()
  12055. .filter((cell) => cell.content === "Queued answer"),
  12056. ).toHaveLength(1),
  12057. );
  12058. await vi.waitFor(() =>
  12059. expect(app.transcript.get("turn-duration:turn_queue_b")).toMatchObject({
  12060. status: "succeeded",
  12061. durationMs: 3_000,
  12062. }),
  12063. );
  12064. const settledUi = app.tui.render(80).join("\n");
  12065. expect(settledUi).toContain("Completed in 3s");
  12066. expect(settledUi.indexOf("Completed in 3s")).toBeGreaterThan(
  12067. settledUi.indexOf("Queued answer"),
  12068. );
  12069. expect(settledUi).not.toContain("message waiting");
  12070. expect(settledUi).not.toContain("Next · after current response");
  12071. await app.stop();
  12072. });
  12073. it("records submitted drafts in editor history", async () => {
  12074. const terminal = new FakeTerminal();
  12075. const runtime = createRuntime();
  12076. const app = createTuiApp({
  12077. runtime,
  12078. terminal,
  12079. version: "0.1.0",
  12080. workspaceDir: "/workspace",
  12081. });
  12082. await app.ready;
  12083. app.editor.setText("Remember this draft");
  12084. app.editor.handleInput("\r");
  12085. await vi.waitFor(() =>
  12086. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  12087. );
  12088. app.editor.handleInput("\u001b[A");
  12089. expect(app.editor.getText()).toBe("Remember this draft");
  12090. });
  12091. it("continues sending and switching sessions when draft cleanup fails", async () => {
  12092. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-warning-"));
  12093. const runtime = createRuntime();
  12094. const app = createTuiApp({
  12095. runtime,
  12096. terminal: new FakeTerminal(),
  12097. version: "0.1.0",
  12098. dataDir,
  12099. workspaceDir: "/workspace",
  12100. });
  12101. const flush = vi.spyOn(TuiDraftRecovery.prototype, "flush");
  12102. try {
  12103. await app.ready;
  12104. flush.mockRejectedValue(
  12105. new TuiDraftRecoveryError("cleanup", new Error("deletion denied")),
  12106. );
  12107. app.editor.setText("hello");
  12108. app.editor.handleInput("\r");
  12109. await vi.waitFor(() =>
  12110. expect(
  12111. app.transcript.snapshot().filter((cell) => cell.kind === "warning"),
  12112. ).toHaveLength(1),
  12113. );
  12114. const warnings = app.transcript
  12115. .snapshot()
  12116. .filter((cell) => cell.kind === "warning");
  12117. expect(warnings[0]?.content).toContain(
  12118. composerText("draftCleanupNextStep"),
  12119. );
  12120. expect(warnings[0]?.content).not.toContain(
  12121. composerText("draftRecoveryUnavailable"),
  12122. );
  12123. expect(warnings[0]?.content).toContain("deletion denied");
  12124. await vi.waitFor(() =>
  12125. expect(runtime.sendMessage).toHaveBeenCalledOnce(),
  12126. );
  12127. await vi.waitFor(() =>
  12128. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  12129. );
  12130. await expect(app.openSession("session-2")).resolves.toBeUndefined();
  12131. expect(app.controller.snapshot().session?.sessionId).toBe("session-2");
  12132. app.editor.setText("after switching");
  12133. app.editor.handleInput("\r");
  12134. await vi.waitFor(() =>
  12135. expect(runtime.sendMessage).toHaveBeenCalledTimes(2),
  12136. );
  12137. await expect(app.stop()).resolves.toBeUndefined();
  12138. } finally {
  12139. await app.stop();
  12140. flush.mockRestore();
  12141. await rm(dataDir, { recursive: true, force: true });
  12142. }
  12143. });
  12144. it("does not read or restore a persisted Draft during TUI startup", async () => {
  12145. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-"));
  12146. try {
  12147. const first = createTuiApp({
  12148. runtime: createRuntime(),
  12149. terminal: new FakeTerminal(),
  12150. version: "0.1.0",
  12151. dataDir,
  12152. workspaceDir: "/workspace/recovery",
  12153. });
  12154. await first.ready;
  12155. first.editor.setText("/exit");
  12156. await first.stop();
  12157. const loadDraft = vi.spyOn(TuiDraftRecovery.prototype, "load");
  12158. const restored = createTuiApp({
  12159. runtime: createRuntime(),
  12160. terminal: new FakeTerminal(),
  12161. version: "0.1.0",
  12162. dataDir,
  12163. workspaceDir: "/workspace/recovery",
  12164. });
  12165. await restored.ready;
  12166. expect(loadDraft).not.toHaveBeenCalled();
  12167. expect(restored.editor.getText()).toBe("");
  12168. expect(restored.tui.render(80).join("\n")).not.toContain(
  12169. "Draft restored",
  12170. );
  12171. loadDraft.mockRestore();
  12172. restored.editor.setText("");
  12173. await restored.stop();
  12174. } finally {
  12175. await rm(dataDir, { recursive: true, force: true });
  12176. }
  12177. });
  12178. it("does not resume a persisted Draft during startup when login recovery is enabled", async () => {
  12179. const dataDir = await mkdtemp(join(tmpdir(), "mcode-login-restart-draft-"));
  12180. try {
  12181. const first = createTuiApp({
  12182. runtime: createRuntime(),
  12183. terminal: new FakeTerminal(),
  12184. version: "0.1.0",
  12185. dataDir,
  12186. workspaceDir: "/workspace/login-recovery",
  12187. });
  12188. await first.ready;
  12189. first.editor.setText("send after Global login");
  12190. await first.stop();
  12191. const restored = createTuiApp({
  12192. runtime: createRuntime(),
  12193. terminal: new FakeTerminal(),
  12194. version: "0.1.0",
  12195. dataDir,
  12196. workspaceDir: "/workspace/login-recovery",
  12197. resumeDraftAfterLogin: true,
  12198. });
  12199. await restored.ready;
  12200. restored.start();
  12201. expect(restored.editor.getText()).toBe("");
  12202. expect(restored.getSurface()).toBe("welcome");
  12203. expect(restored.tui.render(80).join("\n")).toContain(
  12204. "Tips for getting started",
  12205. );
  12206. await restored.stop();
  12207. } finally {
  12208. await rm(dataDir, { recursive: true, force: true });
  12209. }
  12210. });
  12211. it("keeps the submitted Draft recoverable when shutdown wins before Runtime admission", async () => {
  12212. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-pending-draft-"));
  12213. try {
  12214. const runtime = createRuntime();
  12215. vi.spyOn(runtime, "sendMessage").mockImplementation(
  12216. async function* sendMessage(
  12217. _req: SendMessageReq,
  12218. signal?: AbortSignal,
  12219. ) {
  12220. yield* [];
  12221. await new Promise<void>((_resolve, reject) => {
  12222. signal?.addEventListener(
  12223. "abort",
  12224. () => reject(new Error("admission aborted")),
  12225. {
  12226. once: true,
  12227. },
  12228. );
  12229. });
  12230. throw new Error("unreachable");
  12231. },
  12232. );
  12233. const first = createTuiApp({
  12234. runtime,
  12235. terminal: new FakeTerminal(),
  12236. version: "0.1.0",
  12237. dataDir,
  12238. workspaceDir: "/workspace/pending-recovery",
  12239. });
  12240. await first.ready;
  12241. first.editor.setText("recover me until Runtime accepts");
  12242. await new Promise((resolve) => setTimeout(resolve, 300));
  12243. first.editor.handleInput("\r");
  12244. await vi.waitFor(() =>
  12245. expect(runtime.sendMessage).toHaveBeenCalledOnce(),
  12246. );
  12247. await first.stop();
  12248. const restored = createTuiApp({
  12249. runtime: createRuntime(),
  12250. terminal: new FakeTerminal(),
  12251. version: "0.1.0",
  12252. dataDir,
  12253. workspaceDir: "/workspace/pending-recovery",
  12254. });
  12255. await restored.ready;
  12256. await restored.openSession("session-1");
  12257. expect(restored.editor.getText()).toBe(
  12258. "recover me until Runtime accepts",
  12259. );
  12260. const rendered = restored.tui.render(80).join("\n");
  12261. expect(rendered).toContain("recover me until Runtime accepts");
  12262. expect(rendered).not.toContain("Message kept under Failed");
  12263. await restored.stop();
  12264. } finally {
  12265. await rm(dataDir, { recursive: true, force: true });
  12266. }
  12267. });
  12268. it("does not restore a submitted Draft after Runtime accepts the turn", async () => {
  12269. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-accepted-draft-"));
  12270. try {
  12271. const runtime = createRuntime();
  12272. vi.mocked(runtime.sendMessage).mockImplementation(
  12273. async function* sendMessage(
  12274. _req: SendMessageReq,
  12275. signal?: AbortSignal,
  12276. ) {
  12277. await new Promise<void>((resolve) => {
  12278. signal?.addEventListener("abort", resolve, { once: true });
  12279. });
  12280. yield { type: "done" };
  12281. },
  12282. );
  12283. const first = createTuiApp({
  12284. runtime,
  12285. terminal: new FakeTerminal(),
  12286. version: "0.1.0",
  12287. dataDir,
  12288. workspaceDir: "/workspace/accepted-recovery",
  12289. });
  12290. await first.ready;
  12291. first.editor.setText("already accepted by Runtime");
  12292. await new Promise((resolve) => setTimeout(resolve, 300));
  12293. first.editor.handleInput("\r");
  12294. await vi.waitFor(() =>
  12295. expect(runtime.sendMessage).toHaveBeenCalledOnce(),
  12296. );
  12297. await first.stop();
  12298. const restored = createTuiApp({
  12299. runtime: createRuntime(),
  12300. terminal: new FakeTerminal(),
  12301. version: "0.1.0",
  12302. dataDir,
  12303. workspaceDir: "/workspace/accepted-recovery",
  12304. });
  12305. await restored.ready;
  12306. expect(restored.editor.getText()).toBe("");
  12307. await restored.stop();
  12308. } finally {
  12309. await rm(dataDir, { recursive: true, force: true });
  12310. }
  12311. });
  12312. it("serializes rapid Session switches without mixing their Drafts", async () => {
  12313. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-"));
  12314. try {
  12315. const app = createTuiApp({
  12316. runtime: createRuntime(),
  12317. terminal: new FakeTerminal(),
  12318. version: "0.1.0",
  12319. dataDir,
  12320. workspaceDir: "/workspace/recovery",
  12321. });
  12322. await app.ready;
  12323. await app.openSession("session-a");
  12324. app.editor.setText("Draft for Session A");
  12325. await app.openSession("session-b");
  12326. app.editor.setText("Draft for Session B");
  12327. await Promise.all([
  12328. app.openSession("session-a"),
  12329. app.openSession("session-b"),
  12330. ]);
  12331. expect(app.controller.snapshot().session?.sessionId).toBe("session-b");
  12332. expect(app.editor.getText()).toBe("Draft for Session B");
  12333. await app.openSession("session-a");
  12334. expect(app.editor.getText()).toBe("Draft for Session A");
  12335. await app.openSession("session-b");
  12336. expect(app.editor.getText()).toBe("Draft for Session B");
  12337. await app.stop();
  12338. } finally {
  12339. await rm(dataDir, { recursive: true, force: true });
  12340. }
  12341. });
  12342. it("moves to the new-session Draft namespace after archiving the current Session", async () => {
  12343. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-"));
  12344. try {
  12345. const app = createTuiApp({
  12346. runtime: createRuntime(),
  12347. terminal: new FakeTerminal(),
  12348. version: "0.1.0",
  12349. dataDir,
  12350. workspaceDir: "/workspace/recovery",
  12351. });
  12352. await app.ready;
  12353. await app.openSession("session-a");
  12354. app.editor.setText("Archived Session Draft");
  12355. await app.submit("/archive");
  12356. app.editor.setText("Fresh Session Draft");
  12357. await app.openSession("session-a");
  12358. expect(app.editor.getText()).toBe("Archived Session Draft");
  12359. await app.submit("/new");
  12360. expect(app.editor.getText()).toBe("Fresh Session Draft");
  12361. await app.stop();
  12362. } finally {
  12363. await rm(dataDir, { recursive: true, force: true });
  12364. }
  12365. });
  12366. });