| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418 |
- import { describe, expect, it, vi } from "vitest";
- import { mkdtemp, readFile, rm, writeFile, mkdir } from "node:fs/promises";
- import { tmpdir } from "node:os";
- import { join } from "node:path";
- import type { TerminalCapabilities } from "../../src/tui/platform/terminal-capabilities.js";
- import {
- TuiAltScreen,
- VStack,
- type Terminal,
- } from "../../src/tui/engine/public.js";
- import { createTuiProgram } from "../../src/cli/program.js";
- import { resolveTuiStartupEnvironmentOption } from "../../src/cli/environment.js";
- import { runTuiCli } from "../../src/cli/main.js";
- import { launchTui } from "../../src/tui/launcher.js";
- import { createTuiApp } from "../../src/tui/app.js";
- import type {
- TuiModel,
- TuiQuestionnaireRequest,
- TuiQueuedMessage,
- TuiRuntimeEvent,
- TuiRuntime,
- TuiSessionForkPort,
- TuiStreamEvent,
- } from "../../src/runtime/port.js";
- import {
- normalizeTuiRuntimeEvent,
- type RawTuiRuntimeEvent,
- } from "../../src/runtime/event-normalizer.js";
- import type { SendMessageReq } from "@mavis/local-runtime-v2/cli-service";
- import type { TuiObservability } from "../../src/observability/local-observability.js";
- import type { McodeAuthProgress } from "../../src/auth/application.js";
- import { formatTuiShortcut } from "../../src/tui/shell/shortcut-labels.js";
- import { createTuiHostKeybindings } from "../../src/tui/shell/keybindings.js";
- import { stripAnsi } from "../../src/tui/rendering/text.js";
- import {
- TuiDraftRecovery,
- TuiDraftRecoveryError,
- } from "../../src/tui/features/composer/draft-recovery.js";
- import { composerText } from "../../src/tui/features/composer/copy.js";
- import type {
- McodeBusinessEvent,
- McodeBusinessTelemetry,
- } from "../../src/analytics/business-telemetry.js";
- import { VirtualTerminalScreen } from "../helpers/virtual-terminal.js";
- import { TuiFailure } from "../../src/failure.js";
- const runtimeEvent = (event: RawTuiRuntimeEvent): TuiRuntimeEvent =>
- normalizeTuiRuntimeEvent(event);
- function planReviewEventRequest(id: string) {
- return {
- schemaVersion: 2,
- id,
- mode: "plan",
- modePayload: {
- planReview: {
- markdown: "# Frozen plan\n\nImplement and verify the change.",
- path: "/history/session-1/artifacts/plan.md",
- },
- },
- presentation: {
- replaceComposer: true,
- showProgress: true,
- allowBackNavigation: true,
- },
- steps: [
- {
- id: "plan-review",
- question: "Approve?",
- selectionMode: "single",
- options: [{ id: "approve", label: "Approve" }],
- allowOther: true,
- required: true,
- },
- ],
- } as const;
- }
- function planEntryEventRequest(id: string) {
- return {
- schemaVersion: 2,
- id,
- mode: "plan",
- presentation: {
- replaceComposer: true,
- showProgress: true,
- allowBackNavigation: true,
- },
- steps: [
- {
- id: "plan-enter",
- question: "Enter Plan Mode for this task?",
- selectionMode: "single",
- options: [
- { id: "confirm", label: "Confirm" },
- { id: "decline", label: "Decline" },
- ],
- allowOther: true,
- otherPlaceholder: "Others...",
- required: true,
- },
- ],
- } as const;
- }
- function createObservability(): TuiObservability {
- return {
- recordStartup: vi.fn(),
- recordAccess: vi.fn(),
- recordEventStream: vi.fn(),
- recordTerminal: vi.fn(),
- recordProcessStop: vi.fn(),
- observeRender: vi.fn(),
- snapshot: vi.fn(() => ({
- filePath: "/tmp/mcode-observability.jsonl",
- eventCounts: {
- startup: 0,
- runtimeAccess: 0,
- eventStream: 0,
- terminal: 0,
- },
- accessSources: {},
- reconnects: 0,
- render: {
- frames: 0,
- averageDurationMs: 0,
- maxDurationMs: 0,
- p95DurationMs: 0,
- },
- })),
- flush: vi.fn(async () => undefined),
- };
- }
- class FakeTerminal implements Terminal {
- columns = 80;
- rows = 18;
- kittyProtocolActive = false;
- started = false;
- stopped = false;
- startCount = 0;
- stopCount = 0;
- drainCount = 0;
- title = "";
- titleUpdates: string[] = [];
- mouseTracking = false;
- mouseTrackingUpdates: boolean[] = [];
- writes: string[] = [];
- input?: (data: string) => void;
- start(onInput: (data: string) => void): void {
- this.started = true;
- this.stopped = false;
- this.startCount += 1;
- this.input = onInput;
- }
- stop(): void {
- this.stopped = true;
- this.stopCount += 1;
- }
- drainInput(): Promise<void> {
- this.drainCount += 1;
- return Promise.resolve();
- }
- write(data: string): void {
- this.writes.push(data);
- }
- moveBy(): void {}
- hideCursor(): void {}
- showCursor(): void {}
- clearLine(): void {}
- clearFromCursor(): void {}
- clearScreen(): void {}
- setProgress(): void {}
- setMouseTracking(enabled: boolean): void {
- this.mouseTracking = enabled;
- this.mouseTrackingUpdates.push(enabled);
- }
- setTitle(title: string): void {
- this.title = title;
- this.titleUpdates.push(title);
- }
- }
- function renderTerminalViewport(
- app: ReturnType<typeof createTuiApp>,
- terminal: FakeTerminal,
- ): string {
- app.tui.renderNow();
- const screen = new VirtualTerminalScreen(terminal.columns, terminal.rows);
- try {
- for (const write of terminal.writes) screen.feed(write);
- return screen.viewportText();
- } finally {
- screen.dispose();
- }
- }
- function createRuntime(): TuiRuntime {
- const abortSession = vi.fn(async () => true);
- let currentGoal: Awaited<ReturnType<TuiRuntime["getGoal"]>>;
- let createdSession:
- | {
- sessionId: string;
- title: string;
- workspaceDir: string;
- interactionMode?: "plan";
- }
- | undefined;
- const runtime: TuiRuntime = {
- createSession: vi.fn(async () => {
- createdSession = {
- sessionId: "session-1",
- title: "New session",
- workspaceDir: "/workspace",
- };
- return { ...createdSession };
- }),
- listSessions: vi.fn(async () => []),
- listSessionPage: vi.fn(async () => ({
- sessions: [],
- hasMore: false,
- })),
- getSession: vi.fn(async (sessionId: string) =>
- createdSession?.sessionId === sessionId
- ? { ...createdSession }
- : {
- sessionId,
- title: "Existing session",
- workspaceDir: "/workspace",
- },
- ),
- getMessages: vi.fn(async () => []),
- listMessagePage: vi.fn(async () => ({ messages: [], hasMore: false })),
- getSessionForkOptions: vi.fn(async () => ({
- canFork: true,
- worktreeVisible: false,
- worktreeEligible: false,
- })),
- forkSession: vi.fn(async () => ({
- session: {
- sessionId: "session-fork",
- parentSessionId: "session-1",
- title: "New session (fork 1)",
- workspaceDir: "/workspace",
- },
- })),
- getWorkspaceGitMetadata: vi.fn(async () => ({
- isGitRepo: false,
- branch: "",
- detached: false,
- isWorktree: false,
- })),
- renameSession: vi.fn(async (sessionId: string, title: string) => ({
- sessionId,
- title,
- workspaceDir: "/workspace",
- })),
- archiveSession: vi.fn(async () => undefined),
- listSessionInputSummaries: vi.fn(async () => []),
- getSessionRewindPreview: vi.fn(async () => ({ turns: [] })),
- rewindSession: vi.fn(async () => ({ rewound: true })),
- editSessionMessage: vi.fn(async () => ({
- rewound: true,
- turnId: "turn-edit-1",
- userMessageId: "msg-user-v1-edited",
- })),
- isGoalEnabled: vi.fn(() => true),
- getGoal: vi.fn(async () => currentGoal),
- createGoal: vi.fn(async ({ sessionId, objective, attachments }) => {
- currentGoal = {
- goalId: "goal-1",
- sessionId,
- objective,
- status: "active",
- createdAt: 10,
- updatedAt: 10,
- tokensUsed: 0,
- turnsUsed: 0,
- timeUsedSeconds: 0,
- tokenBudget: null,
- statusReason: null,
- hasKickoffAttachments: Boolean(attachments?.length),
- };
- return currentGoal;
- }),
- patchGoal: vi.fn(async (_sessionId, patch) => {
- if (!currentGoal) throw new Error("Goal not found");
- currentGoal = {
- ...currentGoal,
- ...patch,
- updatedAt: currentGoal.updatedAt + 1,
- };
- return currentGoal;
- }),
- clearGoal: vi.fn(async () => {
- const existed = Boolean(currentGoal);
- currentGoal = undefined;
- return existed;
- }),
- getInstructionSources: vi.fn(async () => []),
- getRuntimeDiagnostics: vi.fn(async () => ({
- status: "ok",
- surface: "cli-standalone",
- runtimeMode: "clean",
- runtimeOwnerKind: "cli",
- runtimeOwnerId: "minimax-code",
- dataDir: "/home/dev/.minimax",
- configPath: "/home/dev/.minimax/config.yaml",
- configPresent: true,
- authCachePresent: true,
- defaultModel: "minimax/MiniMax-M2.7",
- providerId: "minimax",
- modelId: "MiniMax-M2.7",
- authMode: "managed-login",
- authModeSource: "explicit",
- managedTokenPresent: true,
- apiKeyPresent: false,
- customProviderCount: 0,
- warnings: [],
- })),
- prepareFeedback: vi.fn(async ({ description, sessionId }) => ({
- schemaVersion: 1 as const,
- draftId: "feedback-draft-1",
- description,
- diagnostics: [
- { label: "Client", value: "mcode 0.1.0" },
- { label: "Runtime", value: "clean · cli" },
- { label: "Session", value: sessionId ?? "not included" },
- ],
- included: ["redacted feedback description"],
- excluded: ["credentials and tokens", "conversation prompts and messages"],
- expiresAtMs: Date.now() + 60_000,
- })),
- submitFeedback: vi.fn(async () => ({
- schemaVersion: 1 as const,
- ticketId: "ticket-1",
- status: "processing" as const,
- createdAtMs: Date.now(),
- })),
- cancelFeedback: vi.fn(async () => true),
- runDailyCheckin: vi.fn(async () => ({
- status: "claimed" as const,
- dayNo: 2,
- points: 20,
- expireAtMs: 1_800_000_000_000,
- panel: {
- scene: 2,
- days: Array.from({ length: 7 }, (_, index) => ({
- day_no: index + 1,
- points: (index + 1) * 10,
- status: index <= 1 ? 3 : 1,
- is_today: index === 1,
- })),
- },
- })),
- getAccountStatus: vi.fn(async () => ({
- status: "ready",
- defaultModel: "minimax/MiniMax-M2.7",
- providerId: "minimax",
- modelId: "MiniMax-M2.7",
- authMode: "managed-login",
- managedTokenPresent: true,
- warnings: [],
- })),
- listProviderPresets: vi.fn(async () => []),
- getCodexOAuthStatus: vi.fn(async () => ({
- state: "hidden" as const,
- providerId: "openai-codex" as const,
- })),
- startCodexOAuthLogin: vi.fn(async () => ({
- state: "hidden" as const,
- providerId: "openai-codex" as const,
- })),
- getPermissionMode: vi.fn(async () => "auto" as const),
- setPermissionMode: vi.fn(async (mode) => mode),
- getPlanModeCapabilities: vi.fn(async () => ({ entryEnabled: true })),
- getPendingQuestionnaire: vi.fn(async () => undefined),
- getLatestPlanReview: vi.fn(async () => undefined),
- replyQuestionnaire: vi.fn(async () => true),
- dismissQuestionnaire: vi.fn(async () => true),
- listPendingPermissions: vi.fn(async () => []),
- replyPermission: vi.fn(async () => true),
- listModels: vi.fn(async () => [
- {
- providerId: "minimax",
- modelId: "MiniMax-M2.7",
- displayName: "MiniMax M2.7",
- providerKind: "minimax-managed",
- selected: true,
- },
- ]),
- selectModel: vi.fn(async () => true),
- getSessionUsage: vi.fn(async () => ({
- summary: {
- inputTokens: 100,
- outputTokens: 20,
- totalTokens: 120,
- turns: 1,
- },
- rows: [],
- })),
- requestCompaction: vi.fn(async () => ({
- success: true,
- sessionId: "session-1",
- compactionId: "compact-1",
- messagesBefore: 12,
- messagesAfter: 4,
- tokensBefore: 4000,
- tokensAfter: 1200,
- })),
- getContextSnapshot: vi.fn(async () => ({ status: "empty" as const })),
- getActiveRun: vi.fn(async (sessionId: string) => ({
- schemaVersion: 1 as const,
- sessionId,
- state: "idle" as const,
- actions: { steer: false },
- })),
- getDelegationSnapshot: vi.fn(async (rootSessionId: string) => ({
- schemaVersion: 1 as const,
- rootSessionId,
- members: [],
- })),
- stopDelegation: vi.fn(async (rootSessionId: string) => ({
- schemaVersion: 1 as const,
- rootSessionId,
- rootStopped: await abortSession({ id: rootSessionId }),
- stoppedSessionIds: [],
- activeSessionIds: [],
- failedSessionIds: [],
- })),
- steer: vi.fn(async (input) => ({
- turnId: input.requestedTurnId ?? "turn-steer",
- mode: input.requestedTurnId
- ? ("steered" as const)
- : ("activated" as const),
- ...(input.requestedTurnId
- ? {}
- : {
- completion:
- (async function* completion(): AsyncGenerator<TuiStreamEvent> {
- yield { type: "done", turnId: "turn-steer" };
- })(),
- }),
- })),
- listSkills: vi.fn(async () => ({
- skills: [
- {
- name: "docs",
- displayName: "Docs",
- description: "Read project docs",
- enabled: true,
- sourceKind: "builtin",
- },
- ],
- hasMore: false,
- })),
- inspectProjectMcp: vi.fn(async () => undefined),
- listMcpServers: vi.fn(async () => [
- {
- name: "browser",
- enabled: true,
- transport: "stdio",
- description: "Browser tools",
- configJson: '{"env":{"TOKEN":"hidden"}}',
- },
- ]),
- listQueuedMessages: vi.fn(async () => []),
- getQueueSnapshot: vi.fn(async (sessionId: string) => {
- const items = await runtime.listQueuedMessages(sessionId);
- return {
- items,
- paused: items.some((item) => item.status === "paused"),
- pendingCount: items.length,
- };
- }),
- continueQueue: vi.fn(async () => undefined),
- steerQueuedMessage: vi.fn(async (_sessionId: string, itemId: string) => ({
- queueItemId: itemId,
- turnId: "turn-steered-queue",
- })),
- enqueueMessage: vi.fn(async () => ({
- itemId: "queue-1",
- status: "queued",
- position: 1,
- })),
- updateQueuedMessageContent: vi.fn(async () => undefined),
- deleteQueuedMessage: vi.fn(async () => undefined),
- watchEvents: vi.fn(async function* watchEvents(signal) {
- await new Promise<void>((resolve) => {
- signal.addEventListener("abort", resolve, { once: true });
- });
- for (const event of [] as TuiRuntimeEvent[]) yield event;
- }),
- watchSessionTurn: vi.fn(async function* watchSessionTurn() {}),
- sendMessage: vi.fn(
- async function* sendMessage(request): AsyncGenerator<TuiStreamEvent> {
- if (createdSession?.sessionId === request.id) {
- if (request.clientIntent === "plan-entry")
- createdSession.interactionMode = "plan";
- if (request.clientIntent === "plan-exit")
- delete createdSession.interactionMode;
- }
- yield { type: "delta", content: "Hello from the Agent" };
- yield { type: "done" };
- },
- ),
- abortSession,
- };
- return runtime;
- }
- describe("createTuiApp", () => {
- it.each(["regular", "fullscreen"] as const)(
- "configures /statusline from terminal input and reopens the saved selection in %s mode",
- async (tuiMode) => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const persistStatusLineItems = vi.fn(async () => undefined);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "test",
- workspaceDir: "/workspace",
- tuiMode,
- statusLineItems: ["current-dir"],
- persistStatusLineItems,
- });
- try {
- app.start();
- await app.ready;
- app.editor.setText("/statusline");
- terminal.input?.("\r");
- await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
- expect(stripAnsi(app.interaction.render(80).join("\n"))).toContain(
- "[x] current-dir",
- );
- terminal.input?.(" ");
- terminal.input?.("\r");
- await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
- expect(persistStatusLineItems).toHaveBeenCalledWith([]);
- app.editor.setText("/statusline");
- terminal.input?.("\r");
- await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
- expect(stripAnsi(app.interaction.render(80).join("\n"))).toContain(
- "[ ] current-dir",
- );
- terminal.input?.("\x1b");
- expect(app.interaction.isActive()).toBe(false);
- expect(persistStatusLineItems).toHaveBeenCalledOnce();
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- } finally {
- await app.stop();
- }
- },
- );
- it.each([
- ["regular", false],
- ["regular", true],
- ["fullscreen", false],
- ["fullscreen", true],
- ] as const)(
- "runs ls unchanged in %s mode after empty-prefix Tab: %s",
- async (tuiMode, pressTab) => {
- const directory = await mkdtemp(join(tmpdir(), "tui-ls-enter-"));
- await mkdir(join(directory, "aaa-directory"));
- await writeFile(join(directory, "root-only.txt"), "root");
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: directory,
- tuiMode,
- });
- try {
- app.start();
- await app.ready;
- app.editor.setText("!ls");
- terminal.input?.(" ");
- expect(stripAnsi(app.editor.render(100).join("\n"))).not.toContain(
- "aaa-directory/",
- );
- if (pressTab) {
- terminal.input?.("\t");
- await vi.waitFor(() =>
- expect(stripAnsi(app.editor.render(100).join("\n"))).toContain(
- "aaa-directory/",
- ),
- );
- }
- expect(app.editor.getText()).toBe("!ls ");
- terminal.input?.("\r");
- await vi.waitFor(
- () =>
- expect(
- app.transcript.snapshot().find((cell) => cell.kind === "shell")
- ?.status,
- ).toBe("succeeded"),
- { timeout: 5000 },
- );
- expect(
- app.transcript.snapshot().find((cell) => cell.kind === "shell"),
- ).toMatchObject({
- title: "! ls",
- content: expect.stringContaining("root-only.txt"),
- });
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- } finally {
- await app.stop();
- await rm(directory, { recursive: true, force: true });
- }
- },
- );
- it.each(["regular", "fullscreen"] as const)(
- "completes a shell path from terminal input in %s mode before executing",
- async (tuiMode) => {
- const directory = await mkdtemp(
- join(tmpdir(), "tui-shell-completion-app-"),
- );
- await writeFile(
- join(directory, "report file.txt"),
- "completed-shell-output",
- );
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: directory,
- tuiMode,
- });
- try {
- app.start();
- await app.ready;
- app.editor.setText(
- process.platform === "win32" ? "!Get-Content " : "!cat ",
- );
- for (const char of "rep") terminal.input?.(char);
- expect(app.editor.getText()).toBe(
- process.platform === "win32" ? "!Get-Content rep" : "!cat rep",
- );
- terminal.input?.("\t");
- await vi.waitFor(() =>
- expect(app.editor.getText()).toBe(
- process.platform === "win32"
- ? "!Get-Content report` file.txt "
- : "!cat report\\ file.txt ",
- ),
- );
- expect(
- app.transcript
- .snapshot()
- .some((cell) => cell.id.startsWith("local:bash:")),
- ).toBe(false);
- terminal.input?.("\r");
- await vi.waitFor(
- () =>
- expect(
- app.transcript
- .snapshot()
- .some(
- (cell) =>
- cell.id.startsWith("local:bash:") &&
- cell.status === "succeeded" &&
- cell.content.includes("completed-shell-output"),
- ),
- ).toBe(true),
- { timeout: 5000 },
- );
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- } finally {
- await app.stop();
- await rm(directory, { recursive: true, force: true });
- }
- },
- );
- it("runs an editor ! command locally and carries its result into the next model message", async () => {
- const directory = await mkdtemp(join(tmpdir(), "tui-bash-app-"));
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: directory,
- });
- try {
- await app.ready;
- app.editor.setText(
- process.platform === "win32"
- ? "!Write-Output shell-result"
- : "!printf shell-result",
- );
- app.editor.submit();
- await vi.waitFor(
- () =>
- expect(
- app.transcript
- .snapshot()
- .some(
- (cell) =>
- cell.id.startsWith("local:bash:") &&
- cell.status === "succeeded",
- ),
- ).toBe(true),
- { timeout: 5000 },
- );
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- expect(
- app.transcript
- .snapshot()
- .find((cell) => cell.id.startsWith("local:bash:"))?.content,
- ).toContain("shell-result");
- expect(stripAnsi(app.tui.render(100).join("\n"))).toContain(
- "shell-result",
- );
- await app.submit("Explain the output");
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- content: expect.stringContaining("shell-result"),
- }),
- expect.anything(),
- );
- } finally {
- await app.stop();
- await rm(directory, { recursive: true, force: true });
- }
- });
- it("shows shell output before the command exits and drains it when the app stops", async () => {
- const directory = await mkdtemp(join(tmpdir(), "tui-bash-stream-"));
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: directory,
- });
- try {
- await app.ready;
- const running = app.submit(
- process.platform === "win32"
- ? "!Write-Output streamed-result; Start-Sleep -Seconds 30"
- : "!printf streamed-result; sleep 30",
- );
- await vi.waitFor(
- () =>
- expect(
- app.transcript
- .snapshot()
- .some(
- (cell) =>
- cell.status === "running" &&
- cell.content.includes("streamed-result"),
- ),
- ).toBe(true),
- { timeout: 5000 },
- );
- expect(stripAnsi(app.tui.render(100).join("\n"))).toContain(
- "streamed-result",
- );
- await app.stop();
- await running;
- expect(
- app.transcript
- .snapshot()
- .find((cell) => cell.id.startsWith("local:bash:"))?.status,
- ).toBe("cancelled");
- } finally {
- await app.stop();
- await rm(directory, { recursive: true, force: true });
- }
- });
- it("continues a restored paused Queue from its manager without sending a new message", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let paused = true;
- vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
- {
- itemId: "paused-follow-up",
- sessionId: "session-1",
- status: paused ? "paused" : "queued",
- content: "Existing queued work",
- },
- ]);
- vi.mocked(runtime.continueQueue).mockImplementation(async () => {
- paused = false;
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "test",
- workspaceDir: "/workspace",
- productFeatures: { queue: true },
- });
- app.start();
- try {
- await app.ready;
- await app.openSession("session-1");
- await app.submit("/queue");
- expect(app.tui.render(120).join("\n")).toContain("c continue queue");
- terminal.input?.("c");
- await vi.waitFor(() =>
- expect(runtime.continueQueue).toHaveBeenCalledWith("session-1"),
- );
- await vi.waitFor(() =>
- expect(app.tui.render(120).join("\n")).toContain("Queue continued."),
- );
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- expect(runtime.enqueueMessage).not.toHaveBeenCalled();
- expect(runtime.deleteQueuedMessage).not.toHaveBeenCalled();
- } finally {
- await app.stop();
- }
- });
- it.each(["keep", "clear", "cancel-enter", "cancel-escape"] as const)(
- "recovers a restored paused Queue when sending a message: %s",
- async (decision) => {
- const dataDir = await mkdtemp(join(tmpdir(), "tui-paused-queue-draft-"));
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let items: TuiQueuedMessage[] = [
- {
- itemId: "paused-follow-up",
- sessionId: "session-1",
- status: "paused",
- content: "Existing queued work",
- },
- ];
- let emitQueueChange:
- | ((event: TuiRuntimeEvent | undefined) => void)
- | undefined;
- vi.mocked(runtime.watchEvents).mockImplementation(
- async function* (signal) {
- const event = await new Promise<TuiRuntimeEvent | undefined>(
- (resolve) => {
- emitQueueChange = resolve;
- signal.addEventListener("abort", () => resolve(undefined), {
- once: true,
- });
- },
- );
- if (!event || signal.aborted) return;
- yield event;
- if (!signal.aborted) {
- await new Promise<void>((resolve) => {
- signal.addEventListener("abort", () => resolve(), { once: true });
- });
- }
- },
- );
- vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
- ...items,
- ]);
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* (request, _signal, options) {
- if (!options?.pausedQueueAction) {
- throw new TuiFailure("runtime", "Queue paused", {
- code: "local_session_queue_paused",
- });
- }
- items =
- options.pausedQueueAction === "clear"
- ? []
- : items.map((item) => ({ ...item, status: "queued" }));
- emitQueueChange?.({
- type: "session.queue.updated",
- sessionId: "session-1",
- source: "runtime-v2",
- timestampMs: Date.now(),
- });
- yield { type: "done", turnId: request.turnId };
- },
- );
- const appOptions = {
- runtime,
- terminal,
- version: "test",
- dataDir,
- workspaceDir: "/workspace",
- productFeatures: { queue: true },
- };
- let app = createTuiApp(appOptions);
- app.start();
- try {
- await app.ready;
- await app.openSession("session-1");
- await vi.waitFor(() => expect(emitQueueChange).toBeTypeOf("function"));
- await vi.waitFor(() =>
- expect(app.tui.render(120).join("\n")).toContain(
- "Existing queued work",
- ),
- );
- terminal.input?.("Resume safely");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.tui.render(120).join("\n")).toContain("Keep my draft"),
- );
- const cancelled = decision.startsWith("cancel");
- if (decision === "cancel-escape") terminal.input?.("\u001b");
- else {
- if (decision === "clear") terminal.input?.("\u001b[B");
- if (decision === "cancel-enter") {
- terminal.input?.("\u001b[B");
- terminal.input?.("\u001b[B");
- }
- terminal.input?.("\r");
- }
- await vi.waitFor(() =>
- expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
- );
- expect(runtime.enqueueMessage).not.toHaveBeenCalled();
- if (cancelled) {
- await vi.waitFor(() =>
- expect(app.editor.getText()).toBe("Resume safely"),
- );
- expect(runtime.sendMessage).toHaveBeenCalledOnce();
- expect(runtime.continueQueue).not.toHaveBeenCalled();
- expect(runtime.deleteQueuedMessage).not.toHaveBeenCalled();
- expect(
- app.transcript.snapshot().filter((cell) => cell.kind === "user"),
- ).toEqual([]);
- expect(
- app.transcript.snapshot().filter((cell) => cell.kind === "error"),
- ).toEqual([]);
- expect(app.tui.render(120).join("\n")).toContain("Queue paused");
- expect(app.tui.render(120).join("\n")).not.toContain("Keep my draft");
- await vi.waitFor(async () => {
- const recovered = await new TuiDraftRecovery({
- dataDir,
- workspaceDir: "/workspace",
- sessionKey: "session-1",
- }).load();
- expect(recovered?.editor.text).toBe("Resume safely");
- expect(recovered?.retrySubmissions ?? []).toEqual([]);
- });
- app.editor.setText("Edited draft");
- await app.stop();
- app = createTuiApp(appOptions);
- app.start();
- await app.ready;
- await app.openSession("session-1");
- await vi.waitFor(() =>
- expect(app.editor.getText()).toBe("Edited draft"),
- );
- expect(runtime.sendMessage).toHaveBeenCalledOnce();
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.tui.render(120).join("\n")).toContain("Keep my draft"),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.sendMessage).toHaveBeenCalledTimes(3),
- );
- await vi.waitFor(() =>
- expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
- );
- expect(
- vi.mocked(runtime.sendMessage).mock.calls[2]?.[0],
- ).toMatchObject({
- content: "Edited draft",
- });
- expect(vi.mocked(runtime.sendMessage).mock.calls[2]?.[2]).toEqual({
- pausedQueueAction: "keep",
- });
- await vi.waitFor(() =>
- expect(app.tui.render(120).join("\n")).not.toContain(
- "Queue paused",
- ),
- );
- expect(app.editor.getText()).toBe("");
- expect(app.tui.render(120).join("\n")).toContain(
- "Existing queued work",
- );
- } else {
- expect(runtime.sendMessage).toHaveBeenCalledTimes(2);
- expect(
- vi.mocked(runtime.sendMessage).mock.calls[1]?.[0],
- ).toMatchObject({
- content: "Resume safely",
- });
- expect(vi.mocked(runtime.sendMessage).mock.calls[1]?.[2]).toEqual({
- pausedQueueAction: decision,
- });
- await vi.waitFor(() =>
- expect(app.tui.render(120).join("\n")).not.toContain(
- "Queue paused",
- ),
- );
- const rendered = app.tui.render(120).join("\n");
- if (decision === "clear")
- expect(rendered).not.toContain("Existing queued work");
- else expect(rendered).toContain("Existing queued work");
- }
- } finally {
- await app.stop();
- await rm(dataDir, { recursive: true, force: true });
- }
- },
- );
- it.each([
- ["plan-entry", "keep"],
- ["plan-entry", "clear"],
- ["plan-entry", "cancel"],
- ["plan-entry", "busy"],
- ["plan-exit", "keep"],
- ["plan-exit", "clear"],
- ["plan-exit", "cancel"],
- ["plan-exit", "busy"],
- ] as const)(
- "recovers a paused Queue with %s and decision %s",
- async (clientIntent, decision) => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let interactionMode: "plan" | undefined =
- clientIntent === "plan-exit" ? "plan" : undefined;
- let rejectRecovery = decision === "busy";
- vi.mocked(runtime.getSession).mockImplementation(async () => ({
- sessionId: "session-1",
- interactionMode,
- }));
- vi.mocked(runtime.listQueuedMessages).mockResolvedValue([
- {
- itemId: "paused-work",
- sessionId: "session-1",
- status: "paused",
- content: "Existing work",
- },
- ]);
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* (request, _signal, options) {
- if (!options?.pausedQueueAction || rejectRecovery) {
- throw new TuiFailure("runtime", "Admission rejected", {
- code: options?.pausedQueueAction
- ? "local_session_busy"
- : "local_session_queue_paused",
- });
- }
- interactionMode =
- request.clientIntent === "plan-entry" ? "plan" : undefined;
- yield { type: "done", turnId: request.turnId };
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "test",
- workspaceDir: "/workspace",
- productFeatures: { queue: true },
- });
- app.start();
- try {
- await app.ready;
- await app.openSession("session-1");
- await app.submit(
- clientIntent === "plan-entry" ? "/plan on" : "/plan off",
- );
- terminal.input?.("Change mode and continue");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.tui.render(120).join("\n")).toContain("Keep my draft"),
- );
- if (decision === "clear" || decision === "cancel")
- terminal.input?.("\u001b[B");
- if (decision === "cancel") terminal.input?.("\u001b[B");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
- );
- expect(runtime.enqueueMessage).not.toHaveBeenCalled();
- if (decision === "cancel" || decision === "busy") {
- await vi.waitFor(() =>
- expect(app.editor.getText()).toBe("Change mode and continue"),
- );
- expect(interactionMode === "plan").toBe(clientIntent === "plan-exit");
- rejectRecovery = false;
- app.editor.setText("Edited mode instruction");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.tui.render(120).join("\n")).toContain("Keep my draft"),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
- );
- }
- expect(runtime.sendMessage).toHaveBeenLastCalledWith(
- expect.objectContaining({ clientIntent }),
- expect.any(AbortSignal),
- { pausedQueueAction: decision === "clear" ? "clear" : "keep" },
- );
- expect(interactionMode === "plan").toBe(clientIntent === "plan-entry");
- expect(app.editor.getText()).toBe("");
- } finally {
- await app.stop();
- }
- },
- );
- it("shows the MCode prompt in an empty Composer and hides it after input", async () => {
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- try {
- app.start();
- await app.ready;
- expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
- "Ask Mcode to do anything",
- );
- app.editor.handleInput("R");
- expect(stripAnsi(app.tui.render(80).join("\n"))).not.toContain(
- "Ask Mcode to do anything",
- );
- expect(app.editor.getText()).toBe("R");
- } finally {
- await app.stop();
- }
- });
- it("copies the last Assistant reply to the client clipboard over SSH", async () => {
- vi.stubEnv("SSH_CONNECTION", "10.0.0.1 50100 10.0.0.2 22");
- vi.stubEnv("SSH_TTY", "/dev/pts/1");
- Object.defineProperty(process.stdin, "isTTY", {
- configurable: true,
- value: true,
- });
- Object.defineProperty(process.stdout, "isTTY", {
- configurable: true,
- value: true,
- });
- const terminal = new FakeTerminal();
- let app: ReturnType<typeof createTuiApp> | undefined;
- try {
- app = createTuiApp({
- runtime: createRuntime(),
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Say hello");
- await app.submit("/copy");
- expect(terminal.writes).toContain(
- "\u001B]52;c;SGVsbG8gZnJvbSB0aGUgQWdlbnQ=\u0007",
- );
- } finally {
- await app?.stop();
- Reflect.deleteProperty(process.stdin, "isTTY");
- Reflect.deleteProperty(process.stdout, "isTTY");
- vi.unstubAllEnvs();
- }
- });
- it("runs /goal through Runtime ownership and renders the active Goal above the Composer", async () => {
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/goal Ship TUI Goal support");
- expect(runtime.createSession).toHaveBeenCalledOnce();
- expect(runtime.createGoal).toHaveBeenCalledWith({
- sessionId: "session-1",
- objective: "Ship TUI Goal support",
- });
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- expect(app.surfaceHost.render(100).join("\n")).toContain("Goal · Active");
- expect(app.surfaceHost.render(100).join("\n")).toContain(
- "Ship TUI Goal support",
- );
- await app.submit("/goal pause");
- expect(runtime.patchGoal).toHaveBeenCalledWith("session-1", {
- status: "paused",
- });
- expect(app.surfaceHost.render(100).join("\n")).toContain("Goal · Paused");
- await app.stop();
- });
- it("wires complete chat and autocomplete business events into the TUI surface", async () => {
- const events: McodeBusinessEvent[] = [];
- const businessTelemetry: McodeBusinessTelemetry = {
- track: (event, properties) =>
- events.push({ event, properties } as McodeBusinessEvent),
- flush: async () => undefined,
- };
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace/agent-archon",
- businessTelemetry,
- });
- await app.ready;
- await app.submit("First prompt");
- await app.submit("Second prompt");
- for (const character of "/he") app.editor.handleInput(character);
- await vi.waitFor(() =>
- expect(
- events.some((item) => item.event === "slash_command_menu_view"),
- ).toBe(true),
- );
- app.editor.handleInput("\r");
- expect(events.filter((item) => item.event === "chat_send")).toEqual([
- {
- event: "chat_send",
- properties: {
- chat_type: "chat",
- is_first_message: 1,
- is_attachment: "text",
- },
- },
- {
- event: "chat_send",
- properties: {
- chat_type: "chat",
- is_first_message: 0,
- is_attachment: "text",
- },
- },
- ]);
- expect(events).toContainEqual({
- event: "slash_command_click",
- properties: {
- chat_type: "chat",
- command_type: "other",
- },
- });
- await app.stop();
- });
- it("releases the terminal on suspend and reconciles Runtime state after resume", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const requestProcessSuspend = vi.fn();
- vi.mocked(runtime.watchEvents).mockImplementation(
- async function* watchEvents(signal) {
- await new Promise<void>((resolve) => {
- signal.addEventListener("abort", resolve, { once: true });
- });
- yield* [];
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- requestProcessSuspend,
- });
- app.start();
- await app.ready;
- await app.openSession("session-1");
- await vi.waitFor(() => expect(runtime.watchEvents).toHaveBeenCalledOnce());
- terminal.input?.("\x1a");
- expect(requestProcessSuspend).toHaveBeenCalledOnce();
- await app.suspend();
- expect(terminal.stopCount).toBe(1);
- expect(app.controller.snapshot().status).not.toBe("error");
- await app.resume();
- expect(terminal.startCount).toBe(2);
- await vi.waitFor(() =>
- expect(runtime.watchEvents).toHaveBeenCalledTimes(2),
- );
- expect(runtime.getActiveRun).toHaveBeenCalled();
- await app.stop();
- });
- it.each(["regular", "fullscreen"] as const)(
- "restores %s Composer input after Ctrl+G returns from the external editor",
- async (tuiMode) => {
- const terminal = new FakeTerminal();
- const stopTerminal = vi.spyOn(terminal, "stop");
- const startTerminal = vi.spyOn(terminal, "start");
- const editDraftInExternalEditor = vi.fn(
- async () => "edited in the external editor",
- );
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- tuiMode,
- externalEditorCommand: "code --wait",
- editDraftInExternalEditor,
- });
- app.start();
- await app.ready;
- const longPaste = Array.from(
- { length: 12 },
- (_, index) => `line ${String(index + 1)}`,
- ).join("\n");
- terminal.input?.(`\x1b[200~${longPaste}\x1b[201~`);
- expect(app.editor.getText()).toBe("[paste #1 +12 lines]");
- terminal.input?.("\x07");
- await vi.waitFor(() =>
- expect(editDraftInExternalEditor).toHaveBeenCalledOnce(),
- );
- expect(editDraftInExternalEditor).toHaveBeenCalledWith({
- command: "code --wait",
- draft: longPaste,
- cwd: "/workspace",
- });
- await vi.waitFor(() =>
- expect(app.editor.getText()).toBe("edited in the external editor"),
- );
- expect(stopTerminal).toHaveBeenCalledOnce();
- expect(startTerminal).toHaveBeenCalledTimes(2);
- terminal.input?.("!");
- expect(app.editor.getText()).toBe("edited in the external editor!");
- await app.stop();
- },
- );
- it("loads Runtime-owned Git context into the status rail without blocking startup", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.getWorkspaceGitMetadata).mockResolvedValue({
- isGitRepo: true,
- branch: "feat/status-context",
- detached: false,
- isWorktree: true,
- });
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/Users/dev/github/agent-archon",
- homeDir: "/Users/dev",
- });
- await app.ready;
- await vi.waitFor(() => {
- expect(runtime.getWorkspaceGitMetadata).toHaveBeenCalledWith(
- "/Users/dev/github/agent-archon",
- );
- const rendered = app.tui.render(120).join("\n");
- expect(rendered).toContain("~/github/agent-archon");
- expect(rendered).toContain("⎇ feat/status-context · worktree");
- });
- await app.stop();
- });
- it("keeps Pi clear-on-shrink disabled for the inline product by default", async () => {
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- expect(app.tui.getClearOnShrink()).toBe(false);
- await app.ready;
- await app.stop();
- });
- it("drains Pi terminal input before restoring the terminal on shutdown", async () => {
- const terminal = new FakeTerminal();
- const drainInput = vi.spyOn(terminal, "drainInput");
- const stopTerminal = vi.spyOn(terminal, "stop");
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.stop();
- expect(drainInput).toHaveBeenCalledWith(1000);
- expect(stopTerminal).toHaveBeenCalledOnce();
- expect(drainInput.mock.invocationCallOrder[0]).toBeLessThan(
- stopTerminal.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
- );
- });
- it("shows the Runtime initialization error text when the Session catalog is unavailable", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.listSessions).mockRejectedValue(
- new Error("Unable to connect to the Runtime on port 1234"),
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- expect(app.controller.snapshot()).toMatchObject({
- status: "error",
- error:
- "Couldn't load sessions: Unable to connect to the Runtime on port 1234. Retry.",
- sessions: [],
- });
- expect(app.tui.render(80).join("\n")).toContain(
- "Error · Couldn't load sessions:",
- );
- await app.stop();
- });
- it("shows an available update as a dedicated startup notice", async () => {
- const terminal = new FakeTerminal();
- const checkForUpdate = vi.fn(async () => ({ latestVersion: "1.2.4" }));
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal,
- version: "1.2.3",
- workspaceDir: "/workspace",
- checkForUpdate,
- });
- app.start();
- await app.ready;
- await vi.waitFor(() => {
- expect(terminal.writes.join("")).toContain(
- "A new version of MCode is available",
- );
- });
- const rendered = terminal.writes.join("");
- expect(checkForUpdate).toHaveBeenCalledTimes(1);
- expect(rendered).toContain("Run '/update' to install MCode 1.2.4");
- await app.submit("Start working");
- expect(app.getSurface()).toBe("conversation");
- expect(app.tui.render(80).join("\n")).not.toContain(
- "A new version of MCode is available",
- );
- await app.submit("/new");
- expect(app.getSurface()).toBe("welcome");
- expect(app.tui.render(80).join("\n")).toContain(
- "A new version of MCode is available",
- );
- await app.stop();
- });
- it("keeps the Welcome handoff out of the primary hint and submits it on Ctrl+U", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSkills).mockResolvedValue({
- skills: [
- {
- name: "resume-codex",
- displayName: "Resume Codex",
- description: "Continue a Codex session",
- enabled: true,
- sourceKind: "builtin",
- },
- ],
- hasMore: false,
- });
- const sessionId = "01a02373-25ae-76a1-880c-9253ba939cdc";
- const findRecentCodexSession = vi.fn(async () => ({
- sessionId,
- updatedAtMs: Date.now() - 60_000,
- source: "cli" as const,
- }));
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- findRecentCodexSession,
- });
- app.start();
- await app.ready;
- await vi.waitFor(() =>
- expect(findRecentCodexSession).toHaveBeenCalledOnce(),
- );
- const welcome = app.tui.render(100).join("\n");
- expect(welcome).toContain("Start");
- expect(welcome).not.toContain("Coming from Codex?");
- terminal.input?.("\x15");
- await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- id: "session-1",
- content: `/resume-codex ${sessionId}`,
- }),
- expect.any(AbortSignal),
- );
- expect(app.tui.render(100).join("\n")).not.toContain("Coming from Codex?");
- await app.stop();
- });
- it("invalidates an in-flight Codex handoff scan after the user starts typing", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSkills).mockResolvedValue({
- skills: [
- {
- name: "resume-codex",
- displayName: "Resume Codex",
- description: "Continue a Codex session",
- enabled: true,
- sourceKind: "builtin",
- },
- ],
- hasMore: false,
- });
- let resolveRecent:
- | ((session: {
- sessionId: string;
- updatedAtMs: number;
- source: "cli";
- }) => void)
- | undefined;
- const findRecentCodexSession = vi.fn(
- async () =>
- await new Promise<{
- sessionId: string;
- updatedAtMs: number;
- source: "cli";
- }>((resolve) => {
- resolveRecent = resolve;
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- findRecentCodexSession,
- });
- app.start();
- terminal.input?.("x");
- await vi.waitFor(() =>
- expect(findRecentCodexSession).toHaveBeenCalledOnce(),
- );
- resolveRecent?.({
- sessionId: "01a02373-25ae-76a1-880c-9253ba939cdc",
- updatedAtMs: Date.now(),
- source: "cli",
- });
- await Promise.resolve();
- await Promise.resolve();
- expect(app.editor.getText()).toBe("x");
- expect(app.tui.render(100).join("\n")).not.toContain("Coming from Codex?");
- await app.stop();
- });
- it("does not inspect Codex storage when the resume Skill is unavailable", async () => {
- const runtime = createRuntime();
- const findRecentCodexSession = vi.fn(async () => ({
- sessionId: "01a02373-25ae-76a1-880c-9253ba939cdc",
- updatedAtMs: Date.now(),
- source: "cli" as const,
- }));
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- findRecentCodexSession,
- });
- app.start();
- await app.ready;
- await vi.waitFor(() => expect(runtime.listSkills).toHaveBeenCalledOnce());
- await Promise.resolve();
- expect(findRecentCodexSession).not.toHaveBeenCalled();
- expect(app.tui.render(100).join("\n")).not.toContain("Coming from Codex?");
- await app.stop();
- });
- it.each(["unsupported result", "blank version", "rejected check"] as const)(
- "keeps a %s startup update result out of the notice and transcript",
- async (scenario) => {
- const terminal = new FakeTerminal();
- const checkForUpdate = vi.fn(async () => {
- if (scenario === "rejected check")
- throw new Error("registry unavailable");
- if (scenario === "unsupported result") return undefined;
- return { latestVersion: " " };
- });
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal,
- version: "1.2.3",
- workspaceDir: "/workspace",
- checkForUpdate,
- });
- app.start();
- await app.ready;
- await vi.waitFor(() => expect(checkForUpdate).toHaveBeenCalledOnce());
- await app.stop();
- expect(terminal.writes.join("")).not.toContain(
- "A new version of MCode is available",
- );
- expect(
- app.transcript.snapshot().filter((cell) => cell.kind === "error"),
- ).toEqual([]);
- },
- );
- it("routes /update through the in-process update confirmation flow", async () => {
- const plan = {
- kind: "available" as const,
- source: "managed-installer" as const,
- currentVersion: "1.2.3",
- latestVersion: "1.2.4",
- channel: "stable" as const,
- };
- const inspectUpdate = vi.fn(async () => plan);
- const applyUpdate = vi.fn(async () => ({
- applied: true,
- message:
- "MCode 1.2.4 is installed. Restart running MCode sessions to use it.",
- }));
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal: new FakeTerminal(),
- version: "1.2.3",
- workspaceDir: "/workspace",
- inspectUpdate,
- applyUpdate,
- });
- await app.ready;
- await app.submit("/update");
- expect(inspectUpdate).toHaveBeenCalledOnce();
- expect(app.interaction.current()?.render(80).join("\n")).toContain(
- "MCode update",
- );
- app.interaction.current()?.handleInput?.("\r");
- await vi.waitFor(() =>
- expect(applyUpdate).toHaveBeenCalledWith(
- plan,
- expect.objectContaining({
- onOutput: expect.any(Function),
- }),
- ),
- );
- await vi.waitFor(() =>
- expect(
- app.transcript
- .snapshot()
- .some((cell) => cell.content.includes("MCode update completed")),
- ).toBe(true),
- );
- await app.stop();
- });
- it("leaves the current TUI after /update stages an npm-prefix replacement", async () => {
- const plan = {
- kind: "package-manager" as const,
- source: "npm-prefix" as const,
- currentVersion: "1.2.3",
- latestVersion: "1.2.4",
- packageTag: "latest" as const,
- command: {
- executable: "npm",
- args: ["install"],
- display: "npm install",
- },
- };
- const requestRestart = vi.fn();
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal: new FakeTerminal(),
- version: "1.2.3",
- workspaceDir: "/workspace",
- inspectUpdate: async () => plan,
- applyUpdate: async () => ({
- applied: true,
- restartRequired: true,
- message: "MCode 1.2.4 is staged safely.",
- }),
- requestRestart,
- });
- app.start();
- await app.ready;
- await app.submit("/update");
- app.interaction.current()?.handleInput?.("\r");
- await vi.waitFor(() => expect(requestRestart).toHaveBeenCalledOnce());
- await app.stopped;
- });
- it("rechecks local and Runtime work before applying an update", async () => {
- const runtime = createRuntime();
- const applyUpdate = vi.fn(async () => ({
- applied: true,
- message: "updated",
- }));
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "1.2.3",
- workspaceDir: "/workspace",
- inspectUpdate: async () => ({
- kind: "available",
- source: "managed-installer",
- currentVersion: "1.2.3",
- latestVersion: "1.2.4",
- channel: "stable",
- }),
- applyUpdate,
- });
- await app.ready;
- await app.openSession("session-1");
- vi.mocked(runtime.getActiveRun).mockResolvedValue({
- schemaVersion: 1,
- sessionId: "session-1",
- state: "running",
- turnId: "turn-active",
- actions: { steer: true },
- });
- await app.submit("/update");
- app.interaction.current()?.handleInput?.("\r");
- await vi.waitFor(() =>
- expect(
- app.transcript
- .snapshot()
- .some((cell) =>
- cell.content.includes(
- "MCode update failed: Finish or stop the active response before updating.",
- ),
- ),
- ).toBe(true),
- );
- expect(applyUpdate).not.toHaveBeenCalled();
- await app.stop();
- });
- it("fails the update gate closed when Runtime state cannot be verified", async () => {
- const runtime = createRuntime();
- const applyUpdate = vi.fn(async () => ({
- applied: true,
- message: "updated",
- }));
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "1.2.3",
- workspaceDir: "/workspace",
- inspectUpdate: async () => ({
- kind: "available",
- source: "managed-installer",
- currentVersion: "1.2.3",
- latestVersion: "1.2.4",
- channel: "stable",
- }),
- applyUpdate,
- });
- await app.ready;
- await app.openSession("session-1");
- vi.mocked(runtime.getActiveRun).mockRejectedValue(
- new Error("Runtime unavailable"),
- );
- await app.submit("/update");
- app.interaction.current()?.handleInput?.("\r");
- await vi.waitFor(() =>
- expect(
- app.transcript
- .snapshot()
- .some((cell) =>
- cell.content.includes("Unable to verify that this Session is idle"),
- ),
- ).toBe(true),
- );
- expect(applyUpdate).not.toHaveBeenCalled();
- await app.stop();
- });
- it("does not expose the TUI before base hydration has settled", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let releaseSessions: (() => void) | undefined;
- vi.mocked(runtime.listSessions).mockImplementation(
- async () =>
- await new Promise((resolve) => {
- releaseSessions = () => resolve([]);
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- let settled = false;
- void app.ready.then(() => {
- settled = true;
- });
- await Promise.resolve();
- expect(settled).toBe(false);
- releaseSessions?.();
- await app.ready;
- app.start();
- const rendered = app.tui.render(80).join("\n");
- expect(rendered).not.toContain("Starting MiniMax Code");
- expect(rendered).not.toContain("Loading session");
- await app.stop();
- });
- it("renders server startup in the welcome composer header until hydration settles", async () => {
- const runtime = createRuntime();
- let releaseSessions: (() => void) | undefined;
- vi.mocked(runtime.listSessions).mockImplementation(
- async () =>
- await new Promise((resolve) => {
- releaseSessions = () => resolve([]);
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- try {
- app.setStartupStatus("⠋ Starting server...");
- app.start();
- const starting = app.tui.render(80).join("\n");
- expect(starting).toContain("⠋ Starting server...");
- expect(starting).not.toContain("Start · @ file · / autocomplete");
- expect(starting).not.toContain("Loading session");
- releaseSessions?.();
- await app.ready;
- app.setStartupStatus(undefined);
- expect(app.tui.render(80).join("\n")).toContain(
- "Start · @ file · / autocomplete",
- );
- } finally {
- releaseSessions?.();
- await app.stop();
- }
- });
- it("waits for account hydration before allowing the first message", async () => {
- const runtime = createRuntime();
- let resolveAccount!: (
- account: Awaited<ReturnType<typeof runtime.getAccountStatus>>,
- ) => void;
- vi.mocked(runtime.getAccountStatus).mockReturnValue(
- new Promise((resolve) => {
- resolveAccount = resolve;
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- try {
- const readiness = await Promise.race([
- app.ready.then(() => "ready" as const),
- new Promise<"blocked">((resolve) =>
- setTimeout(() => resolve("blocked"), 100),
- ),
- ]);
- expect(readiness).toBe("blocked");
- expect(runtime.createSession).not.toHaveBeenCalled();
- resolveAccount({
- status: "ready",
- defaultModel: "minimax/MiniMax-M2.7",
- managedTokenPresent: true,
- warnings: [],
- });
- await app.ready;
- const submission = app.submit("Send after account hydration");
- await submission;
- expect(runtime.createSession).toHaveBeenCalledWith({
- workspaceDir: "/workspace",
- });
- expect(app.transcript.snapshot()).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- kind: "user",
- content: "Send after account hydration",
- }),
- expect.objectContaining({
- kind: "assistant",
- content: "Hello from the Agent",
- }),
- ]),
- );
- } finally {
- resolveAccount({
- status: "ready",
- defaultModel: "minimax/MiniMax-M2.7",
- managedTokenPresent: true,
- warnings: [],
- });
- await app.ready;
- await app.stop();
- }
- });
- it("does not wait for Token Plan membership hydration before App readiness", async () => {
- const runtime = createRuntime();
- const baseAccount = {
- status: "ready" as const,
- defaultModel: "minimax/MiniMax-M2.7",
- providerId: "minimax",
- modelId: "MiniMax-M2.7",
- authMode: "managed-login",
- managedTokenPresent: true,
- modelSource: "token-plan" as const,
- warnings: [],
- };
- const hydratedAccount = {
- ...baseAccount,
- tokenPlanQuotaState: "available" as const,
- tokenPlanQuota: {
- fiveHour: { remainingPercent: 90, unlimited: false },
- weekly: { remainingPercent: 80, unlimited: false },
- },
- };
- let resolveMembership!: (account: typeof hydratedAccount) => void;
- vi.mocked(runtime.getAccountStatus).mockImplementation(
- async (_sessionId, options) => {
- if (options?.includeMembership === true) {
- return await new Promise((resolve) => {
- resolveMembership = resolve;
- });
- }
- return baseAccount;
- },
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- try {
- await app.ready;
- expect(runtime.getAccountStatus).toHaveBeenCalledWith(undefined, {
- includeMembership: false,
- });
- expect(runtime.getAccountStatus).toHaveBeenCalledWith(undefined, {
- includeMembership: true,
- });
- expect(app.controller.snapshot().account).toMatchObject(baseAccount);
- resolveMembership(hydratedAccount);
- await vi.waitFor(() =>
- expect(app.controller.snapshot().account).toMatchObject({
- tokenPlanQuotaState: "available",
- }),
- );
- } finally {
- resolveMembership(hydratedAccount);
- await app.stop();
- }
- });
- it("waits for permission mode hydration before reporting App readiness", async () => {
- const runtime = createRuntime();
- let resolvePermissionMode!: (mode: "auto") => void;
- vi.mocked(runtime.getPermissionMode).mockReturnValue(
- new Promise((resolve) => {
- resolvePermissionMode = resolve;
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- const readiness = Promise.race([
- app.ready.then(() => "ready" as const),
- new Promise<"blocked">((resolve) =>
- setTimeout(() => resolve("blocked"), 100),
- ),
- ]);
- await expect(readiness).resolves.toBe("blocked");
- resolvePermissionMode("auto");
- await app.ready;
- await app.stop();
- });
- it("accepts modeled account and optional permission degradation at the ready boundary", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.getAccountStatus).mockRejectedValue(
- new Error("account offline"),
- );
- vi.mocked(runtime.getPermissionMode).mockRejectedValue(
- new Error("config unavailable"),
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await expect(app.ready).resolves.toBeUndefined();
- expect(app.controller.snapshot().account).toEqual({
- status: "unknown",
- warnings: [],
- });
- await app.stop();
- });
- it("hydrates the selected model display name into the status rail on startup", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.getAccountStatus).mockResolvedValue({
- status: "ready",
- defaultModel: "custom_provider:innerTest/MiniMax-M3",
- providerId: "custom_provider:innerTest",
- modelId: "MiniMax-M3",
- authMode: "byok",
- managedTokenPresent: true,
- warnings: [],
- });
- vi.mocked(runtime.listModels).mockResolvedValue([
- {
- providerId: "custom_provider:innerTest",
- modelId: "MiniMax-M3",
- displayName: "m3.05",
- selected: true,
- },
- ]);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await vi.waitFor(() =>
- expect(app.tui.render(120).join("\n")).toContain("✦ m3.05"),
- );
- await app.stop();
- });
- it("restores a managed-login failure to the Composer", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.getAccountStatus).mockResolvedValue({
- status: "ready",
- defaultModel: "minimax/MiniMax-M2.7",
- authMode: "managed-login",
- modelSource: "token-plan",
- managedTokenPresent: false,
- warnings: [],
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await vi.waitFor(() =>
- expect(app.tui.render(80).join("\n")).toContain("Sign in with /login"),
- );
- terminal.input?.("Keep this until login");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.editor.getText()).toBe("Keep this until login"),
- );
- expect(app.tui.render(80).join("\n")).toContain("Keep this until login");
- expect(app.transcript.snapshot()).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- kind: "warning",
- content:
- "Sign in to MiniMax to use Agent features. Run /login, then retry.",
- }),
- ]),
- );
- expect(runtime.createSession).not.toHaveBeenCalled();
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- await app.stop();
- });
- it("renders an Enter submission before the asynchronous login preflight settles", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- let resolveAccount:
- | ((
- account: Awaited<ReturnType<typeof runtime.getAccountStatus>>,
- ) => void)
- | undefined;
- vi.mocked(runtime.getAccountStatus).mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- resolveAccount = resolve;
- }),
- );
- const writesBeforeSubmission = terminal.writes.length;
- terminal.input?.("Show this immediately");
- terminal.input?.("\r");
- expect(app.editor.getText()).toBe("");
- expect(
- app.transcript.snapshot().filter((cell) => cell.kind === "user"),
- ).toEqual([
- expect.objectContaining({
- status: "pending",
- content: "Show this immediately",
- }),
- ]);
- await vi.waitFor(() =>
- expect(terminal.writes.length).toBeGreaterThan(writesBeforeSubmission),
- );
- expect(runtime.createSession).not.toHaveBeenCalled();
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- await vi.waitFor(() => expect(resolveAccount).toBeTypeOf("function"));
- resolveAccount?.({
- status: "ready",
- defaultModel: "minimax/MiniMax-M2.7",
- providerId: "minimax",
- modelId: "MiniMax-M2.7",
- authMode: "managed-login",
- managedTokenPresent: true,
- warnings: [],
- });
- await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
- await app.stop();
- });
- it("keeps a login-blocked submission editable after current-region sign-in", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let authenticated = false;
- vi.mocked(runtime.getAccountStatus).mockImplementation(async () =>
- authenticated
- ? {
- status: "ready",
- defaultModel: "minimax/MiniMax-M2.7",
- providerId: "minimax",
- modelId: "MiniMax-M2.7",
- authMode: "managed-login",
- modelSource: "token-plan",
- managedTokenPresent: true,
- warnings: [],
- }
- : {
- status: "needs-login",
- authMode: "managed-login",
- modelSource: "token-plan",
- managedTokenPresent: false,
- warnings: [],
- },
- );
- const auth = {
- login: vi.fn(async () => {
- authenticated = true;
- return {
- state: "authenticated" as const,
- message: "Signed in with MiniMax.",
- };
- }),
- logout: vi.fn(async () => ({
- state: "signed-out" as const,
- message: "Signed out of MiniMax.",
- })),
- };
- const app = createTuiApp({
- runtime,
- auth,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- terminal.input?.("Send this after login");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.editor.getText()).toBe("Send this after login"),
- );
- await app.submit("/login");
- app.interaction.current()?.handleInput("\r");
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- app.editor.handleInput("\r");
- await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- id: "session-1",
- content: "Send this after login",
- turnId: expect.any(String),
- }),
- expect.any(AbortSignal),
- );
- expect(app.transcript.snapshot()).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- kind: "user",
- content: "Send this after login",
- }),
- ]),
- );
- await app.stop();
- });
- it("runs /checkin immediately for a signed-in MiniMax account", async () => {
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/checkin");
- expect(runtime.runDailyCheckin).toHaveBeenCalledOnce();
- expect(app.transcript.snapshot()).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- kind: "final-summary",
- content: expect.stringContaining(
- "Checked in: Cycle day 2, +20 Credits",
- ),
- }),
- ]),
- );
- await app.stop();
- });
- it("shows a generic /checkin failure without backend details", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.runDailyCheckin).mockRejectedValue(
- new Error("internal signin shard rejected request"),
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/checkin");
- const transcript = app.transcript
- .snapshot()
- .map((cell) => cell.content)
- .join("\n");
- expect(transcript).toContain("Couldn't complete daily check-in.");
- expect(transcript).not.toContain("internal signin shard");
- await app.stop();
- });
- it("does not open login when /checkin cannot verify account status", async () => {
- const runtime = createRuntime();
- const auth = {
- login: vi.fn(),
- logout: vi.fn(async () => ({
- state: "signed-out" as const,
- message: "Signed out of MiniMax.",
- })),
- };
- const app = createTuiApp({
- runtime,
- auth,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- vi.mocked(runtime.getAccountStatus).mockRejectedValue(
- new Error("status unavailable"),
- );
- await app.submit("/checkin");
- expect(app.interaction.current()).toBeUndefined();
- expect(auth.login).not.toHaveBeenCalled();
- expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
- await app.stop();
- });
- it("starts MiniMax login and resumes /checkin once after authentication", async () => {
- const runtime = createRuntime();
- let authenticated = false;
- vi.mocked(runtime.getAccountStatus).mockImplementation(async () => ({
- status: authenticated ? "ready" : "needs-login",
- authMode: "managed-login",
- modelSource: "byok",
- managedTokenPresent: authenticated,
- warnings: [],
- }));
- const auth = {
- login: vi.fn(async () => {
- authenticated = true;
- return {
- state: "authenticated" as const,
- message: "Signed in with MiniMax.",
- };
- }),
- logout: vi.fn(async () => ({
- state: "signed-out" as const,
- message: "Signed out of MiniMax.",
- })),
- };
- const app = createTuiApp({
- runtime,
- auth,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/checkin");
- expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
- app.interaction.current()?.handleInput("\r");
- await vi.waitFor(() =>
- expect(runtime.runDailyCheckin).toHaveBeenCalledOnce(),
- );
- expect(auth.login).toHaveBeenCalledWith(expect.any(Function), "cn");
- await app.stop();
- });
- it("does not resume /checkin when the login picker is cancelled", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.getAccountStatus).mockResolvedValue({
- status: "needs-login",
- authMode: "managed-login",
- modelSource: "byok",
- managedTokenPresent: false,
- warnings: [],
- });
- const auth = {
- login: vi.fn(),
- logout: vi.fn(async () => ({
- state: "signed-out" as const,
- message: "Signed out of MiniMax.",
- })),
- };
- const app = createTuiApp({
- runtime,
- auth,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/checkin");
- app.interaction.current()?.handleInput("\u001b");
- expect(auth.login).not.toHaveBeenCalled();
- expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
- await app.stop();
- });
- it("does not resume /checkin when browser login fails", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.getAccountStatus).mockResolvedValue({
- status: "needs-login",
- managedTokenPresent: false,
- warnings: [],
- });
- const auth = {
- login: vi.fn(async () => {
- throw new Error("browser login failed");
- }),
- logout: vi.fn(async () => ({
- state: "signed-out" as const,
- message: "Signed out of MiniMax.",
- })),
- };
- const app = createTuiApp({
- runtime,
- auth,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/checkin");
- app.interaction.current()?.handleInput("\r");
- await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
- expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
- await app.stop();
- });
- it("carries /checkin through a cross-region login restart", async () => {
- const runtime = createRuntime();
- const requestRestart = vi.fn();
- vi.mocked(runtime.getAccountStatus).mockResolvedValue({
- status: "needs-login",
- managedTokenPresent: false,
- warnings: [],
- });
- const auth = {
- login: vi.fn(async () => ({
- state: "authenticated" as const,
- restartRequired: true,
- message: "Signed in with MiniMax Global.",
- })),
- logout: vi.fn(async () => ({
- state: "signed-out" as const,
- message: "Signed out of MiniMax.",
- })),
- };
- const app = createTuiApp({
- runtime,
- auth,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- requestRestart,
- });
- app.start();
- await app.ready;
- await app.submit("/checkin");
- app.interaction.current()?.handleInput("\u001b[B");
- app.interaction.current()?.handleInput("\r");
- await vi.waitFor(() =>
- expect(requestRestart).toHaveBeenCalledWith("en", "/checkin"),
- );
- expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
- await app.stopped;
- });
- it("restarts after cross-region login while keeping the blocked submission", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const requestRestart = vi.fn();
- const notifyAuthContextChanged = vi.fn(async () => undefined);
- vi.mocked(runtime.getAccountStatus).mockResolvedValue({
- status: "needs-login",
- authMode: "managed-login",
- modelSource: "token-plan",
- managedTokenPresent: false,
- warnings: [],
- });
- const auth = {
- login: vi.fn(async () => ({
- state: "authenticated" as const,
- restartRequired: true,
- message: "Signed in with MiniMax Global.",
- })),
- logout: vi.fn(async () => ({
- state: "signed-out" as const,
- message: "Signed out of MiniMax.",
- })),
- };
- const app = createTuiApp({
- runtime,
- auth,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- requestRestart,
- notifyAuthContextChanged,
- });
- app.start();
- await app.ready;
- terminal.input?.("Keep this through restart");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.editor.getText()).toBe("Keep this through restart"),
- );
- await app.submit("/login");
- app.interaction.current()?.handleInput("\u001b[B");
- app.interaction.current()?.handleInput("\r");
- await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
- expect(auth.login).toHaveBeenCalledWith(expect.any(Function), "en");
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- await vi.waitFor(() => expect(requestRestart).toHaveBeenCalledOnce());
- expect(requestRestart).toHaveBeenCalledWith("en");
- expect(notifyAuthContextChanged).not.toHaveBeenCalled();
- await app.stopped;
- expect(app.editor.getText()).toBe("Keep this through restart");
- });
- it("offers MiniMax login without blocking an unauthenticated builtin BYOK Turn", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.getAccountStatus).mockResolvedValue({
- status: "ready",
- defaultModel: "minimax/MiniMax-M3",
- providerId: "minimax",
- authMode: "managed-login",
- modelSource: "byok",
- managedTokenPresent: false,
- warnings: [],
- });
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await vi.waitFor(() =>
- expect(app.tui.render(80).join("\n")).toContain("Sign in with /login"),
- );
- await app.submit("BYOK still runs");
- expect(runtime.createSession).toHaveBeenCalledWith({
- workspaceDir: "/workspace",
- });
- expect(app.transcript.snapshot()).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ kind: "user", content: "BYOK still runs" }),
- expect.objectContaining({
- kind: "assistant",
- content: "Hello from the Agent",
- }),
- ]),
- );
- await app.stop();
- });
- it("starts a terminal-native workbench and submits messages through the Agent runtime", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- homeDir: "/home/dev",
- });
- app.start();
- await app.ready;
- expect(app.getSurface()).toBe("welcome");
- await app.submit("Say hello");
- expect(app.getSurface()).toBe("conversation");
- const conversation = app.tui.render(80).join("\n");
- expect(conversation).toContain("Tips for getting started");
- expect(conversation).toContain("Say hello");
- expect(conversation).toContain("Hello from the Agent");
- expect(terminal.started).toBe(true);
- expect(terminal.title).toBe("Minimax Code");
- expect(runtime.createSession).toHaveBeenCalledWith({
- workspaceDir: "/workspace",
- });
- expect(app.transcript.snapshot()).toEqual([
- expect.objectContaining({ kind: "user", content: "Say hello" }),
- expect.objectContaining({
- kind: "assistant",
- status: "succeeded",
- content: "Hello from the Agent",
- }),
- expect.objectContaining({ kind: "turn-duration", status: "succeeded" }),
- ]);
- await app.stop();
- expect(terminal.stopped).toBe(true);
- });
- it("syncs the generated Session title to the terminal without duplicate writes", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let sessionTitle = "New session";
- let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
- vi.mocked(runtime.listSessions).mockImplementation(async () => [
- {
- sessionId: "session-1",
- title: sessionTitle,
- workspaceDir: "/workspace",
- },
- ]);
- vi.mocked(runtime.watchEvents).mockImplementation(
- async function* watchEvents(signal) {
- const event = await new Promise<TuiRuntimeEvent | undefined>(
- (resolve) => {
- emitEvent = resolve;
- signal.addEventListener("abort", () => resolve(undefined), {
- once: true,
- });
- },
- );
- if (event) yield event;
- await new Promise<void>((resolve) => {
- signal.addEventListener("abort", resolve, { once: true });
- });
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Review uncommitted work");
- await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
- sessionTitle = "Review uncommitted work";
- emitEvent?.(
- runtimeEvent({
- type: "session.title_updated",
- timestamp: Date.now(),
- source: "runtime",
- payload: {
- sessionId: "session-1",
- title: sessionTitle,
- },
- }),
- );
- await vi.waitFor(() => expect(terminal.title).toBe(sessionTitle));
- await app.submit("/status");
- expect(terminal.titleUpdates).toEqual(["Minimax Code", sessionTitle]);
- await app.stop();
- });
- it("keeps chat state alive while a regular feature overlay owns the viewport", async () => {
- const terminal = new FakeTerminal();
- terminal.rows = 6;
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- const featureInput = vi.fn();
- const featureContent = {
- render: () => ["feature-header", "feature-body"],
- invalidate: () => undefined,
- };
- const feature = {
- id: "sessions",
- layoutRoot: new VStack([{ component: featureContent }]),
- render: featureContent.render,
- invalidate: () => undefined,
- handleInput: featureInput,
- };
- app.start();
- await app.ready;
- const screen = new VirtualTerminalScreen(terminal.columns, terminal.rows);
- let writeIndex = 0;
- const flushWrites = (): void => {
- for (; writeIndex < terminal.writes.length; writeIndex += 1) {
- screen.feed(terminal.writes[writeIndex] ?? "");
- }
- };
- flushWrites();
- app.editor.setText("preserved draft");
- const handle = app.surfaceHost.pushFeature({ screen: feature });
- app.tui.renderNow();
- flushWrites();
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "sessions",
- });
- expect(app.surfaceHost.render(80).join("\n")).toContain("preserved draft");
- expect(screen.viewportText()).toContain("feature-header");
- expect(screen.viewportText()).toContain("feature-body");
- expect(app.tui.mode).toBe("regular");
- expect(terminal.startCount).toBe(1);
- expect(terminal.stopCount).toBe(0);
- terminal.input?.("j");
- expect(featureInput).toHaveBeenCalledWith("j");
- expect(handle.close()).toBe(true);
- app.tui.renderNow();
- flushWrites();
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "chat",
- id: "chat",
- });
- expect(app.editor.getText()).toBe("preserved draft");
- expect(app.surfaceHost.render(80).join("\n")).toContain("preserved draft");
- expect(screen.viewportText()).toContain("preserved draft");
- expect(screen.viewportText()).not.toContain("feature-header");
- await app.stop();
- screen.dispose();
- });
- it("switches /settings through explicit choices and closes after applying", async () => {
- const terminal = new FakeTerminal();
- const persistTuiMode = vi.fn();
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal,
- version: "0.2.0",
- workspaceDir: "/workspace",
- tuiMode: "regular",
- persistTuiMode,
- });
- app.start();
- await app.ready;
- expect(app.surfaceHost.getChatMode()).toBe("regular");
- expect(app.tui.mode).toBe("regular");
- await app.submit("/settings");
- const fullscreenSettings = app.interaction.current();
- expect(app.tui.getFocusedComponent()).toBe(fullscreenSettings);
- expect(app.surfaceHost.render(80).join("\n")).toContain(
- "TUI mode · Regular",
- );
- terminal.input?.("\u001b[B");
- terminal.input?.("\r");
- expect(app.surfaceHost.getChatMode()).toBe("fullscreen");
- expect(app.tui.mode).toBe("fullscreen");
- expect(app.interaction.isActive()).toBe(false);
- expect(app.tui.getFocusedComponent()).toBe(app.editor);
- expect(persistTuiMode).toHaveBeenLastCalledWith("fullscreen");
- expect(app.editor.focused).toBe(true);
- terminal.input?.("/");
- await vi.waitFor(() =>
- expect(app.editor.render(60).join("\n")).toContain(
- "Show available commands",
- ),
- );
- terminal.input?.("\u001b");
- app.editor.setText("");
- await app.submit("/settings");
- const regularSettings = app.interaction.current();
- expect(app.tui.getFocusedComponent()).toBe(regularSettings);
- expect(app.surfaceHost.render(80).join("\n")).toContain(
- "TUI mode · Fullscreen",
- );
- terminal.input?.("\u001b[A");
- terminal.input?.("\r");
- expect(app.surfaceHost.getChatMode()).toBe("regular");
- expect(app.tui.mode).toBe("regular");
- expect(app.interaction.isActive()).toBe(false);
- expect(app.tui.getFocusedComponent()).toBe(app.editor);
- expect(persistTuiMode).toHaveBeenLastCalledWith("regular");
- await app.stop();
- });
- it("keeps the Pi Editor and Slash Command autocomplete active in fullscreen chat", async () => {
- const terminal = new FakeTerminal();
- terminal.rows = 8;
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal,
- version: "0.2.0",
- workspaceDir: "/workspace",
- tuiMode: "fullscreen",
- });
- app.start();
- await app.ready;
- terminal.input?.("/");
- await vi.waitFor(() =>
- expect(app.editor.render(60).join("\n")).toContain(
- "Show available commands",
- ),
- );
- expect(app.editor.getText()).toBe("/");
- terminal.input?.("\u001B[B");
- expect(app.editor.getText()).toBe("/");
- terminal.input?.("\u001B");
- expect(app.editor.getText()).toBe("/");
- expect(app.editor.focused).toBe(true);
- await app.stop();
- });
- it("renders regular-mode Slash Command autocomplete on the first keypress and every update", async () => {
- const terminal = new FakeTerminal();
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal,
- version: "0.2.0",
- workspaceDir: "/workspace",
- tuiMode: "regular",
- });
- app.start();
- await app.ready;
- const screen = new VirtualTerminalScreen(terminal.columns, terminal.rows);
- let writeIndex = 0;
- const flushWrites = (): void => {
- for (; writeIndex < terminal.writes.length; writeIndex += 1) {
- screen.feed(terminal.writes[writeIndex] ?? "");
- }
- };
- flushWrites();
- terminal.input?.("/");
- await vi.waitFor(() => {
- flushWrites();
- expect(screen.viewportText()).toContain("Show available commands");
- });
- expect(screen.viewportText()).toContain("/");
- terminal.input?.("m");
- await vi.waitFor(() => {
- flushWrites();
- expect(screen.viewportText()).toContain("Choose a model");
- });
- expect(screen.viewportText()).toContain("/m");
- screen.dispose();
- await app.stop();
- });
- it("resumes fullscreen tail following when submitting from scrolled history", async () => {
- const terminal = new FakeTerminal();
- terminal.rows = 6;
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal,
- version: "0.2.0",
- workspaceDir: "/workspace",
- tuiMode: "fullscreen",
- });
- app.start();
- await app.ready;
- for (let index = 1; index <= 4; index += 1) {
- await app.submit(`Prompt ${String(index)}`);
- }
- app.tui.renderNow();
- terminal.input?.("\u001B[5~");
- expect((app.tui as TuiAltScreen).isFollowingOutput).toBe(false);
- await app.submit("Latest prompt");
- expect((app.tui as TuiAltScreen).isFollowingOutput).toBe(true);
- await app.stop();
- });
- it("stops the terminal without waiting for a stalled Desktop event stream", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.watchEvents).mockImplementation(
- async function* watchEvents() {
- await new Promise<void>(() => undefined);
- yield runtimeEvent({
- type: "unreachable",
- timestamp: 0,
- source: "test",
- payload: {},
- });
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- const stopping = app.stop();
- await vi.waitFor(() => expect(terminal.stopped).toBe(true));
- await stopping;
- });
- it("restores the terminal before a stalled remote turn abort finishes", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let finishRemoteAbort: ((value: boolean) => void) | undefined;
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage(_req: SendMessageReq, signal?: AbortSignal) {
- await new Promise<void>((resolve) => {
- signal?.addEventListener("abort", () => resolve(), { once: true });
- });
- yield { type: "done" };
- },
- );
- vi.mocked(runtime.abortSession).mockImplementation(
- async () =>
- await new Promise<boolean>((resolve) => {
- finishRemoteAbort = resolve;
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- const submitting = app.submit("Keep running");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().status).toBe("running"),
- );
- const stopping = app.stop();
- await vi.waitFor(() => expect(terminal.stopped).toBe(true));
- finishRemoteAbort?.(true);
- await Promise.all([submitting, stopping]);
- });
- it("stops the active turn before leaving the UI", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let finishTurn: (() => void) | undefined;
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage() {
- yield {
- type: "delta",
- turnId: "turn-detached",
- role: "assistant",
- content: "Still running",
- };
- await new Promise<void>((resolve) => {
- finishTurn = resolve;
- });
- yield { type: "done", turnId: "turn-detached" };
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- const submitting = app.submit("Keep running after the UI leaves");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().status).toBe("running"),
- );
- await app.leaveUi();
- expect(terminal.stopped).toBe(true);
- expect(runtime.abortSession).toHaveBeenCalledWith(
- expect.objectContaining({ id: "session-1" }),
- );
- finishTurn?.();
- await submitting;
- });
- it("resumes a launcher-selected Session and exposes its ID for the exit hint", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- expect(app.controller.snapshot().session?.sessionId).toBeUndefined();
- await app.openSession("session-existing");
- expect(runtime.getSession).toHaveBeenCalledWith("session-existing");
- expect(runtime.getMessages).toHaveBeenCalledWith("session-existing");
- expect(app.controller.snapshot().session?.sessionId).toBe(
- "session-existing",
- );
- await app.leaveUi();
- });
- it("reports a launcher continue hydration failure in the Transcript", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-existing",
- title: "Existing session",
- workspaceDir: "/workspace",
- },
- ]);
- vi.mocked(runtime.getSession).mockRejectedValue(
- new Error("Session hydration failed"),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- await expect(app.continueLatestSession()).rejects.toThrow(
- "Session hydration failed",
- );
- expect(app.transcript.snapshot().at(-1)).toMatchObject({
- kind: "error",
- content:
- "Couldn't continue the latest conversation: Session hydration failed. Retry after the connection recovers.",
- });
- await app.leaveUi();
- });
- it("can disable queue UI and preserve the next draft while a turn is running", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let finishTool: (() => void) | undefined;
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage() {
- yield {
- type: "delta",
- turnId: "turn-running-tool",
- toolCalls: [
- {
- id: "read-1",
- name: "read",
- status: "running",
- input: { path: "src/cart/price.ts" },
- },
- ],
- };
- await new Promise<void>((resolve) => {
- finishTool = resolve;
- });
- yield { type: "done", turnId: "turn-running-tool" };
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- productFeatures: { queue: false },
- });
- await app.ready;
- const submission = app.submit("Inspect the pricing logic");
- await vi.waitFor(() => {
- const rendered = app.tui.render(80).join("\n");
- expect(rendered).toContain("Reading (src/cart/price.ts)");
- expect(rendered).toContain("Running");
- expect(rendered).not.toContain("Running · 0s");
- expect(rendered).not.toContain("Running · Read");
- expect(rendered).not.toContain("MCode · Running");
- expect(rendered).toContain("Ctrl+O details");
- expect(rendered).toContain("Esc stop");
- expect(rendered).not.toContain("Enter run next");
- expect(rendered).not.toContain("Message · Enter send");
- expect(rendered).not.toContain("Follow-up");
- expect(rendered).not.toContain("waiting");
- });
- await app.submit("Review the tests next");
- expect(runtime.enqueueMessage).not.toHaveBeenCalled();
- expect(app.editor.getText()).toBe("Review the tests next");
- expect(app.tui.render(80).join("\n")).toContain("Esc to interrupt");
- finishTool?.();
- await submission;
- });
- it("refreshes the running queue hint from the same bindings as the hotkeys panel", async () => {
- const keybindings = createTuiHostKeybindings({
- platform: "linux",
- suspendSupported: true,
- });
- const runtime = createRuntime();
- let finishTurn: (() => void) | undefined;
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage() {
- yield {
- type: "delta",
- turnId: "turn-custom-queue",
- thinking: "Inspecting the repository",
- };
- await new Promise<void>((resolve) => {
- finishTurn = resolve;
- });
- yield { type: "done", turnId: "turn-custom-queue" };
- },
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- keybindings: keybindings.registry,
- });
- await app.ready;
- keybindings.manager.setUserBindings({ "run.queue-draft": "ctrl+enter" });
- const submission = app.submit("Inspect the repository");
- try {
- await vi.waitFor(() => {
- const rendered = stripAnsi(app.tui.render(100).join("\n"));
- expect(rendered).toContain("Running");
- expect(rendered).toContain("Ctrl+Enter queue");
- expect(rendered).not.toContain("Alt+Enter queue");
- expect(
- keybindings.registry
- .helpRows()
- .find((row) => row.ids.includes("run.queue-draft"))?.keys,
- ).toBe("Ctrl+Enter");
- });
- } finally {
- finishTurn?.();
- await submission;
- await app.stop();
- }
- });
- it("shows running Thinking in chat and opens the full Transcript with /transcript", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let finishThinking: (() => void) | undefined;
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage() {
- yield {
- type: "delta",
- turnId: "turn-running-thinking",
- thinking: "Inspecting the repository",
- };
- await new Promise<void>((resolve) => {
- finishThinking = resolve;
- });
- yield { type: "done", turnId: "turn-running-thinking" };
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- const submission = app.submit("Inspect the repository");
- const countThinkingBodyRows = (rendered: string): number =>
- rendered
- .split("\n")
- .filter(
- (line) =>
- line.includes("Inspecting the repository") &&
- !line.includes("MCode"),
- ).length;
- let expandedThinkingRows = 0;
- try {
- await vi.waitFor(() => {
- const thinking = app.transcript
- .snapshot()
- .find((cell) => cell.kind === "thinking");
- expect(thinking?.content).toBe("Inspecting the repository");
- expect(thinking?.expanded).toBeUndefined();
- const rendered = app.tui.render(80).join("\n");
- expect(rendered).toContain("Running");
- expect(rendered).not.toContain("Running · 0s");
- expect(rendered).toContain(`${formatTuiShortcut("alt+enter")} queue`);
- expect(rendered).toContain("Enter steer");
- expect(rendered).not.toContain(`${formatTuiShortcut("ctrl+x")} steer`);
- expect(rendered).toContain("Ctrl+O details");
- expect(rendered).toContain("Esc stop");
- expect(rendered).toContain("Thinking…");
- expect(rendered).not.toContain("MCode ·");
- expect(rendered).not.toContain("Thinking · Inspecting the repository");
- expandedThinkingRows = countThinkingBodyRows(rendered);
- expect(expandedThinkingRows).toBeGreaterThan(0);
- });
- await app.submit("/transcript");
- await vi.waitFor(() => {
- const rendered = renderTerminalViewport(app, terminal);
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "transcript",
- });
- expect(rendered).toContain("Transcript");
- expect(rendered).not.toContain("Inspecting the repository");
- expect(countThinkingBodyRows(rendered)).toBeLessThan(
- expandedThinkingRows,
- );
- });
- terminal.input?.("\x14");
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "transcript",
- });
- finishThinking?.();
- finishThinking = undefined;
- await submission;
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "transcript",
- });
- expect(app.controller.snapshot().activeTurnId).toBeUndefined();
- expect(
- app.transcript.snapshot().find((cell) => cell.kind === "thinking"),
- ).toMatchObject({
- status: "succeeded",
- });
- terminal.input?.("\u001B");
- await vi.waitFor(() => {
- const rendered = app.tui.render(80).join("\n");
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "chat",
- id: "chat",
- });
- expect(rendered).toContain("Message · Enter send");
- expect(rendered).not.toContain("Running");
- });
- } finally {
- finishThinking?.();
- await submission;
- await app.stop();
- }
- });
- it("toggles hidden and full inline Tool output with Ctrl+O", async () => {
- const terminal = new FakeTerminal();
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- app.transcript.upsert({
- id: "tool-detail-toggle",
- kind: "tool",
- status: "succeeded",
- title: "bash",
- content: '{"command":"pnpm test"}',
- detail: [
- "result line 1",
- "result line 2",
- "result line 3",
- "result line 4",
- ].join("\n"),
- createdAtMs: 1,
- });
- expect(app.tui.render(80).join("\n")).not.toContain("result line 1");
- expect(app.tui.render(80).join("\n")).not.toContain("result line 4");
- terminal.input?.("\x0f");
- const detailed = app.tui.render(80).join("\n");
- expect(detailed).toContain("result line 1");
- expect(detailed).toContain("result line 3");
- expect(detailed).toContain("result line 4");
- expect(detailed).not.toContain("Details expanded");
- terminal.input?.("\x0f");
- const compact = app.tui.render(80).join("\n");
- expect(compact).not.toContain("result line 1");
- expect(compact).not.toContain("result line 3");
- expect(compact).not.toContain("result line 4");
- expect(compact).not.toContain("Details collapsed");
- await app.stop();
- });
- it("uses Ctrl+T for tasks while Ctrl+O remains scoped to transcript details", async () => {
- const terminal = new FakeTerminal();
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- app.controller.applyRuntimeTurnEvent("turn-todo", {
- type: "generic",
- eventType: "todo_updated",
- turnId: "turn-todo",
- data: {
- todos: [
- { content: "Inspect Desktop behavior", status: "completed" },
- { content: "Polish the task rail", status: "in_progress" },
- { content: "Run focused tests", status: "pending" },
- { content: "Review narrow layouts", status: "pending" },
- { content: "Update user documentation", status: "pending" },
- { content: "Publish the test package", status: "pending" },
- ],
- },
- });
- const compact = app.tui.render(80).join("\n");
- expect(compact).toContain("✓ Inspect Desktop behavior");
- expect(compact).toContain("● Polish the task rail");
- expect(compact).toContain("Ctrl+T expand");
- expect(compact).not.toContain("Publish the test package");
- expect(compact).not.toContain("todo_updated");
- terminal.input?.("\x0f");
- const transcriptDetailed = app.tui.render(80).join("\n");
- expect(transcriptDetailed).toContain("Ctrl+T expand");
- expect(transcriptDetailed).not.toContain("Publish the test package");
- terminal.input?.("\x14");
- const tasksExpanded = app.tui.render(80).join("\n");
- expect(tasksExpanded).toContain(
- "Todo list 1/6 · 5 remaining · Ctrl+T compact",
- );
- expect(tasksExpanded).toContain("Publish the test package");
- terminal.input?.("\x0f");
- expect(app.tui.render(80).join("\n")).toContain("Publish the test package");
- app.controller.applyRuntimeTurnEvent("turn-todo", {
- type: "generic",
- eventType: "todo_updated",
- turnId: "turn-todo",
- data: {
- todos: [
- { content: "Inspect Desktop behavior", status: "completed" },
- { content: "Polish the task rail", status: "completed" },
- { content: "Run focused tests", status: "completed" },
- { content: "Review narrow layouts", status: "completed" },
- { content: "Update user documentation", status: "completed" },
- { content: "Publish the test package", status: "completed" },
- ],
- },
- });
- expect(app.tui.render(80).join("\n")).toContain(
- "✓ Todo list 6/6 completed",
- );
- await app.stop();
- });
- it("keeps settled Thinking hidden until Ctrl+O requests transcript details", async () => {
- const terminal = new FakeTerminal();
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- app.transcript.upsert({
- id: "thinking-detail-toggle",
- kind: "thinking",
- status: "succeeded",
- content: "Private settled reasoning",
- durationMs: 3_200,
- createdAtMs: 1,
- updatedAtMs: 3_201,
- });
- const compact = app.tui.render(80).join("\n");
- expect(compact).toContain("Thought for 3.2s");
- expect(compact).not.toContain("Private settled reasoning");
- terminal.input?.("\x0f");
- expect(app.tui.render(80).join("\n")).toContain(
- "Private settled reasoning",
- );
- terminal.input?.("\x0f");
- expect(app.tui.render(80).join("\n")).not.toContain(
- "Private settled reasoning",
- );
- await app.stop();
- });
- it("returns from the conversation surface to Welcome after /new", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- await app.submit("Start a conversation");
- expect(app.getSurface()).toBe("conversation");
- await app.submit("/new");
- expect(app.getSurface()).toBe("welcome");
- expect(app.transcript.snapshot()).toEqual([]);
- });
- it("clears into a fresh conversation while keeping the previous session resumable", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- await app.submit("Keep this conversation");
- expect(app.controller.snapshot().session?.sessionId).toBe("session-1");
- await app.submit("/clear");
- expect(app.getSurface()).toBe("welcome");
- expect(app.transcript.snapshot()).toEqual([]);
- expect(app.controller.snapshot()).toMatchObject({
- status: "idle",
- session: undefined,
- sessions: [expect.objectContaining({ sessionId: "session-1" })],
- });
- expect(runtime.archiveSession).not.toHaveBeenCalled();
- });
- it("opens read-only Help above the Composer without using a TUI overlay", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- const showOverlay = vi.spyOn(app.tui, "showOverlay");
- app.start();
- await app.ready;
- const modelRequestsBeforeHelp = vi.mocked(runtime.listModels).mock.calls
- .length;
- const activeRunRequestsBeforeHelp = vi.mocked(runtime.getActiveRun).mock
- .calls.length;
- await app.submit("/help");
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- expect(app.transcript.snapshot()).toEqual([]);
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.interaction.isActive()).toBe(true);
- expect(terminal.mouseTracking).toBe(false);
- terminal.input?.("m");
- terminal.input?.("\r");
- expect(app.tui.hasOverlay()).toBe(false);
- await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
- expect(app.editor.getText()).toBe("");
- expect(runtime.listModels).toHaveBeenCalledTimes(modelRequestsBeforeHelp);
- expect(runtime.getActiveRun).toHaveBeenCalledTimes(
- activeRunRequestsBeforeHelp,
- );
- expect(showOverlay).not.toHaveBeenCalled();
- await app.stop();
- });
- it("lets Help use the available terminal height instead of capping it at twelve rows", async () => {
- const terminal = new FakeTerminal();
- terminal.rows = 30;
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.submit("/help");
- expect(app.interaction.current()?.render?.(terminal.columns)).toHaveLength(
- 24,
- );
- terminal.rows = 18;
- expect(app.interaction.current()?.render?.(terminal.columns)).toHaveLength(
- 12,
- );
- await app.stop();
- });
- it("keeps steer executable and exposes it in slash-command discovery", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
- schemaVersion: 1,
- sessionId,
- state: "running",
- turnId: "turn-active",
- actions: { steer: true },
- }));
- vi.mocked(runtime.steer).mockResolvedValue({
- turnId: "turn-active",
- mode: "steered",
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.submit("Create session");
- await app.submit("/help");
- const helpPanel = app.interaction.current();
- expect(helpPanel).toBeDefined();
- expect(app.tui.hasOverlay()).toBe(false);
- const helpPages: string[] = [];
- for (let page = 0; page < 20; page += 1) {
- const current = helpPanel?.render?.(100).join("\n") ?? "";
- if (current === helpPages.at(-1)) break;
- helpPages.push(current);
- helpPanel?.handleInput?.("\x1b[6~");
- }
- const help = helpPages.join("\n");
- expect(help).toContain("/steer <message>");
- expect(help).not.toContain("/send-now");
- expect(help).not.toContain("/retry");
- helpPanel?.handleInput?.("\x1b");
- await app.submit("/steer focus on the failing test");
- expect(runtime.steer).toHaveBeenCalledWith(
- expect.objectContaining({
- sessionId: "session-1",
- source: "api",
- message: { content: "focus on the failing test" },
- producerId: "mcode",
- idempotencyKey: expect.stringMatching(/^run_action_/u),
- }),
- );
- await app.stop();
- });
- it("refreshes Runtime steer capability before Enter submits the active Draft", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let finishTurn: (() => void) | undefined;
- let consumeSteer: (() => void) | undefined;
- const steerConsumptionReady = new Promise<void>((resolve) => {
- consumeSteer = resolve;
- });
- let steerAvailable = false;
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage() {
- yield {
- type: "delta",
- turnId: "turn-active",
- content: "Working on it",
- };
- await steerConsumptionReady;
- yield {
- type: "message",
- message: {
- id: "message-steer",
- turnId: "turn-active",
- role: "user",
- content: "focus on the failing test",
- },
- };
- await new Promise<void>((resolve) => {
- finishTurn = resolve;
- });
- yield { type: "done", turnId: "turn-active" };
- },
- );
- vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) =>
- steerAvailable
- ? {
- schemaVersion: 1,
- sessionId,
- state: "running",
- turnId: "turn-active",
- actions: { steer: true },
- }
- : {
- schemaVersion: 1,
- sessionId,
- state: "idle",
- actions: { steer: false },
- },
- );
- vi.mocked(runtime.steer).mockResolvedValue({
- turnId: "turn-active",
- mode: "steered",
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- const submission = app.submit("Inspect the failure");
- try {
- await vi.waitFor(() =>
- expect(app.tui.render(80).join("\n")).toContain("Running"),
- );
- steerAvailable = true;
- terminal.input?.("focus on the failing test");
- terminal.input?.("\r");
- expect(app.editor.getText()).toBe("");
- await vi.waitFor(() =>
- expect(runtime.steer).toHaveBeenCalledWith(
- expect.objectContaining({
- sessionId: "session-1",
- source: "api",
- message: { content: "focus on the failing test" },
- producerId: "mcode",
- idempotencyKey: expect.stringMatching(/^run_action_/u),
- requestedTurnId: "turn-active",
- }),
- ),
- );
- expect(app.transcript.snapshot().at(-1)).toMatchObject({
- kind: "user",
- status: "pending",
- content: "focus on the failing test",
- userPresentation: "pending-steer",
- });
- expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
- "↳ Next · focus on the failing test",
- );
- consumeSteer?.();
- await vi.waitFor(() =>
- expect(
- app.transcript.snapshot().filter((cell) => cell.kind === "user"),
- ).toEqual([
- expect.objectContaining({ content: "Inspect the failure" }),
- expect.objectContaining({
- status: "succeeded",
- content: "focus on the failing test",
- sourceMessageId: "message-steer",
- userPresentation: undefined,
- }),
- ]),
- );
- const rendered = app.tui.render(80).join("\n");
- expect(rendered).toContain("Inspect the failure");
- expect(rendered).toContain("focus on the failing test");
- expect(stripAnsi(rendered)).not.toContain("↳ Next ·");
- expect(app.editor.getText()).toBe("");
- } finally {
- consumeSteer?.();
- await vi.waitFor(() => expect(finishTurn).toEqual(expect.any(Function)));
- finishTurn?.();
- await submission;
- await app.stop();
- }
- });
- it("queues with Alt+Enter, restores with Option+Up, then steers with Enter", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const queuedItems: TuiQueuedMessage[] = [];
- let finishTurn: (() => void) | undefined;
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage() {
- yield {
- type: "delta",
- turnId: "turn-active",
- content: "Working on it",
- };
- await new Promise<void>((resolve) => {
- finishTurn = resolve;
- });
- yield { type: "done", turnId: "turn-active" };
- },
- );
- vi.mocked(runtime.enqueueMessage).mockImplementation(
- async (sessionId, content) => {
- const item: TuiQueuedMessage = {
- itemId: "queue-guidance",
- sessionId,
- status: "queued",
- source: "api",
- content,
- };
- queuedItems.push(item);
- return {
- itemId: item.itemId,
- status: item.status,
- position: queuedItems.length,
- };
- },
- );
- vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
- ...queuedItems,
- ]);
- vi.mocked(runtime.deleteQueuedMessage).mockImplementation(
- async (_sessionId, itemId) => {
- const index = queuedItems.findIndex((item) => item.itemId === itemId);
- return index >= 0 ? queuedItems.splice(index, 1)[0] : undefined;
- },
- );
- vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
- schemaVersion: 1,
- sessionId,
- state: "running",
- turnId: "turn-active",
- actions: { steer: true },
- }));
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- const submission = app.submit("Inspect the failure");
- try {
- await vi.waitFor(() =>
- expect(app.tui.render(80).join("\n")).toContain("Running"),
- );
- terminal.input?.("Use the preview branch directly");
- terminal.input?.("\x1b\r");
- await vi.waitFor(() =>
- expect(app.tui.render(80).join("\n")).toContain(
- "Use the preview branch directly",
- ),
- );
- await vi.waitFor(() =>
- expect(runtime.listQueuedMessages).toHaveBeenCalledWith("session-1"),
- );
- expect(app.editor.getText()).toBe("");
- terminal.input?.("\x1b[1;3A");
- await vi.waitFor(() =>
- expect(app.editor.getText()).toBe("Use the preview branch directly"),
- );
- expect(runtime.deleteQueuedMessage).toHaveBeenCalledWith(
- "session-1",
- "queue-guidance",
- );
- expect(runtime.steerQueuedMessage).not.toHaveBeenCalled();
- await vi.waitFor(() =>
- expect(app.tui.render(80).join("\n")).not.toContain("Queued ·"),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.steer).toHaveBeenCalledWith(
- expect.objectContaining({
- sessionId: "session-1",
- message: { content: "Use the preview branch directly" },
- requestedTurnId: "turn-active",
- }),
- ),
- );
- expect(app.editor.getText()).toBe("");
- } finally {
- finishTurn?.();
- await submission;
- await app.stop();
- }
- });
- it("renders /context from the Runtime-owned persisted context usage", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.getContextSnapshot).mockResolvedValue({
- status: "live",
- model: { provider: "minimax", id: "MiniMax-M3", contextWindow: 10_000 },
- contextUsage: {
- contextWindowTokens: 10_000,
- usedTokens: 3_000,
- totalCountSource: "PROVIDER_USAGE_ANCHORED",
- components: [
- { kind: "SYSTEM_PROMPT", tokens: 1_000 },
- { kind: "MEMORY", tokens: 0 },
- { kind: "TOOLS", tokens: 0 },
- { kind: "SKILLS", tokens: 0 },
- { kind: "MESSAGES", tokens: 2_000 },
- { kind: "OTHER", tokens: 0 },
- ],
- },
- });
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.submit("Create session");
- const transcriptBeforeContext = app.transcript.snapshot();
- await app.submit("/context");
- expect(app.transcript.snapshot()).toEqual(transcriptBeforeContext);
- expect(app.interaction.current()).toBeDefined();
- const rendered = app.tui.render(80).join("\n");
- expect(rendered).toContain("Context");
- expect(rendered).toContain("3k/10k tokens (30% used)");
- expect(rendered).toContain("Usage by category");
- expect(rendered).toContain("Messages");
- expect(rendered).toMatch(/[⛁⛀⛶]/u);
- app.interaction.current()?.handleInput?.("\x1b");
- expect(app.interaction.current()).toBeUndefined();
- expect(app.transcript.snapshot()).toEqual(transcriptBeforeContext);
- });
- it("routes /init through the Runtime-owned init Skill and the normal Agent turn", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSkills).mockResolvedValue({
- skills: [
- {
- name: "init",
- displayName: "Init",
- description: "Analyze the codebase and generate AGENTS.md",
- enabled: true,
- sourceKind: "builtin",
- },
- ],
- hasMore: false,
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await vi.waitFor(() => expect(runtime.listSkills).toHaveBeenCalled());
- await app.submit("/init");
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({ id: "session-1", content: "/init" }),
- expect.any(AbortSignal),
- );
- });
- it("forwards literal slash-prefixed prompts without invoking local commands", async () => {
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- const prompts = [
- "/commands",
- "/diff",
- "/tool",
- "/tools",
- "/resumex",
- "/renamex Renamed by a typo",
- "/clearx",
- "/tmp/sample-photo.JPG 用 read 工具直接读这个图片,告诉我是什么",
- "/not-a-command explain what this text means",
- "/context 这样还是会显示上下文信息",
- ];
- try {
- app.start();
- await app.ready;
- for (const prompt of prompts) {
- await app.submit(prompt);
- expect(runtime.sendMessage).toHaveBeenLastCalledWith(
- expect.objectContaining({ id: "session-1", content: prompt }),
- expect.any(AbortSignal),
- );
- expect(app.interaction.current()).toBeUndefined();
- expect(app.tui.hasOverlay()).toBe(false);
- }
- expect(runtime.sendMessage).toHaveBeenCalledTimes(prompts.length);
- expect(runtime.renameSession).not.toHaveBeenCalled();
- // Context metrics refresh independently; the overlay assertions above verify no local command ran.
- expect(app.transcript.snapshot()).not.toContainEqual(
- expect.objectContaining({ content: "Unknown command. Use /help." }),
- );
- } finally {
- await app.stop();
- }
- });
- it("keeps contextual commands local and submits other legacy names as prompts", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.submit("/queue");
- expect(runtime.listQueuedMessages).not.toHaveBeenCalled();
- expect(app.transcript.snapshot()).toEqual([]);
- expect(app.tui.render(80).join("\n")).toContain(
- "No messages are waiting and no response is currently running.",
- );
- await app.submit("/queue-clear");
- expect(runtime.deleteQueuedMessage).not.toHaveBeenCalled();
- await app.submit("/send-now do this first");
- await app.submit("/retry");
- expect(
- vi
- .mocked(runtime.sendMessage)
- .mock.calls.map(([request]) => request.content),
- ).toEqual(["/queue-clear", "/send-now do this first"]);
- expect(app.tui.render(80).join("\n")).toContain(
- "There is no failed response to retry in this Session.",
- );
- });
- it("resends the failed user submission through /retry instead of sending the command as text", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let attempt = 0;
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage() {
- attempt += 1;
- if (attempt === 1) {
- yield { type: "error", message: "terminated" };
- return;
- }
- yield { type: "delta", content: "Recovered response" };
- yield { type: "done" };
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.submit("Explain this failure");
- expect(app.tui.render(100).join("\n")).toContain(
- "The model connection ended before the response was completed.",
- );
- expect(app.tui.render(100).join("\n")).toContain(
- "Run /retry to resend your last message.",
- );
- await app.submit("/retry");
- expect(
- vi
- .mocked(runtime.sendMessage)
- .mock.calls.map(([request]) => request.content),
- ).toEqual(["Explain this failure", "Explain this failure"]);
- expect(
- vi
- .mocked(runtime.sendMessage)
- .mock.calls.some(([request]) => request.content === "/retry"),
- ).toBe(false);
- expect(app.transcript.snapshot()).toContainEqual(
- expect.objectContaining({
- kind: "assistant",
- content: "Recovered response",
- }),
- );
- await app.stop();
- });
- it("uses Runtime retry-continuation when a terminal failure has no local submission snapshot", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const restoredSession = {
- sessionId: "session-1",
- title: "Restored session",
- workspaceDir: "/workspace",
- status: "error",
- errorMessage: "terminated",
- };
- vi.mocked(runtime.listSessions).mockResolvedValue([restoredSession]);
- vi.mocked(runtime.getSession).mockResolvedValue(restoredSession);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/resume session-1");
- expect(app.tui.render(100).join("\n")).toContain(
- "The model connection ended before the response was completed.",
- );
- await app.submit("/retry");
- expect(runtime.sendMessage).toHaveBeenLastCalledWith(
- expect.objectContaining({
- id: "session-1",
- content: "",
- clientIntent: "retry-continuation",
- }),
- expect.any(AbortSignal),
- );
- await app.stop();
- });
- it("reports service authentication failures without assuming the user needs to sign in", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage() {
- yield { type: "error", message: "authentication failed" };
- },
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.submit("Use the protected model");
- expect(app.tui.render(100).join("\n")).toContain(
- "The service rejected request authentication.",
- );
- expect(app.tui.render(100).join("\n")).not.toContain("Run /login");
- expect(app.tui.render(100).join("\n")).not.toContain("Run /retry");
- await app.submit("/retry");
- expect(runtime.sendMessage).toHaveBeenCalledOnce();
- await app.stop();
- });
- it("cycles the shared permission mode with Alt+M without repeating the shortcut", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- expect(app.tui.render(80).join("\n")).toContain("Auto");
- expect(app.tui.render(80).join("\n")).not.toContain("Shift+Tab");
- expect(app.tui.render(80).join("\n")).not.toContain(
- "Shift+Tab switch mode",
- );
- terminal.input?.("\x1bm");
- await vi.waitFor(() => {
- expect(runtime.setPermissionMode).toHaveBeenCalledWith(
- "bypassPermissions",
- );
- const rendered = app.tui.render(80).join("\n");
- expect(rendered).toContain("Full access");
- expect(rendered).not.toContain("Shift+Tab");
- expect(rendered.match(/Full access/g)).toHaveLength(1);
- expect(rendered).not.toContain("Desktop permissions:");
- });
- await app.stop();
- });
- it("projects Token Plan warnings into the status rail", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.getAccountStatus).mockResolvedValue({
- status: "ready",
- defaultModel: "minimax/MiniMax-M2.7",
- providerId: "minimax",
- modelId: "MiniMax-M2.7",
- authMode: "managed-login",
- managedTokenPresent: true,
- modelSource: "token-plan",
- tokenPlanQuotaState: "available",
- tokenPlanQuota: {
- fiveHour: { remainingPercent: 30, unlimited: false },
- weekly: { remainingPercent: 64, unlimited: false },
- },
- warnings: [],
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Measure this turn");
- await vi.waitFor(() => {
- const rendered = app.tui.render(120).join("\n");
- expect(rendered).toContain("5h 30%");
- expect(rendered).not.toContain("Week 64%");
- });
- await app.stop();
- });
- it("keeps Token Plan subscription state out of the status rail when no quota exists", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.getAccountStatus).mockResolvedValue({
- status: "ready",
- defaultModel: "minimax/MiniMax-M3",
- providerId: "minimax",
- modelId: "MiniMax-M3",
- authMode: "managed-login",
- managedTokenPresent: true,
- modelSource: "token-plan",
- tokenPlanQuotaState: "not-subscribed",
- warnings: [],
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Measure this turn");
- await vi.waitFor(() => {
- const rendered = app.tui.render(120).join("\n");
- expect(rendered).toContain("✦ MiniMax M2.7");
- expect(rendered).not.toMatch(/Context 5%|Quota|Plan|5h|Week/u);
- });
- await app.stop();
- });
- it("keeps the current permission mode when an Alt+M update fails", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.setPermissionMode).mockRejectedValueOnce(
- new Error("config is read-only"),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- terminal.input?.("\x1bm");
- await vi.waitFor(() => {
- expect(app.tui.render(80).join("\n")).toContain("Auto");
- expect(app.tui.render(80).join("\n")).not.toContain("FULL");
- expect(app.transcript.snapshot().at(-1)).toMatchObject({
- kind: "warning",
- content:
- "Permission mode was not changed: config is read-only. Retry /permission or Alt+M.",
- });
- });
- await app.stop();
- });
- it("arms Plan with Shift+Tab and sends the one-shot Runtime intent", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- terminal.input?.("\x1b[Z");
- expect(app.tui.render(100).join("\n")).toContain("PLAN next");
- expect(app.tui.render(100).join("\n")).toContain(
- "Plan Mode · next message enters Plan",
- );
- terminal.input?.("计");
- expect(app.tui.render(100).join("\n")).toContain(
- "Plan Mode · next message enters Plan",
- );
- expect(app.tui.render(32).join("\n")).toContain("Plan Mode");
- terminal.input?.("\x7f");
- expect(app.editor.getText()).toBe("");
- expect(app.tui.render(100).join("\n")).toContain(
- "Plan Mode · next message enters Plan",
- );
- terminal.input?.("计");
- terminal.input?.("划");
- expect(app.editor.getText()).toBe("计划");
- expect(app.tui.render(100).join("\n")).toContain("PLAN next");
- expect(app.tui.render(100).join("\n")).toContain(
- "Plan Mode · next message enters Plan",
- );
- terminal.input?.("\r");
- await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
- await app.controller.whenIdle();
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- content: "计划",
- clientIntent: "plan-entry",
- }),
- expect.any(AbortSignal),
- );
- expect(app.tui.render(100).join("\n")).toContain("PLAN");
- expect(app.tui.render(100).join("\n")).toContain("Auto");
- await app.stop();
- });
- it("keeps ordinary messages in Plan and exits only with an explicit one-shot intent", async () => {
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/plan on");
- await app.submit("Draft the implementation plan");
- await app.submit("Refine the verification section");
- expect(runtime.sendMessage).toHaveBeenNthCalledWith(
- 2,
- expect.not.objectContaining({ clientIntent: expect.anything() }),
- expect.any(AbortSignal),
- );
- expect(app.tui.render(100).join("\n")).toContain(
- "/workspace │ PLAN │ Auto",
- );
- await app.submit("/plan off");
- await app.submit("Implement the approved direction");
- expect(runtime.sendMessage).toHaveBeenLastCalledWith(
- expect.objectContaining({ clientIntent: "plan-exit" }),
- expect.any(AbortSignal),
- );
- expect(app.tui.render(100).join("\n")).not.toContain("PLAN");
- await app.stop();
- });
- it("keeps the one-shot Plan intent armed when direct admission rejects it", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.sendMessage).mockImplementationOnce(
- async function* rejectedAdmission() {
- yield* [] as TuiStreamEvent[];
- throw Object.assign(new Error("Plan entry is disabled"), {
- code: "local_plan_entry_disabled",
- });
- },
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/plan on");
- await app.submit("Plan this after the feature is enabled");
- expect(app.tui.render(100).join("\n")).toContain("PLAN next");
- await app.submit("Retry the same Plan intent");
- expect(runtime.sendMessage).toHaveBeenLastCalledWith(
- expect.objectContaining({ clientIntent: "plan-entry" }),
- expect.any(AbortSignal),
- );
- await app.stop();
- });
- it("settles a Plan transition from authoritative Session metadata when the stream is empty", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.sendMessage).mockImplementationOnce(
- async function* emptyAcceptedStream() {
- yield* [] as TuiStreamEvent[];
- },
- );
- vi.mocked(runtime.getSession).mockResolvedValue({
- sessionId: "session-1",
- workspace: "/workspace",
- interactionMode: "plan",
- });
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/plan on");
- await app.submit("Plan without emitting a stream event");
- expect(runtime.getSession).toHaveBeenCalledWith("session-1");
- expect(app.tui.render(100).join("\n")).toContain(
- "/workspace │ PLAN │ Auto",
- );
- expect(app.tui.render(100).join("\n")).not.toContain("PLAN next");
- await app.stop();
- });
- it("clears accepted Plan entry while authoritative metadata refresh is unavailable", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.getSession).mockRejectedValue(
- new Error("metadata temporarily unavailable"),
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/plan on");
- await app.submit("OK");
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({ content: "OK", clientIntent: "plan-entry" }),
- expect.any(AbortSignal),
- );
- expect(app.tui.render(100).join("\n")).not.toContain("/workspace │ PLAN");
- expect(app.tui.render(100).join("\n")).not.toContain("DEFAULT next");
- await app.stop();
- });
- it("preserves Plan intent through direct busy fallback into the Runtime Queue", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.listModels).mockResolvedValue([
- {
- providerId: "minimax",
- modelId: "MiniMax-M2.7",
- selected: true,
- variant: "",
- },
- ]);
- vi.mocked(runtime.sendMessage).mockImplementationOnce(
- async function* busyAdmission() {
- yield* [] as TuiStreamEvent[];
- throw Object.assign(new Error("Session is busy"), {
- code: "local_session_busy",
- });
- },
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/plan on");
- await app.submit("Queue this Plan request");
- expect(runtime.enqueueMessage).toHaveBeenCalledWith(
- "session-1",
- "Queue this Plan request",
- {
- attachments: [],
- clientIntent: "plan-entry",
- model: { providerId: "minimax", modelId: "MiniMax-M2.7", variant: "" },
- },
- );
- expect(app.tui.render(100).join("\n")).not.toContain("PLAN queued");
- await app.stop();
- });
- it("binds a one-shot Plan intent to only the first concurrent submission", async () => {
- let releaseFirstEvent: (() => void) | undefined;
- const firstEventGate = new Promise<void>((resolve) => {
- releaseFirstEvent = resolve;
- });
- const runtime = createRuntime();
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* delayedAdmission() {
- await firstEventGate;
- yield { type: "delta", content: "Planning" };
- yield { type: "done" };
- },
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/plan on");
- const first = app.submit("Plan the implementation");
- await vi.waitFor(() =>
- expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
- );
- await app.submit("Queue a follow-up while admission is quiet");
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({ clientIntent: "plan-entry" }),
- expect.any(AbortSignal),
- );
- expect(runtime.enqueueMessage).toHaveBeenCalledWith(
- "session-1",
- "Queue a follow-up while admission is quiet",
- {
- attachments: [],
- model: { providerId: "minimax", modelId: "MiniMax-M2.7" },
- },
- );
- releaseFirstEvent?.();
- await first;
- await app.stop();
- });
- it("shows the Desktop-aligned confirmation when the Agent calls EnterPlanMode", async () => {
- let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
- const runtime = createRuntime();
- vi.mocked(runtime.watchEvents).mockImplementation(
- async function* watchEvents(signal) {
- const event = await new Promise<TuiRuntimeEvent | undefined>(
- (resolve) => {
- emitEvent = resolve;
- signal.addEventListener("abort", () => resolve(undefined), {
- once: true,
- });
- },
- );
- if (event) yield event;
- await new Promise<void>((resolve) => {
- signal.addEventListener("abort", resolve, { once: true });
- });
- },
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Plan a complex change");
- await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
- const askEvent = runtimeEvent({
- type: "questionnaire.ask",
- timestamp: Date.now(),
- source: "runtime",
- payload: {
- sessionId: "session-1",
- agentName: "mavis",
- request: planEntryEventRequest("plan-entry-agent-tool"),
- },
- });
- expect(askEvent).toMatchObject({
- type: "questionnaire.ask",
- sessionId: "session-1",
- request: { id: "plan-entry-agent-tool", mode: "plan" },
- });
- emitEvent?.(askEvent);
- await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
- const panel = app.interaction.current();
- const rendered = panel?.render?.(100).join("\n") ?? "";
- expect(rendered).toContain("Use Plan mode?");
- expect(rendered).toContain(
- "Plan mode structures complex tasks before execution.",
- );
- expect(rendered).toContain("Continue with plan");
- expect(rendered).toContain("Deny");
- panel?.handleInput?.("\r");
- await vi.waitFor(() =>
- expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
- "mavis",
- "plan-entry-agent-tool",
- [
- {
- stepId: "plan-enter",
- selectedOptionIds: ["confirm"],
- selectedOther: false,
- },
- ],
- ),
- );
- await app.stop();
- });
- it("keeps a pending Plan exit armed when steer guides the current Plan Turn", async () => {
- let finishTurn: (() => void) | undefined;
- let interactionMode: "plan" | undefined;
- const runtime = createRuntime();
- vi.mocked(runtime.getSession).mockImplementation(async () => ({
- sessionId: "session-1",
- workspace: "/workspace",
- ...(interactionMode ? { interactionMode } : {}),
- }));
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* activePlanTurn() {
- interactionMode = "plan";
- yield { type: "delta", content: "Drafting the plan" };
- await new Promise<void>((resolve) => {
- finishTurn = resolve;
- });
- yield { type: "done" };
- },
- );
- vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
- schemaVersion: 1,
- sessionId,
- state: "running",
- turnId: "turn-plan",
- actions: { steer: true },
- }));
- vi.mocked(runtime.steer).mockResolvedValue({
- turnId: "turn-plan",
- mode: "steered",
- });
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/plan on");
- const planTurn = app.submit("Draft a plan");
- await vi.waitFor(() =>
- expect(app.tui.render(100).join("\n")).toContain(
- "/workspace │ PLAN │ Auto",
- ),
- );
- await app.submit("/plan off");
- await app.submit("/steer include rollback checks");
- expect(runtime.steer).toHaveBeenCalledWith(
- expect.objectContaining({
- sessionId: "session-1",
- message: { content: "include rollback checks" },
- }),
- );
- expect(app.tui.render(100).join("\n")).toContain("DEFAULT next");
- finishTurn?.();
- await planTurn;
- await app.stop();
- });
- it("does not arm a mode transition while a Plan Review is pending", async () => {
- let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
- const runtime = createRuntime();
- vi.mocked(runtime.watchEvents).mockImplementation(
- async function* watchEvents(signal) {
- const event = await new Promise<TuiRuntimeEvent | undefined>(
- (resolve) => {
- emitEvent = resolve;
- signal.addEventListener("abort", () => resolve(undefined), {
- once: true,
- });
- },
- );
- if (event) yield event;
- await new Promise<void>((resolve) => {
- signal.addEventListener("abort", resolve, { once: true });
- });
- },
- );
- const terminal = new FakeTerminal();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/plan on");
- await app.submit("Draft a plan");
- await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
- emitEvent?.(
- runtimeEvent({
- type: "questionnaire.ask",
- timestamp: Date.now(),
- source: "runtime",
- payload: {
- sessionId: "session-1",
- agentName: "mavis",
- request: planReviewEventRequest("plan-review-mode-guard"),
- },
- }),
- );
- await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
- // The compact panel owns the decision; the frozen plan is projected to the Transcript.
- expect(app.interaction.current()?.render?.(100).join("\n")).toContain(
- "Plan complete. What would you like to do?",
- );
- expect(app.tui.render(100).join("\n")).toContain("Frozen plan");
- terminal.input?.("\x1b[Z");
- expect(app.interaction.isActive()).toBe(true);
- expect(app.tui.render(100).join("\n")).toContain(
- "/workspace │ PLAN │ Auto",
- );
- expect(app.tui.render(100).join("\n")).not.toContain("DEFAULT next");
- await app.submit("/plan off");
- expect(app.interaction.isActive()).toBe(true);
- expect(app.tui.render(100).join("\n")).toContain(
- "/workspace │ PLAN │ Auto",
- );
- expect(app.tui.render(100).join("\n")).not.toContain("DEFAULT next");
- expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
- await app.submit("/steer bypass the review");
- expect(app.interaction.isActive()).toBe(true);
- expect(runtime.steer).not.toHaveBeenCalled();
- app.interaction.current()?.handleInput?.("\u001b");
- await vi.waitFor(() =>
- expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
- "mavis",
- "plan-review-mode-guard",
- [expect.objectContaining({ skipped: true })],
- ),
- );
- await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
- expect(app.tui.render(100).join("\n")).toContain(
- "/workspace │ PLAN │ Auto",
- );
- await app.stop();
- });
- it("streams Plan feedback and replaces it with the revised Plan Review", async () => {
- let emitReview: ((event: TuiRuntimeEvent) => void) | undefined;
- let releaseContinuation: (() => void) | undefined;
- let finishReply: ((value: boolean) => void) | undefined;
- const runtime = createRuntime();
- vi.mocked(runtime.replyQuestionnaire).mockImplementation(
- async () =>
- await new Promise<boolean>((resolve) => {
- finishReply = resolve;
- }),
- );
- vi.mocked(runtime.watchEvents).mockImplementation(
- async function* watchEvents(signal) {
- const review = await new Promise<TuiRuntimeEvent | undefined>(
- (resolve) => {
- emitReview = resolve;
- signal.addEventListener("abort", () => resolve(undefined), {
- once: true,
- });
- },
- );
- if (!review || signal.aborted) return;
- yield review;
- await new Promise<void>((resolve) => {
- releaseContinuation = resolve;
- signal.addEventListener("abort", resolve, { once: true });
- });
- if (signal.aborted) return;
- const turnId = "turn-runtime-plan-feedback";
- yield runtimeEvent({
- type: "session.start",
- timestamp: Date.now(),
- source: "runtime",
- payload: { sessionId: "session-1", turnId },
- });
- vi.mocked(runtime.getMessages).mockResolvedValue([
- {
- id: "assistant-revised-plan",
- role: "assistant",
- content: "I revised the plan with rollback coverage.",
- },
- ]);
- yield runtimeEvent({
- type: "questionnaire.ask",
- timestamp: Date.now(),
- source: "runtime",
- payload: {
- sessionId: "session-1",
- agentName: "mavis",
- request: {
- ...planReviewEventRequest("plan-review-feedback-revised"),
- modePayload: {
- planReview: {
- markdown:
- "# Revised frozen plan\n\nIncludes rollback coverage.",
- path: "/history/session-1/artifacts/plan.md",
- },
- },
- },
- },
- });
- yield runtimeEvent({
- type: "session.finish",
- timestamp: Date.now(),
- source: "runtime",
- payload: { sessionId: "session-1", turnId },
- });
- finishReply?.(true);
- await new Promise<void>((resolve) => {
- signal.addEventListener("abort", resolve, { once: true });
- });
- },
- );
- const terminal = new FakeTerminal();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/plan on");
- await app.submit("Draft a plan");
- await vi.waitFor(() => expect(emitReview).toBeTypeOf("function"));
- emitReview?.(
- runtimeEvent({
- type: "questionnaire.ask",
- timestamp: Date.now(),
- source: "runtime",
- payload: {
- sessionId: "session-1",
- agentName: "mavis",
- request: planReviewEventRequest("plan-review-feedback-live"),
- },
- }),
- );
- await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
- terminal.input?.("\u001b[B");
- terminal.input?.("\u001b[B");
- terminal.input?.("\r");
- for (const character of "Add rollback coverage")
- terminal.input?.(character);
- terminal.input?.("\r");
- await vi.waitFor(() => expect(finishReply).toBeTypeOf("function"));
- releaseContinuation?.();
- await vi.waitFor(() =>
- expect(
- app.transcript
- .snapshot()
- .map((cell) => cell.content)
- .join("\n"),
- ).toContain("I revised the plan with rollback coverage."),
- );
- expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
- "session-1",
- "turn-runtime-plan-feedback",
- expect.any(AbortSignal),
- );
- await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
- // The revised plan is projected to the Transcript; the panel stays the compact decision.
- expect(app.interaction.current()?.render?.(100).join("\n")).toContain(
- "Plan complete. What would you like to do?",
- );
- expect(app.tui.render(100).join("\n")).toContain("Revised frozen plan");
- expect(app.tui.render(100).join("\n")).not.toContain(
- "Message · Enter send",
- );
- await app.stop();
- });
- it("supports explicit /plan and /permission mode commands", async () => {
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/plan on");
- expect(app.tui.render(100).join("\n")).toContain("PLAN next");
- await app.submit("/permission full");
- expect(runtime.setPermissionMode).toHaveBeenCalledWith("bypassPermissions");
- expect(app.tui.render(100).join("\n")).toContain("Full access");
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- await app.submit("Plan with Full access");
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({ clientIntent: "plan-entry" }),
- expect.any(AbortSignal),
- );
- expect(app.tui.render(100).join("\n")).toContain("PLAN");
- expect(app.tui.render(100).join("\n")).toContain("Full access");
- await app.stop();
- });
- it("opens a permission mode selector for bare /permission", async () => {
- const runtime = createRuntime();
- const terminal = new FakeTerminal();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/permission");
- expect(app.interaction.isActive()).toBe(true);
- const rendered = app.interaction.current()?.render?.(100).join("\n") ?? "";
- expect(rendered).toContain("╭─ Permission");
- expect(rendered).toContain("Current · Auto");
- expect(rendered).toContain("ASK");
- expect(rendered).toContain("› AUTO");
- expect(rendered).toContain("FULL");
- expect(runtime.setPermissionMode).not.toHaveBeenCalled();
- terminal.input?.("\u001b[B");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.setPermissionMode).toHaveBeenCalledWith(
- "bypassPermissions",
- ),
- );
- expect(app.interaction.isActive()).toBe(false);
- expect(app.tui.render(100).join("\n")).toContain("Full access");
- await app.submit("/permission status");
- expect(app.interaction.isActive()).toBe(false);
- expect(
- app.transcript
- .snapshot()
- .map((cell) => cell.content)
- .join("\n"),
- ).toContain("Permission mode: Full access.");
- await app.stop();
- });
- it("opens the latest settled Plan as a read-only full snapshot", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.getLatestPlanReview).mockResolvedValue(
- planReviewEventRequest("plan-review-settled"),
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.openSession("session-1");
- await app.submit("/plan view");
- expect(runtime.getLatestPlanReview).toHaveBeenCalledWith(
- "mavis",
- "session-1",
- );
- const rendered = app.interaction.current()?.render?.(100).join("\n") ?? "";
- expect(rendered).toContain("Frozen plan");
- expect(rendered).toContain("/history/session-1/artifacts/plan.md");
- expect(rendered).not.toContain("Agree and start implementation");
- app.interaction.current()?.handleInput?.("\u001b");
- expect(app.interaction.isActive()).toBe(false);
- await app.stop();
- });
- it("does not open a settled Plan after the active Session changes", async () => {
- let resolveReview:
- | ((request: TuiQuestionnaireRequest | undefined) => void)
- | undefined;
- const runtime = createRuntime();
- vi.mocked(runtime.getLatestPlanReview).mockImplementation(
- async () =>
- await new Promise<TuiQuestionnaireRequest | undefined>((resolve) => {
- resolveReview = resolve;
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.openSession("session-1");
- const viewing = app.submit("/plan view");
- await vi.waitFor(() => expect(resolveReview).toBeTypeOf("function"));
- await app.openSession("session-2");
- resolveReview?.(planReviewEventRequest("stale-plan-review"));
- await viewing;
- expect(app.interaction.isActive()).toBe(false);
- expect(app.tui.render(100).join("\n")).not.toContain("Frozen plan");
- await app.stop();
- });
- it("blocks Plan entry but still allows Plan exit when the Runtime capability is disabled", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.getPlanModeCapabilities).mockResolvedValue({
- entryEnabled: false,
- });
- const terminal = new FakeTerminal();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.openSession("session-1");
- terminal.input?.("\x1b[Z");
- await app.submit("/plan on");
- expect(app.tui.render(100).join("\n")).not.toContain("PLAN next");
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- vi.mocked(runtime.getSession).mockResolvedValue({
- sessionId: "session-1",
- workspace: "/workspace",
- interactionMode: "plan",
- });
- await app.controller.refreshSessionMetadata("session-1");
- terminal.input?.("\x1b[Z");
- expect(app.tui.render(100).join("\n")).toContain("DEFAULT next");
- await app.stop();
- });
- it("fails closed when the Runtime Plan capability cannot be loaded", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.getPlanModeCapabilities).mockRejectedValue(
- new Error("Runtime unavailable"),
- );
- const terminal = new FakeTerminal();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- terminal.input?.("\x1b[Z");
- await app.submit("/plan on");
- expect(app.tui.render(100).join("\n")).not.toContain("PLAN next");
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- await app.stop();
- });
- it("submits the hidden Runtime engineering log command name as an ordinary prompt", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- runtimeLogDirectory: "/home/dev/.minimax/v2/observability/logs",
- });
- await app.submit("/logs");
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({ id: "session-1", content: "/logs" }),
- expect.any(AbortSignal),
- );
- });
- it("exposes sanitized checks and submits the hidden /config name as ordinary text", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
- {
- requestId: "permission-1",
- sessionId: "session-1",
- toolName: "bash",
- toolDescription: "Run tests",
- },
- ]);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.submit("/doctor");
- const doctorOutput = app.transcript.snapshot().at(-1)?.content ?? "";
- expect(app.interaction.current()).toBeUndefined();
- await app.submit("/config");
- expect(app.interaction.current()).toBeUndefined();
- await app.submit("/skills docs");
- const skillsPanel = app.interaction.current();
- const skillsOutput = skillsPanel?.render(80).join("\n") ?? "";
- expect(app.tui.render(80).join("\n")).not.toContain("Message · Enter");
- skillsPanel?.handleInput?.("\x1b");
- await app.submit("/mcp browser");
- const mcpPanel = app.interaction.current();
- const mcpOutput = mcpPanel?.render(80).join("\n") ?? "";
- expect(app.tui.render(80).join("\n")).not.toContain("Message · Enter");
- mcpPanel?.handleInput?.("\x1b");
- await app.submit("/permissions");
- const output = app.transcript
- .snapshot()
- .map((cell) => cell.content)
- .join("\n");
- expect(runtime.getRuntimeDiagnostics).toHaveBeenCalledTimes(1);
- expect(runtime.listSkills).toHaveBeenCalledWith("mavis", "docs");
- expect(runtime.listMcpServers).toHaveBeenCalledWith("browser", "session-1");
- expect(runtime.listPendingPermissions).toHaveBeenCalled();
- expect(doctorOutput).toContain("Configuration check");
- expect(doctorOutput).toContain("Status: Valid");
- expect(doctorOutput).not.toContain("/doctor");
- expect(output).toContain("Configuration check");
- expect(output).not.toContain("Effective configuration");
- expect(skillsOutput).toContain("Skills");
- expect(skillsOutput).toContain("Built-in · 1");
- expect(skillsOutput).toContain("Docs");
- expect(skillsOutput).toContain("● available · builtin");
- expect(mcpOutput).toContain("MCP servers");
- expect(mcpOutput).toContain("browser");
- expect(mcpOutput).toContain("◆ configured · stdio");
- expect(output).toContain("bash · Run tests");
- expect(output).not.toContain("TOKEN");
- expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({ id: "session-1", content: "/config" }),
- expect.any(AbortSignal),
- );
- });
- it("previews /feedback without uploading until Enter confirms the Runtime draft", async () => {
- const terminal = new FakeTerminal();
- terminal.rows = 30;
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/feedback Upload failed token=****");
- expect(runtime.prepareFeedback).toHaveBeenCalledWith({
- description: "Upload failed token=****",
- });
- expect(runtime.submitFeedback).not.toHaveBeenCalled();
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.interaction.isActive()).toBe(true);
- const panel = app.interaction.current();
- expect(panel?.render(80).join("\n")).toContain("Review feedback");
- panel?.handleInput?.("d");
- expect(panel?.render(80).join("\n")).toContain("Client mcode 0.1.0");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.submitFeedback).toHaveBeenCalledWith(
- "feedback-draft-1",
- expect.objectContaining({ onPhase: expect.any(Function) }),
- ),
- );
- expect(panel?.render(80).join("\n")).toContain("ticket-1");
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- terminal.input?.("\x1b");
- expect(app.interaction.isActive()).toBe(false);
- await app.stop();
- });
- it("cancels /feedback without uploading and keeps missing descriptions out of the Agent", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/feedback");
- expect(app.transcript.snapshot().at(-1)).toMatchObject({
- kind: "final-summary",
- content: "Usage: /feedback <message>",
- });
- expect(runtime.prepareFeedback).not.toHaveBeenCalled();
- await app.submit("/feedback Cancel this report");
- terminal.input?.("\x1b");
- await vi.waitFor(() =>
- expect(runtime.cancelFeedback).toHaveBeenCalledWith("feedback-draft-1"),
- );
- expect(runtime.submitFeedback).not.toHaveBeenCalled();
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- await app.stop();
- });
- it("keeps the status report local and submits the hidden /config name as text", async () => {
- const terminal = new FakeTerminal();
- terminal.rows = 24;
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- const transcriptBeforeStatus = app.transcript.snapshot();
- await app.submit("/status");
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.interaction.isActive()).toBe(true);
- expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
- const statusOutput = app.tui.render(80).join("\n");
- expect(statusOutput).toContain("MCode status");
- expect(statusOutput).toContain("Model");
- expect(statusOutput).not.toContain("/status");
- expect(statusOutput).toContain("/workspace");
- expect(statusOutput).toMatch(/Branch:\s+Not a Git repository/u);
- expect(statusOutput).toContain("Not applicable");
- expect(statusOutput).toContain("Session");
- expect(statusOutput).toContain("Permissions");
- expect(statusOutput).toContain("Auto");
- app.interaction.current()?.handleInput?.("\x1b");
- expect(app.interaction.isActive()).toBe(false);
- expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
- await app.submit("/config");
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.interaction.isActive()).toBe(false);
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({ id: "session-1", content: "/config" }),
- expect.any(AbortSignal),
- );
- expect(runtime.getRuntimeDiagnostics).not.toHaveBeenCalled();
- await app.stop();
- });
- it("commits the first frame immediately when the Pi renderer starts", async () => {
- const terminal = new FakeTerminal();
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- let firstFrameCommitted = false;
- void app.firstFrame.then(() => {
- firstFrameCommitted = true;
- });
- app.start();
- await app.firstFrame;
- expect(terminal.started).toBe(true);
- expect(firstFrameCommitted).toBe(true);
- expect(terminal.writes.join("")).toContain("Tips for getting started");
- await app.stop();
- });
- it("chooses the account region before routing login through the auth application", async () => {
- const runtime = createRuntime();
- const openedTargets: string[] = [];
- const logoutUrl =
- "https://agent.minimax.io/auth/logout?logout_redirect_uri=https%3A%2F%2Fagent.minimax.io";
- let authenticated = false;
- vi.mocked(runtime.getAccountStatus).mockImplementation(async () =>
- authenticated
- ? {
- status: "ready",
- defaultModel: "minimax/MiniMax-M2.7",
- providerId: "minimax",
- modelId: "MiniMax-M2.7",
- authMode: "managed-login",
- managedTokenPresent: true,
- warnings: [],
- }
- : {
- status: "needs-login",
- authMode: "managed-login",
- managedTokenPresent: false,
- warnings: [],
- },
- );
- const auth = {
- login: vi.fn(
- async (
- onProgress?: (progress: McodeAuthProgress) => void,
- _region?: "cn" | "en",
- ) => {
- authenticated = true;
- onProgress?.({
- state: "device-authorization",
- userCode: "ABCD-EFGH",
- verificationUri: "https://account.example.test/device",
- expiresInSec: 300,
- });
- return {
- state: "authenticated" as const,
- message:
- _region === "en"
- ? "Signed in with MiniMax Global. Restart MCode to use this account region."
- : "Signed in with MiniMax.",
- };
- },
- ),
- logout: vi.fn(async () => {
- authenticated = false;
- return {
- state: "signed-out" as const,
- message: "Signed out of MiniMax.",
- logoutUrl,
- };
- }),
- };
- const notifyAuthContextChanged = vi.fn(async () => {
- throw new Error("Hook lifecycle cleanup failed");
- });
- const app = createTuiApp({
- runtime,
- auth,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- openExternalTarget: async (target) => {
- openedTargets.push(target);
- throw new Error("no desktop session");
- },
- notifyAuthContextChanged,
- });
- app.start();
- await app.ready;
- expect(app.tui.render(80).join("\n")).toContain("Sign in with /login");
- await app.submit("/login");
- expect(auth.login).not.toHaveBeenCalled();
- expect(app.interaction.render(80).join("\n")).toContain("China (CN)");
- expect(app.interaction.render(80).join("\n")).toContain("Global");
- app.interaction.current()?.handleInput("\u001b[B");
- app.interaction.current()?.handleInput("\r");
- await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
- await vi.waitFor(() =>
- expect(app.controller.snapshot().account?.managedTokenPresent).toBe(true),
- );
- expect(app.getSurface()).toBe("conversation");
- expect(app.tui.render(80).join("\n")).not.toContain("Sign in with /login");
- expect(app.tui.render(80).join("\n")).not.toContain("Login required");
- await app.submit("/logout");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().account?.managedTokenPresent).toBe(
- false,
- ),
- );
- expect(app.tui.render(80).join("\n")).toContain("Sign in with /login");
- expect(auth.login).toHaveBeenCalledWith(expect.any(Function), "en");
- expect(openedTargets).toEqual([
- "https://account.example.test/device?client_surface=tui&download_source=mcode-internal",
- logoutUrl,
- ]);
- await vi.waitFor(() =>
- expect(app.transcript.snapshot()).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- kind: "warning",
- content:
- "Couldn't open the default browser. Open the authorization URL above manually.",
- }),
- expect.objectContaining({
- kind: "warning",
- content:
- "Couldn't open the default browser. Open the sign-out URL above manually.",
- }),
- ]),
- ),
- );
- expect(app.transcript.snapshot().slice(-6)).toMatchObject([
- {
- kind: "final-summary",
- content:
- "Complete MiniMax login in your browser:\nhttps://account.example.test/device?client_surface=tui&download_source=mcode-internal\nCode: ABCD-EFGH",
- },
- {
- kind: "warning",
- content:
- "Couldn't open the default browser. Open the authorization URL above manually.",
- },
- {
- kind: "final-summary",
- content:
- "Signed in with MiniMax Global. Restart MCode to use this account region.",
- },
- {
- kind: "final-summary",
- content: "Signed out of MiniMax.",
- },
- {
- kind: "final-summary",
- content: `Finish signing out in your browser:\n${logoutUrl}`,
- },
- {
- kind: "warning",
- content:
- "Couldn't open the default browser. Open the sign-out URL above manually.",
- },
- ]);
- expect(auth.login).toHaveBeenCalledOnce();
- expect(auth.logout).toHaveBeenCalledOnce();
- expect(notifyAuthContextChanged.mock.calls).toEqual([
- ["authenticated"],
- ["logged_out"],
- ]);
- expect(
- app.transcript
- .snapshot()
- .map((cell) => cell.content)
- .join("\n"),
- ).not.toContain("Sign-in wasn't completed");
- expect(
- app.transcript
- .snapshot()
- .map((cell) => cell.content)
- .join("\n"),
- ).not.toContain("Couldn't sign out");
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- await app.stop();
- });
- it("clears Runtime auth context when the shared account is already signed out", async () => {
- const notifyAuthContextChanged = vi.fn(async () => undefined);
- const logoutUrl =
- "https://agent.minimax.cn/auth/logout?logout_redirect_uri=https%3A%2F%2Fagent.minimax.cn";
- const openExternalTarget = vi.fn(() => new Promise<void>(() => {}));
- const app = createTuiApp({
- runtime: createRuntime(),
- auth: {
- login: vi.fn(),
- logout: vi.fn(async () => ({
- state: "already-signed-out" as const,
- message: "Already signed out of MiniMax.",
- logoutUrl,
- })),
- },
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- notifyAuthContextChanged,
- openExternalTarget,
- });
- app.start();
- await app.ready;
- await app.submit("/logout");
- expect(notifyAuthContextChanged).toHaveBeenCalledOnce();
- expect(notifyAuthContextChanged).toHaveBeenCalledWith("logged_out");
- expect(openExternalTarget).toHaveBeenCalledWith(logoutUrl);
- expect(app.transcript.snapshot()).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- content: `Finish signing out in your browser:\n${logoutUrl}`,
- }),
- ]),
- );
- await app.stop();
- });
- it("refreshes Runtime auth context when login renews an existing account", async () => {
- const runtime = createRuntime();
- let authenticated = false;
- vi.mocked(runtime.getAccountStatus).mockImplementation(async () =>
- authenticated
- ? {
- status: "ready",
- defaultModel: "minimax/MiniMax-M2.7",
- providerId: "minimax",
- modelId: "MiniMax-M2.7",
- authMode: "managed-login",
- managedTokenPresent: true,
- warnings: [],
- }
- : {
- status: "needs-login",
- authMode: "managed-login",
- managedTokenPresent: false,
- warnings: [],
- },
- );
- const notifyAuthContextChanged = vi.fn(async () => undefined);
- const auth = {
- login: vi.fn(async () => {
- authenticated = true;
- return {
- state: "already-authenticated" as const,
- message: "Already signed in with MiniMax.",
- };
- }),
- logout: vi.fn(async () => ({
- state: "signed-out" as const,
- message: "Signed out of MiniMax.",
- })),
- };
- const app = createTuiApp({
- runtime,
- auth,
- notifyAuthContextChanged,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- expect(app.tui.render(80).join("\n")).toContain("Sign in with /login");
- await app.submit("/login");
- app.interaction.current()?.handleInput("\u001b[B");
- app.interaction.current()?.handleInput("\r");
- await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
- expect(notifyAuthContextChanged).toHaveBeenCalledOnce();
- expect(notifyAuthContextChanged).toHaveBeenCalledWith("authenticated");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().account?.managedTokenPresent).toBe(true),
- );
- expect(app.getSurface()).toBe("conversation");
- expect(app.tui.render(80).join("\n")).not.toContain("Sign in with /login");
- expect(app.tui.render(80).join("\n")).not.toContain("Login required");
- await app.stop();
- });
- it("exits immediately through /quit without aborting the shared Runtime turn", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const abortSession = vi.spyOn(runtime, "abortSession");
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/quit");
- await app.stopped;
- expect(terminal.stopped).toBe(true);
- expect(abortSession).not.toHaveBeenCalled();
- });
- it("does not restore /quit after reopening the exited Session", async () => {
- const dataDir = await mkdtemp(join(tmpdir(), "mcode-quit-draft-"));
- try {
- const first = createTuiApp({
- runtime: createRuntime(),
- terminal: new FakeTerminal(),
- version: "0.1.0",
- dataDir,
- workspaceDir: "/workspace",
- });
- await first.ready;
- await first.openSession("session-1");
- first.editor.setText("/quit");
- first.editor.handleInput("\r");
- await first.stopped;
- const restored = createTuiApp({
- runtime: createRuntime(),
- terminal: new FakeTerminal(),
- version: "0.1.0",
- dataDir,
- workspaceDir: "/workspace",
- });
- await restored.ready;
- await restored.openSession("session-1");
- expect(restored.editor.getText()).toBe("");
- await restored.stop();
- } finally {
- await rm(dataDir, { recursive: true, force: true });
- }
- });
- it("keeps warning status details visible until the local panel closes", async () => {
- const terminal = new FakeTerminal();
- terminal.rows = 40;
- const runtime = createRuntime();
- vi.mocked(runtime.getAccountStatus).mockResolvedValue({
- status: "warning",
- defaultModel: "minimax/MiniMax-M2.7",
- providerId: "minimax",
- modelId: "MiniMax-M2.7",
- authMode: "managed-login",
- managedTokenPresent: true,
- warnings: ["Desktop login should be refreshed soon."],
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- const transcriptBeforeStatus = app.transcript.snapshot();
- await app.submit("/status");
- const rendered = app.tui.render(80).join("\n");
- expect(app.interaction.current()).toBeDefined();
- expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
- expect(rendered).toContain("Needs attention");
- expect(rendered).toContain("Connected with warnings");
- expect(rendered).toContain("Model");
- expect(rendered).toContain("Desktop login should be refreshed");
- expect(rendered).toContain("soon.");
- app.interaction.current()?.handleInput?.("\x1b");
- expect(app.interaction.current()).toBeUndefined();
- expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
- expect(app.tui.render(80).join("\n")).not.toContain(
- "Desktop login should be refreshed",
- );
- await app.stop();
- });
- it("reports doctor failures and submits the hidden /config name as text", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.getRuntimeDiagnostics).mockRejectedValue(
- new Error("Diagnostics unavailable"),
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.submit("/doctor");
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.transcript.snapshot().at(-1)).toMatchObject({
- kind: "error",
- content:
- "Couldn't load configuration check: Diagnostics unavailable. Retry.",
- });
- await app.submit("/config");
- expect(app.tui.hasOverlay()).toBe(false);
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({ id: "session-1", content: "/config" }),
- expect.any(AbortSignal),
- );
- expect(runtime.getRuntimeDiagnostics).toHaveBeenCalledTimes(1);
- });
- it("lets an async Session card replace a local status panel", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let resolveSessionPage:
- | ((page: {
- sessions: Array<{
- sessionId: string;
- title: string;
- workspaceDir: string;
- updatedAt: number;
- }>;
- hasMore: boolean;
- }) => void)
- | undefined;
- vi.mocked(runtime.listSessionPage).mockImplementationOnce(
- async () =>
- await new Promise((resolve) => {
- resolveSessionPage = resolve;
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- const transcriptBeforeStatus = app.transcript.snapshot();
- const sessionCard = app.submit("/sessions");
- await vi.waitFor(() =>
- expect(runtime.listSessionPage).toHaveBeenCalledOnce(),
- );
- await app.submit("/status");
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.interaction.isActive()).toBe(true);
- expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
- expect(app.tui.render(80).join("\n")).toContain("MCode status");
- resolveSessionPage?.({
- sessions: [
- {
- sessionId: "session-race",
- title: "Session opened after status",
- workspaceDir: "/workspace",
- updatedAt: Date.now(),
- },
- ],
- hasMore: false,
- });
- await sessionCard;
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.interaction.isActive()).toBe(true);
- app.interaction.current()?.handleInput?.("\x03");
- expect(runtime.getSession).not.toHaveBeenCalled();
- expect(app.interaction.isActive()).toBe(false);
- expect(app.tui.hasOverlay()).toBe(false);
- await app.stop();
- });
- it("keeps unsupported standalone MCP inspection concise and recoverable", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.listMcpServers).mockRejectedValue(
- Object.assign(new Error("DesktopService implementation detail"), {
- status: 501,
- code: "NOT_IMPLEMENTED",
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.submit("/mcp");
- expect(app.transcript.snapshot().at(-1)).toMatchObject({
- kind: "warning",
- content:
- "MCP status is not available in this build. Configured MCP tools remain available.",
- });
- });
- it("registers enabled Skills as discoverable slash commands without shadowing built-ins", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSkills).mockResolvedValue({
- skills: [
- {
- name: "docs",
- displayName: "Docs",
- description: "Read project docs",
- enabled: true,
- sourceKind: "builtin",
- },
- {
- name: "disabled-skill",
- enabled: false,
- },
- {
- name: "help",
- enabled: true,
- },
- ...Array.from({ length: 14 }, (_, index) => ({
- name: `skill-${index}`,
- description: `Generated skill ${index}`,
- enabled: true,
- })),
- ],
- hasMore: false,
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- app.editor.setText("/docs summarize this repository");
- expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
- "Skill · instructions · Enter invoke",
- );
- app.editor.setText("/context");
- expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
- "Command · Enter run",
- );
- app.editor.setText("/context explain this repository");
- expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
- "Prompt · Enter send",
- );
- app.editor.setText("/stop");
- expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
- "Command · Enter run",
- );
- app.editor.setText("/config");
- expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
- "Prompt · Enter send",
- );
- app.editor.setText("");
- await app.submit("/help");
- expect(app.transcript.snapshot()).toEqual([]);
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.interaction.isActive()).toBe(true);
- for (const character of "docs") terminal.input?.(character);
- terminal.input?.("\r");
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.interaction.isActive()).toBe(false);
- expect(app.editor.getText()).toBe("");
- await app.submit("/docs summarize this repository");
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- id: "session-1",
- content: "/docs summarize this repository",
- }),
- expect.any(AbortSignal),
- );
- vi.mocked(runtime.sendMessage).mockClear();
- await app.submit("/disabled-skill");
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({ id: "session-1", content: "/disabled-skill" }),
- expect.any(AbortSignal),
- );
- await app.stop();
- });
- it("deduplicates configured Skills case-insensitively and reserves built-in names", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSkills).mockResolvedValue({
- skills: [
- {
- name: "HELP",
- description: "A Skill that must not shadow /help",
- enabled: true,
- },
- {
- name: "Docs",
- description: "Read project docs",
- enabled: true,
- },
- {
- name: "docs",
- description: "Duplicate project docs command",
- enabled: true,
- },
- ],
- hasMore: false,
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/help");
- const helpPanel = app.interaction.current();
- expect(helpPanel).toBeDefined();
- helpPanel?.handleInput?.("\x1b");
- await app.submit("/help [arguments]");
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- id: "session-1",
- content: "/help [arguments]",
- }),
- expect.any(AbortSignal),
- );
- vi.mocked(runtime.sendMessage).mockClear();
- await app.submit("/docs explain this repository");
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- id: "session-1",
- content: "/docs explain this repository",
- }),
- expect.any(AbortSignal),
- );
- await app.stop();
- });
- it("uses public Runtime owners for Session inspection commands", async () => {
- const terminal = new FakeTerminal();
- terminal.rows = 40;
- const runtime = createRuntime();
- vi.mocked(runtime.getAccountStatus).mockResolvedValue({
- status: "ready",
- defaultModel: "minimax/MiniMax-M3",
- providerId: "minimax-cn-coding-plan",
- authMode: "managed-login",
- managedTokenPresent: true,
- modelSource: "token-plan",
- tokenPlanQuotaState: "available",
- tokenPlanSummary: { tier: "Ultra Plan", creditBalance: "0" },
- tokenPlanQuota: {
- fiveHour: { remainingPercent: 100, unlimited: false },
- weekly: { remainingPercent: 99, unlimited: false },
- video: { remainingCount: 5, totalCount: 5, unlimited: false },
- },
- warnings: [],
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.submit("Create a session");
- vi.mocked(runtime.sendMessage).mockClear();
- vi.mocked(runtime.getSessionUsage).mockClear();
- vi.mocked(runtime.getContextSnapshot).mockResolvedValueOnce({
- status: "live",
- contextUsage: {
- contextWindowTokens: 10_000,
- usedTokens: 3_000,
- totalCountSource: "PROVIDER_USAGE_ANCHORED",
- components: [],
- },
- });
- const transcriptBeforeUsage = app.transcript.snapshot();
- await app.submit("/usage");
- const usageOutput = app.tui.render(80).join("\n");
- expect(app.interaction.current()).toBeDefined();
- expect(app.transcript.snapshot()).toEqual(transcriptBeforeUsage);
- expect(usageOutput).toContain("Usage");
- expect(usageOutput).toContain("120 total");
- expect(usageOutput).toContain("30% used · 70% free");
- expect(usageOutput).toContain("Ultra Plan");
- expect(usageOutput).toContain("100% left");
- app.interaction.current()?.handleInput?.("\x1b");
- expect(app.interaction.current()).toBeUndefined();
- expect(app.transcript.snapshot()).toEqual(transcriptBeforeUsage);
- await app.submit("/compact keep test evidence");
- expect(runtime.getSessionUsage).toHaveBeenCalledWith("session-1");
- expect(runtime.getContextSnapshot).toHaveBeenCalledWith("session-1");
- expect(runtime.getAccountStatus).toHaveBeenCalledWith("session-1", {
- includeMembership: true,
- forceRefresh: true,
- });
- expect(runtime.requestCompaction).toHaveBeenCalledWith(
- "session-1",
- "mavis",
- "keep test evidence",
- );
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- const output = app.transcript
- .snapshot()
- .map((cell) => cell.content)
- .join("\n");
- expect(output).not.toContain("Session usage");
- expect(output).not.toMatch(
- /Turns|Total tokens|Cost|Reasoning|Cache|Runtime|source|compaction|snapshot/i,
- );
- expect(output).not.toContain("Compaction completed");
- expect(output).not.toContain("4,000 → 1,200 tokens");
- expect(output).not.toContain("compact-1");
- });
- it("shows compaction as live activity until the Runtime request settles", async () => {
- const runtime = createRuntime();
- let resolveCompaction:
- | ((result: {
- success: true;
- sessionId: string;
- compactionId: string;
- }) => void)
- | undefined;
- vi.mocked(runtime.requestCompaction).mockImplementationOnce(
- async () =>
- await new Promise((resolve) => {
- resolveCompaction = resolve;
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.submit("Create a session");
- const pending = app.submit("/compact keep decisions");
- await vi.waitFor(() =>
- expect(app.tui.render(80).join("\n")).toContain("Compacting context"),
- );
- expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
- resolveCompaction?.({
- success: true,
- sessionId: "session-1",
- compactionId: "compact-1",
- });
- await pending;
- expect(app.tui.render(80).join("\n")).not.toContain("Compacting context");
- });
- it("treats Runtime NOTHING_TO_COMPACT as a recoverable Session state", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.requestCompaction).mockRejectedValue(
- Object.assign(new Error("HTTP 400 implementation detail"), {
- status: 400,
- code: "NOTHING_TO_COMPACT",
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.submit("Create a session");
- await app.submit("/compact");
- expect(app.transcript.snapshot().at(-1)).toMatchObject({
- kind: "final-summary",
- content: "No compaction is needed for this conversation yet.",
- });
- });
- it("shows account usage before a Session exists and keeps Session-only inspection recoverable", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.getAccountStatus).mockResolvedValue({
- status: "ready",
- authMode: "byok",
- managedTokenPresent: false,
- modelSource: "byok",
- tokenPlanQuotaState: "available",
- tokenPlanSummary: { tier: "Pro Plan" },
- tokenPlanQuota: {
- fiveHour: { remainingPercent: 75, unlimited: false },
- weekly: { remainingPercent: 50, unlimited: false },
- },
- warnings: [],
- });
- const terminal = new FakeTerminal();
- terminal.rows = 40;
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.submit("/usage");
- const usageOutput = app.tui.render(80).join("\n");
- expect(app.interaction.current()).toBeDefined();
- expect(app.transcript.snapshot()).toEqual([]);
- expect(usageOutput).toContain("Usage");
- expect(usageOutput).toContain("Account only");
- expect(usageOutput).toContain("Pro Plan");
- expect(usageOutput).toContain("75% left");
- app.interaction.current()?.handleInput?.("\x1b");
- expect(app.interaction.current()).toBeUndefined();
- expect(app.transcript.snapshot()).toEqual([]);
- await app.submit("/compact");
- expect(runtime.getSessionUsage).not.toHaveBeenCalled();
- expect(runtime.getContextSnapshot).not.toHaveBeenCalled();
- expect(runtime.getAccountStatus).toHaveBeenCalledWith(undefined, {
- includeMembership: true,
- forceRefresh: true,
- });
- expect(app.transcript.snapshot()).toEqual([]);
- expect(app.tui.render(80).join("\n")).toContain(
- "Start or resume a Session before compacting it.",
- );
- });
- it("keeps prompt history and long bracketed paste intact in the Composer", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- terminal.input?.("first prompt");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
- );
- terminal.input?.("second prompt");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.sendMessage).toHaveBeenCalledTimes(2),
- );
- terminal.input?.("\x1b[A");
- expect(app.editor.getText()).toBe("second prompt");
- terminal.input?.("\x1b[A");
- expect(app.editor.getText()).toBe("first prompt");
- terminal.input?.("\x1b[B");
- expect(app.editor.getText()).toBe("second prompt");
- app.editor.setText("");
- const pasted = `Explain this payload:\n${"x".repeat(1_200)}`;
- terminal.input?.(`\x1b[200~${pasted}\x1b[201~`);
- expect(app.editor.getText()).toContain("[paste #");
- expect(app.editor.getExpandedText()).toBe(pasted);
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.sendMessage).toHaveBeenCalledTimes(3),
- );
- expect(runtime.sendMessage).toHaveBeenLastCalledWith(
- expect.objectContaining({ id: "session-1", content: pasted }),
- expect.any(AbortSignal),
- );
- await app.stop();
- });
- it("trusts bracketed paste and submits dense typed input without a false newline", async () => {
- const terminal = new FakeTerminal();
- Object.defineProperty(terminal, "capabilities", {
- value: {
- terminalId: "unknown",
- platform: "linux",
- isTTY: true,
- transport: "local",
- multiplexer: "none",
- color: true,
- colorLevel: 3,
- } satisfies TerminalCapabilities,
- });
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- for (const character of "abcdefgh") terminal.input?.(character);
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
- );
- expect(app.editor.getText()).toBe("");
- await app.stop();
- });
- it("projects an otty image paste as an inline editor placeholder", async () => {
- const terminal = new FakeTerminal();
- const resolveAttachment = vi.fn(async () => ({
- type: "image" as const,
- filePath: "/tmp/otty-paste/image-123.png",
- fileName: "image-123.png",
- mimeType: "image/png",
- sizeBytes: 1_024,
- }));
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- resolveAttachment,
- });
- app.start();
- await app.ready;
- terminal.input?.("\x1b[200~/tmp/otty-paste/image-123.png\x1b[201~");
- await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledTimes(1));
- const rendered = app.tui.render(80).join("\n");
- expect(app.editor.getText()).toBe("[Image #1] ");
- expect(rendered).toContain("[Image #1]");
- expect(rendered).not.toContain("/tmp/otty-paste/");
- await app.stop();
- });
- it.each(["regular", "fullscreen"] as const)(
- "keeps image preview controls separate from Enter submission in %s mode",
- async (tuiMode) => {
- const terminal = new FakeTerminal();
- terminal.rows = 40;
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- tuiMode,
- version: "0.1.0",
- workspaceDir: "/workspace",
- resolveAttachment: async () => ({
- type: "image",
- filePath: "/tmp/image-preview-missing.png",
- fileName: "preview.png",
- mimeType: "image/png",
- sizeBytes: 32768,
- }),
- });
- app.start();
- await app.ready;
- terminal.input?.("\x1b[200~/tmp/image-preview-missing.png\x1b[201~");
- await vi.waitFor(() =>
- expect(app.editor.getAttachmentPreview()?.id).toBe(
- "/tmp/image-preview-missing.png",
- ),
- );
- expect(app.editor.getText()).toBe("[Image #1] ");
- expect(app.tui.render(80).join("\n")).toContain("preview.png");
- expect(app.tui.render(80).join("\n")).toContain("32 KB");
- expect(app.tui.render(80).join("\n")).not.toMatch(/Option\+I|Alt\+I/);
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- terminal.input?.("\x1b");
- expect(app.editor.getAttachmentPreview()).toBeUndefined();
- terminal.input?.("\x1b[D");
- expect(app.editor.getAttachmentPreview()?.id).toBe(
- "/tmp/image-preview-missing.png",
- );
- terminal.input?.("\r");
- await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalled());
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- content: "",
- attachments: [
- expect.objectContaining({
- local: { filePath: "/tmp/image-preview-missing.png" },
- }),
- ],
- }),
- expect.any(AbortSignal),
- );
- expect(app.editor.getAttachmentPreview()).toBeUndefined();
- await app.stop();
- },
- );
- it("projects a pasted absolute WeChat image path as a short inline placeholder", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const wechatImagePath =
- "D:\\Yingyong\\social\\wechat\\xwechat_files\\wxid_demo\\temp\\RWTemp\\2026-08\\3336519cd4d5351f4bc5a5a68c7fea75.png";
- const resolveAttachment = vi.fn(async () => ({
- type: "image" as const,
- filePath: wechatImagePath,
- fileName: "3336519cd4d5351f4bc5a5a68c7fea75.png",
- mimeType: "image/png",
- sizeBytes: 1_024,
- }));
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "D:\\workspace",
- resolveAttachment,
- });
- app.start();
- await app.ready;
- terminal.input?.(`\x1b[200~'${wechatImagePath}'\x1b[201~`);
- await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledOnce());
- expect(resolveAttachment).toHaveBeenCalledWith(`'${wechatImagePath}'`, {
- source: "terminal-paste",
- workspaceDir: "D:\\workspace",
- });
- expect(app.editor.getText()).toBe("[Image #1] ");
- expect(app.tui.render(80).join("\n")).not.toContain("xwechat_files");
- await app.submit("Inspect this image");
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- content: "Inspect this image",
- attachments: [
- expect.objectContaining({
- local: { filePath: wechatImagePath },
- }),
- ],
- }),
- expect.any(AbortSignal),
- );
- await app.stop();
- });
- it("keeps an image placeholder visible before a long CJK prompt", async () => {
- const terminal = new FakeTerminal();
- const resolveAttachment = vi.fn(async () => ({
- type: "image" as const,
- filePath: "/tmp/otty-paste/logo.png",
- fileName: "logo.png",
- mimeType: "image/png",
- sizeBytes: 1_024,
- }));
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- resolveAttachment,
- });
- app.start();
- await app.ready;
- terminal.input?.("\x1b[200~/tmp/otty-paste/logo.png\x1b[201~");
- await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledTimes(1));
- app.editor.insertTextAtCursor(
- "logo 不太对还是,还出现了奇怪的--; logo你自己截取把:",
- );
- const rendered = app.tui.render(80).join("\n");
- expect(rendered).toContain("[Image #1]");
- await app.stop();
- });
- it("removes an inline image placeholder and its attachment with Backspace", async () => {
- const terminal = new FakeTerminal();
- const resolveAttachment = vi.fn(async () => ({
- type: "image" as const,
- filePath: "/tmp/otty-paste/image-123.png",
- fileName: "image-123.png",
- mimeType: "image/png",
- sizeBytes: 1_024,
- }));
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- resolveAttachment,
- });
- app.start();
- await app.ready;
- app.editor.setText("first line\nsecond line");
- terminal.input?.("\x1b[200~/tmp/otty-paste/image-123.png\x1b[201~");
- await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledTimes(1));
- expect(app.editor.getText()).toBe("first line\nsecond line [Image #1] ");
- expect(app.tui.render(80).join("\n")).toContain("[Image #1]");
- terminal.input?.("\x7f");
- await vi.waitFor(() =>
- expect(app.editor.getText().trimEnd()).toBe("first line\nsecond line"),
- );
- expect(app.tui.render(80).join("\n")).not.toContain("[Image #1]");
- await app.stop();
- });
- it("resumes Desktop history, supports rename, and executes the files-unchanged fork flow", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-existing",
- title: "Existing session",
- workspaceDir: "/workspace",
- updatedAt: 200,
- },
- ]);
- const history = [
- {
- id: "msg-user-v1-fork-source",
- turnId: "turn-history",
- role: "user" as const,
- content: "Try the original approach",
- timestamp: 90,
- },
- {
- id: "assistant-fork-source",
- turnId: "turn-history",
- role: "assistant" as const,
- content: "Recovered answer",
- timestamp: 100,
- actions: { fork: true },
- },
- ];
- const forkRuntime = runtime as TuiRuntime & TuiSessionForkPort;
- vi.mocked(runtime.getMessages).mockResolvedValue(history);
- vi.mocked(runtime.listMessagePage).mockResolvedValue({
- messages: history,
- hasMore: false,
- });
- vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
- sessionId === "session-fork"
- ? {
- sessionId,
- parentSessionId: "session-existing",
- title: "Existing session (fork 1)",
- workspaceDir: "/workspace",
- }
- : {
- sessionId,
- title: "Existing session",
- workspaceDir: "/workspace",
- },
- );
- vi.mocked(forkRuntime.getSessionForkOptions).mockResolvedValue({
- canFork: true,
- suggestedTitle: "Existing session (fork 1)",
- worktreeVisible: false,
- worktreeEligible: false,
- });
- vi.mocked(forkRuntime.forkSession).mockResolvedValue({
- session: {
- sessionId: "session-fork",
- parentSessionId: "session-existing",
- title: "Existing session (fork 1)",
- workspaceDir: "/workspace",
- },
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/sessions");
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.interaction.isActive()).toBe(true);
- app.interaction.current()?.handleInput?.("\x1b");
- expect(app.interaction.isActive()).toBe(false);
- await app.submit("/resume 1");
- expect(app.getSurface()).toBe("conversation");
- vi.mocked(runtime.renameSession).mockClear();
- await app.submit("/rename");
- expect(runtime.renameSession).not.toHaveBeenCalled();
- expect(app.interaction.isActive()).toBe(true);
- expect(app.tui.render(100).join("\n")).toContain(
- "Sessions / Rename session",
- );
- app.interaction.current()?.handleInput?.("\x1b");
- expect(app.tui.render(100).join("\n")).toContain("Sessions");
- app.interaction.current()?.handleInput?.("\x1b");
- expect(app.interaction.isActive()).toBe(false);
- await app.submit("/rename Renamed session");
- vi.mocked(runtime.createSession).mockClear();
- await app.submit("/fork");
- await vi.waitFor(() =>
- expect(runtime.listSessionInputSummaries).toHaveBeenCalledWith(
- "session-existing",
- {
- limit: 100,
- },
- ),
- );
- // The new fork flow owns the surface with the history picker, not the
- // generic transcript panel.
- expect(renderTerminalViewport(app, terminal)).toContain(
- "Fork from a previous message",
- );
- expect(renderTerminalViewport(app, terminal)).not.toContain("Transcript");
- // Esc cancels without calling the fork Runtime API.
- const beforeForkCalls = vi.mocked(runtime.forkSession).mock.calls.length;
- app.surfaceHost.popFeature();
- expect(vi.mocked(runtime.forkSession).mock.calls.length).toBe(
- beforeForkCalls,
- );
- const transcriptBeforeStatus = app.transcript.snapshot();
- await app.submit("/status");
- expect(runtime.getSession).toHaveBeenCalledWith("session-existing");
- expect(app.interaction.current()).toBeDefined();
- expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
- expect(app.tui.render(100).join("\n")).toContain("MCode status");
- expect(runtime.renameSession).toHaveBeenCalledWith(
- "session-existing",
- "Renamed session",
- );
- expect(runtime.createSession).not.toHaveBeenCalled();
- expect(app.transcript.snapshot()).not.toEqual(
- expect.arrayContaining([
- expect.objectContaining({ content: "Unknown command. Use /help." }),
- ]),
- );
- app.interaction.current()?.handleInput?.("\x1b");
- await app.stop();
- });
- it.each(["regular", "fullscreen"] as const)(
- "presents /history in %s mode and returns to chat on cancel",
- async (tuiMode) => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- {
- userMessageId: "msg-user-history",
- assistantMessageId: "msg-assistant-history",
- contentHead: "Inspect the Session UI",
- timestamp: 1_700_000_000_000,
- fileChangeCount: 1,
- },
- ]);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- tuiMode,
- });
- app.start();
- await app.ready;
- await app.submit("Seed the session");
- await app.submit("/history");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-history:explorer",
- }),
- );
- expect(renderTerminalViewport(app, terminal)).toContain(
- "Inspect the Session UI",
- );
- expect(renderTerminalViewport(app, terminal)).toContain("Search:");
- expect(renderTerminalViewport(app, terminal)).toContain("Enter actions");
- terminal.input?.("\u001b");
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "chat",
- id: "chat",
- });
- await app.stop();
- },
- );
- it("forks with the assistant boundary and starts a new operation after a terminal failure", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- {
- userMessageId: "msg-user-1",
- assistantMessageId: "msg-assistant-1",
- contentHead: "Investigate flaky login tests",
- timestamp: 1_700_000_000_000,
- fileChangeCount: 2,
- },
- {
- userMessageId: "msg-user-2",
- assistantMessageId: "msg-assistant-2",
- contentHead: "Draft a new CLI handler",
- timestamp: 1_699_999_000_000,
- fileChangeCount: 0,
- },
- ]);
- vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
- canFork: true,
- worktreeVisible: false,
- worktreeEligible: false,
- });
- vi.mocked(runtime.forkSession).mockRejectedValueOnce(
- Object.assign(new Error("persisted fork recovery failed"), {
- key: "FORK_RECOVERY_FAILED",
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- // Submit a message so the controller has an active session id.
- await app.submit("Seed the session");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
- );
- const sourceSessionId = app.controller.snapshot().session?.sessionId;
- expect(sourceSessionId).toBe("session-1");
- const transcriptBefore = app.transcript.snapshot();
- vi.mocked(runtime.createSession).mockClear();
- vi.mocked(runtime.forkSession).mockClear();
- vi.mocked(runtime.getSessionForkOptions).mockClear();
- vi.mocked(runtime.listSessionInputSummaries).mockClear();
- await app.submit("/fork");
- // 1. /fork loads input summaries, not the generic transcript.
- await vi.waitFor(() =>
- expect(runtime.listSessionInputSummaries).toHaveBeenCalledWith(
- sourceSessionId,
- {
- limit: 100,
- },
- ),
- );
- expect(renderTerminalViewport(app, terminal)).toContain(
- "Fork from a previous message",
- );
- expect(renderTerminalViewport(app, terminal)).not.toContain("Transcript");
- // 2. The newest summary (last entry) is selected by default; confirm with Enter.
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:history",
- }),
- );
- terminal.input?.("\r");
- // The history selection only fetches options; it must not mutate yet.
- await vi.waitFor(() =>
- expect(runtime.getSessionForkOptions).toHaveBeenCalledWith(
- sourceSessionId,
- "msg-assistant-2",
- ),
- );
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:fork-confirm",
- }),
- );
- expect(runtime.forkSession).not.toHaveBeenCalled();
- expect(renderTerminalViewport(app, terminal)).toContain("Confirm fork");
- // 3. Explicit confirmation performs the mutation.
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.forkSession).toHaveBeenCalledWith(
- expect.objectContaining({
- sessionId: sourceSessionId,
- assistantMessageId: "msg-assistant-2",
- useSuggestedTitle: true,
- createIsolatedWorktree: false,
- }),
- ),
- );
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:fork-confirm",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.forkSession).toHaveBeenCalledTimes(2),
- );
- const forkCalls = vi.mocked(runtime.forkSession).mock.calls;
- const operationIds = forkCalls.map(([input]) => input.clientRequestId);
- expect(operationIds[0]).toBeTruthy();
- expect(operationIds[1]).toBeTruthy();
- expect(operationIds[0]).not.toBe(operationIds[1]);
- // 5. Activation moves the controller to the child session id.
- await vi.waitFor(() =>
- expect(app.controller.snapshot().session?.sessionId).toBe("session-fork"),
- );
- expect(runtime.createSession).not.toHaveBeenCalled();
- // The user message that seeded the source session was already projected
- // into the transcript before the fork ran; the fork flow must not write
- // any new user-typed cell while the picker is open or the mutation runs.
- expect(
- transcriptBefore.filter((cell) => cell.kind === "user").length,
- ).toBeGreaterThan(0);
- });
- it("does not call forkSession when /fork is cancelled, unavailable, or fails", async () => {
- const scenarios: ReadonlyArray<{
- readonly label: string;
- readonly setup: (runtime: ReturnType<typeof createRuntime>) => void;
- readonly interact: (terminal: FakeTerminal) => void | Promise<void>;
- /** When true, expect forkSession to have been called exactly once. */
- readonly expectForkCall: boolean;
- readonly confirmAfterSelection?: boolean;
- }> = [
- {
- label: "esc cancels the picker without invoking fork",
- setup: (runtime) => {
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- {
- userMessageId: "msg-user-1",
- assistantMessageId: "msg-assistant-1",
- contentHead: "Investigate flaky login tests",
- timestamp: 1_700_000_000_000,
- fileChangeCount: 0,
- },
- ]);
- },
- interact: (terminal) => {
- terminal.input?.("\u001b");
- },
- expectForkCall: false,
- },
- {
- label: "unavailable fork surfaces a warning without invoking fork",
- setup: (runtime) => {
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- {
- userMessageId: "msg-user-1",
- assistantMessageId: "msg-assistant-1",
- contentHead: "Investigate flaky login tests",
- timestamp: 1_700_000_000_000,
- fileChangeCount: 0,
- },
- ]);
- vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
- canFork: false,
- unavailableReason: "No persisted user prompts yet.",
- worktreeVisible: false,
- worktreeEligible: false,
- });
- },
- interact: (terminal) => {
- terminal.input?.("\r");
- },
- expectForkCall: false,
- },
- {
- label:
- "forkSession failure preserves the source session and transcript",
- setup: (runtime) => {
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- {
- userMessageId: "msg-user-1",
- assistantMessageId: "msg-assistant-1",
- contentHead: "Investigate flaky login tests",
- timestamp: 1_700_000_000_000,
- fileChangeCount: 0,
- },
- ]);
- vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
- canFork: true,
- worktreeVisible: false,
- worktreeEligible: false,
- });
- vi.mocked(runtime.forkSession).mockRejectedValue(
- new Error("Runtime offline."),
- );
- },
- interact: (terminal) => {
- terminal.input?.("\r");
- },
- expectForkCall: true,
- confirmAfterSelection: true,
- },
- ];
- for (const scenario of scenarios) {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- scenario.setup(runtime);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Seed the session");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
- );
- const sourceSessionId = app.controller.snapshot().session?.sessionId;
- const transcriptBefore = app.transcript.snapshot();
- await app.submit("/fork");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:history",
- }),
- );
- await scenario.interact(terminal);
- if (scenario.expectForkCall || scenario.label.includes("unavailable")) {
- await vi.waitFor(() =>
- expect(runtime.getSessionForkOptions).toHaveBeenCalled(),
- );
- }
- expect(runtime.forkSession).not.toHaveBeenCalled();
- if (scenario.confirmAfterSelection) {
- terminal.input?.("\r");
- }
- // Give the async fork pipeline a chance to settle.
- await new Promise((resolve) => setTimeout(resolve, 40));
- if (scenario.expectForkCall) {
- expect(
- vi.mocked(runtime.forkSession).mock.calls.length,
- `${scenario.label} should call forkSession once`,
- ).toBe(1);
- } else {
- expect(
- vi.mocked(runtime.forkSession).mock.calls.length,
- `${scenario.label} should not call forkSession`,
- ).toBe(0);
- }
- expect(
- app.controller.snapshot().session?.sessionId,
- `${scenario.label} must not switch sessions`,
- ).toBe(sourceSessionId);
- expect(
- app.transcript.snapshot().filter((cell) => cell.kind === "user").length,
- `${scenario.label} must preserve the source transcript`,
- ).toBe(transcriptBefore.filter((cell) => cell.kind === "user").length);
- await app.stop();
- }
- });
- it("does not call forkSession when the source session changes between summary and selection", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- {
- userMessageId: "msg-user-1",
- assistantMessageId: "msg-assistant-1",
- contentHead: "Investigate flaky login tests",
- timestamp: 1_700_000_000_000,
- fileChangeCount: 0,
- },
- ]);
- vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
- canFork: true,
- worktreeVisible: false,
- worktreeEligible: false,
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Seed the session");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
- );
- await app.submit("/fork");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:history",
- }),
- );
- // Simulate the source session changing while the picker is open.
- const otherSession = {
- sessionId: "session-other",
- title: "Other session",
- workspaceDir: "/workspace",
- };
- vi.mocked(runtime.listSessions).mockResolvedValue([otherSession]);
- vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
- sessionId === otherSession.sessionId
- ? otherSession
- : { sessionId, workspaceDir: "/workspace" },
- );
- await app.openSession(otherSession.sessionId);
- expect(app.controller.snapshot().session?.sessionId).toBe(
- otherSession.sessionId,
- );
- // Confirming the picker now must not call forkSession.
- terminal.input?.("\r");
- await new Promise((resolve) => setTimeout(resolve, 20));
- expect(vi.mocked(runtime.forkSession)).not.toHaveBeenCalled();
- expect(vi.mocked(runtime.getSessionForkOptions).mock.calls.length).toBe(0);
- });
- it("preserves the /fork command draft and skips mutation when a turn is running", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let finishTurn: (() => void) | undefined;
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage() {
- await new Promise<void>((resolve) => {
- finishTurn = resolve;
- });
- yield { type: "done" };
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- const submission = app.submit("Seed the session");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
- );
- await vi.waitFor(() =>
- expect(vi.mocked(runtime.sendMessage)).toHaveBeenCalled(),
- );
- const summariesBefore = vi.mocked(runtime.listSessionInputSummaries).mock
- .calls.length;
- const forkOptionsBefore = vi.mocked(runtime.getSessionForkOptions).mock
- .calls.length;
- const forkBefore = vi.mocked(runtime.forkSession).mock.calls.length;
- // While the turn is still running, /fork should preserve the draft and
- // skip every runtime mutation method.
- app.editor.setText("/fork");
- await app.submit("/fork");
- expect(app.editor.getText()).toBe("/fork");
- expect(vi.mocked(runtime.listSessionInputSummaries).mock.calls.length).toBe(
- summariesBefore,
- );
- expect(vi.mocked(runtime.getSessionForkOptions).mock.calls.length).toBe(
- forkOptionsBefore,
- );
- expect(vi.mocked(runtime.forkSession).mock.calls.length).toBe(forkBefore);
- // The fork surface should not have been pushed either.
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "chat",
- id: "chat",
- });
- finishTurn?.();
- await submission;
- await app.stop();
- });
- it.each([
- ["conversation", []],
- ["conversation_and_files", ["\u001b[B"]],
- ] as const)(
- "runs /rewind with explicit %s scope and stable operation id",
- async (scope, navigation) => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- {
- userMessageId: "msg-user-rewind",
- contentHead: "Undo this point",
- timestamp: 1_700_000_000_000,
- fileChangeCount: 2,
- },
- ]);
- vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
- turns: [
- {
- turnId: "turn-1",
- files: [
- { filePath: "src/ready.ts", action: "modified", skipped: false },
- { filePath: "src/skipped.ts", action: "deleted", skipped: true },
- ],
- },
- ],
- });
- vi.mocked(runtime.rewindSession).mockResolvedValue(
- scope === "conversation"
- ? { rewound: true }
- : {
- rewound: true,
- turnDiffRewind: {
- status: "rewound",
- revertedTurnIds: ["turn-1"],
- },
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Seed rewind session");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
- );
- expect(
- app.transcript.snapshot().some((cell) => cell.kind === "turn-duration"),
- ).toBe(true);
- vi.mocked(runtime.getMessages).mockResolvedValue([]);
- await app.submit("/rewind");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:history",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.getSessionRewindPreview).toHaveBeenCalledWith({
- sessionId: "session-1",
- userMessageId: "msg-user-rewind",
- }),
- );
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:rewind-preview",
- }),
- );
- expect(renderTerminalViewport(app, terminal)).toContain("src/ready.ts");
- expect(renderTerminalViewport(app, terminal)).toContain("src/skipped.ts");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:scope",
- }),
- );
- for (const key of navigation) terminal.input?.(key);
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:rewind-confirm",
- }),
- );
- expect(runtime.rewindSession).not.toHaveBeenCalled();
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
- );
- const input = vi.mocked(runtime.rewindSession).mock.calls[0]?.[0];
- expect(input).toEqual({
- sessionId: "session-1",
- userMessageId: "msg-user-rewind",
- clientRequestId: expect.stringMatching(/^tui-rewind_/),
- ...(scope === "conversation_and_files" ? { rewindTurnDiff: true } : {}),
- });
- expect(input?.clientRequestId).toMatch(/^tui-rewind_/);
- await vi.waitFor(() => expect(runtime.getMessages).toHaveBeenCalled());
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "chat",
- id: "chat",
- }),
- );
- expect(
- app.transcript
- .snapshot()
- .some((cell) => cell.content === "Rewind completed."),
- ).toBe(false);
- expect(app.transcript.snapshot()).toEqual([]);
- await app.stop();
- },
- );
- it("edits only the latest user turn, hides that turn while editing, and adds no completion cell", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- {
- userMessageId: "msg-user-older",
- assistantMessageId: "msg-assistant-older",
- contentHead: "Older prompt",
- timestamp: 1,
- fileChangeCount: 0,
- },
- {
- userMessageId: "msg-user-latest",
- assistantMessageId: "msg-assistant-latest",
- contentHead: "Latest prompt",
- timestamp: 2,
- fileChangeCount: 0,
- },
- ]);
- vi.mocked(runtime.listMessagePage).mockResolvedValue({
- messages: [
- {
- id: "msg-user-older",
- role: "user",
- content: "Older prompt",
- timestamp: 1,
- },
- {
- id: "msg-user-latest",
- role: "user",
- content: "Latest prompt",
- timestamp: 2,
- },
- ],
- hasMore: false,
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Seed edit session");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
- );
- app.transcript.upsert({
- id: "older-user-cell",
- kind: "user",
- status: "succeeded",
- content: "Older prompt",
- sourceMessageId: "msg-user-older",
- turnId: "turn-older",
- createdAtMs: 1,
- });
- app.transcript.upsert({
- id: "latest-user-cell",
- kind: "user",
- status: "succeeded",
- content: "Latest prompt",
- sourceMessageId: "msg-user-latest",
- turnId: "turn-latest",
- createdAtMs: 2,
- });
- app.transcript.upsert({
- id: "latest-assistant-cell",
- kind: "assistant",
- status: "succeeded",
- content: "Latest response",
- sourceMessageId: "msg-assistant-latest",
- turnId: "turn-latest",
- createdAtMs: 3,
- });
- await app.submit("/edit");
- await vi.waitFor(() =>
- expect(app.editor.getExpandedText()).toBe("Latest prompt"),
- );
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "chat",
- id: "chat",
- });
- const editingFrame = app.tui.render(100).join("\n");
- expect(editingFrame).toContain("Older prompt");
- expect(editingFrame).not.toContain("Latest response");
- const historyRefreshCount = vi.mocked(runtime.getMessages).mock.calls
- .length;
- app.editor.setText("Edited latest prompt");
- app.editor.handleInput("\r");
- await vi.waitFor(() =>
- expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
- );
- await vi.waitFor(() =>
- expect(vi.mocked(runtime.getMessages).mock.calls.length).toBeGreaterThan(
- historyRefreshCount,
- ),
- );
- expect(
- app.transcript
- .snapshot()
- .some(
- (cell) =>
- cell.content ===
- "Edited message submitted; regenerating from this point.",
- ),
- ).toBe(false);
- expect(runtime.editSessionMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- userMessageId: "msg-user-latest",
- content: "Edited latest prompt",
- }),
- );
- await app.stop();
- });
- it("restores the hidden latest turn when Edit is cancelled", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- {
- userMessageId: "msg-user-latest",
- assistantMessageId: "msg-assistant-latest",
- contentHead: "Latest prompt",
- timestamp: 2,
- fileChangeCount: 0,
- },
- ]);
- vi.mocked(runtime.listMessagePage).mockResolvedValue({
- messages: [
- {
- id: "msg-user-latest",
- role: "user",
- content: "Latest prompt",
- timestamp: 2,
- },
- ],
- hasMore: false,
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Seed edit session");
- app.transcript.upsert({
- id: "latest-user-cell",
- kind: "user",
- status: "succeeded",
- content: "Latest prompt",
- sourceMessageId: "msg-user-latest",
- turnId: "turn-latest",
- createdAtMs: 2,
- });
- app.transcript.upsert({
- id: "latest-assistant-cell",
- kind: "assistant",
- status: "succeeded",
- content: "Latest response restored on cancel",
- sourceMessageId: "msg-assistant-latest",
- turnId: "turn-latest",
- createdAtMs: 3,
- });
- await app.submit("/edit");
- await vi.waitFor(() =>
- expect(app.editor.getExpandedText()).toBe("Latest prompt"),
- );
- expect(app.tui.render(100).join("\n")).not.toContain(
- "Latest response restored on cancel",
- );
- terminal.input?.("\u001b");
- await vi.waitFor(() => expect(app.editor.getExpandedText()).toBe(""));
- expect(app.tui.render(100).join("\n")).toContain(
- "Latest response restored on cancel",
- );
- expect(runtime.editSessionMessage).not.toHaveBeenCalled();
- await app.stop();
- });
- it.each([
- { reference: "filePath", action: "cancel" },
- { reference: "assetId", action: "send" },
- { reference: "assetId", action: "delete" },
- { reference: "filePath", action: "undo" },
- { reference: "assetId", action: "add" },
- { reference: "filePath", action: "clear-restore" },
- { reference: "filePath", action: "cached" },
- ] as const)(
- "restores editable image chips after double Escape and retry ($reference / $action)",
- async ({ reference, action }) => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- {
- userMessageId: "msg-user-latest",
- assistantMessageId: "msg-assistant-latest",
- contentHead: "Latest prompt from shortcut",
- timestamp: 2,
- fileChangeCount: 0,
- },
- ]);
- vi.mocked(runtime.listMessagePage).mockResolvedValue({
- messages: [
- {
- id: "msg-user-latest",
- role: "user",
- content: "Latest prompt from shortcut",
- attachments: [
- {
- type: "image",
- fileName: "edit-reference.png",
- mimeType: "image/png",
- [reference]:
- reference === "filePath"
- ? "/workspace/edit-reference.png"
- : "asset-edit-image",
- },
- ],
- timestamp: 2,
- },
- ],
- hasMore: false,
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- resolveAttachment: async (path) => ({
- type: "image",
- filePath: path,
- fileName: path.endsWith("new.png") ? "new.png" : "edit-reference.png",
- mimeType: "image/png",
- sizeBytes: 123,
- }),
- });
- app.start();
- await app.ready;
- let restoredText = "Latest prompt from shortcut [Image #1] ";
- if (action === "cached") {
- terminal.input?.("\x1b[200~/workspace/edit-reference.png\x1b[201~");
- await vi.waitFor(() =>
- expect(app.editor.getText()).toContain("[Image #1]"),
- );
- app.editor.handleInput("Latest prompt from shortcut");
- restoredText = app.editor.getText();
- app.editor.handleInput("\r");
- await vi.waitFor(() =>
- expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
- );
- await vi.waitFor(() =>
- expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
- );
- } else {
- await app.submit("Seed edit session");
- }
- terminal.input?.("\u001b");
- terminal.input?.("\u001b");
- await vi.waitFor(() =>
- expect(app.editor.getExpandedText()).toBe(restoredText),
- );
- expect(runtime.listSessionInputSummaries).toHaveBeenCalledWith(
- "session-1",
- { limit: 100 },
- );
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "chat",
- id: "chat",
- });
- expect(stripAnsi(app.tui.render(100).join("\n"))).toContain("[Image #1]");
- vi.mocked(runtime.editSessionMessage).mockRejectedValueOnce(
- new Error("Temporary failure"),
- );
- app.editor.handleInput("\r");
- await vi.waitFor(() =>
- expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
- );
- await vi.waitFor(() =>
- expect(app.editor.getExpandedText()).toBe(restoredText),
- );
- expect(stripAnsi(app.tui.render(100).join("\n"))).toContain("[Image #1]");
- expect(runtime.editSessionMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- content: "Latest prompt from shortcut",
- attachments: [
- expect.objectContaining({
- fileName: "edit-reference.png",
- [reference]:
- reference === "filePath"
- ? "/workspace/edit-reference.png"
- : "asset-edit-image",
- }),
- ],
- }),
- );
- if (action === "delete" || action === "undo") {
- app.editor.handleInput("\x05");
- app.editor.handleInput("\x7f");
- await vi.waitFor(() =>
- expect(app.editor.getText()).not.toContain("[Image #1]"),
- );
- if (action === "undo") {
- app.editor.handleInput("\x1f");
- expect(app.editor.getText()).toContain("[Image #1]");
- }
- }
- if (action === "add") {
- terminal.input?.("\x1b[200~/workspace/new.png\x1b[201~");
- await vi.waitFor(() =>
- expect(app.editor.getText()).toContain("[Image #2]"),
- );
- expect(app.editor.captureDraft().attachmentPlaceholders).toHaveLength(
- 2,
- );
- }
- if (action === "clear-restore") {
- terminal.input?.("\x03");
- expect(app.editor.getText()).toBe("");
- terminal.input?.("\x1f");
- expect(app.editor.getText()).toContain("[Image #1]");
- }
- if (action === "cancel") {
- terminal.input?.("\u001b");
- } else {
- app.editor.handleInput("\r");
- await vi.waitFor(() =>
- expect(runtime.editSessionMessage).toHaveBeenCalledTimes(2),
- );
- const sent = vi.mocked(runtime.editSessionMessage).mock.calls[1]?.[0];
- expect(sent?.content).toBe("Latest prompt from shortcut");
- expect(sent?.attachments ?? []).toHaveLength(
- action === "delete" ? 0 : action === "add" ? 2 : 1,
- );
- if (action !== "delete")
- expect(sent?.attachments?.[0]?.fileName).toBe("edit-reference.png");
- }
- await vi.waitFor(() =>
- expect(stripAnsi(app.tui.render(100).join("\n"))).not.toContain(
- "[Image #1]",
- ),
- );
- await app.stop();
- },
- );
- it("edits the latest committed user turn through the desktop-aligned mutation contract", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- {
- userMessageId: "msg-user-v1-target",
- assistantMessageId: "msg-assistant-v1-target",
- contentHead: "Original prompt head",
- timestamp: 1_700_000_000_000,
- fileChangeCount: 1,
- },
- ]);
- vi.mocked(runtime.listMessagePage).mockResolvedValue({
- messages: [
- {
- id: "msg-user-v1-target",
- role: "user",
- content: "Original complete prompt",
- attachments: [
- {
- type: "file",
- fileName: "spec.md",
- mimeType: "text/markdown",
- sizeBytes: 42,
- filePath: "/workspace/spec.md",
- },
- ],
- timestamp: 1_700_000_000_000,
- },
- ],
- hasMore: false,
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Seed edit session");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
- );
- await app.submit("/edit");
- await vi.waitFor(() =>
- expect(app.editor.getExpandedText()).toBe(
- "Original complete prompt [File #1] ",
- ),
- );
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "chat",
- id: "chat",
- });
- app.editor.setText("Updated prompt");
- app.editor.handleInput("\r");
- await vi.waitFor(() =>
- expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
- );
- expect(runtime.editSessionMessage).toHaveBeenCalledWith({
- sessionId: "session-1",
- userMessageId: "msg-user-v1-target",
- clientRequestId: expect.stringMatching(/^tui-edit_/u),
- content: "Updated prompt",
- attachments: [
- {
- type: "file",
- fileName: "spec.md",
- mimeType: "text/markdown",
- sizeBytes: 42,
- filePath: "/workspace/spec.md",
- },
- ],
- rewindTurnDiff: true,
- });
- await app.stop();
- });
- it("keeps hidden chat context out of the editor and restores it for Edit transport", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const transportContent = [
- "<user-provided-context>",
- "Referenced context",
- "</user-provided-context>",
- "",
- "Original visible prompt",
- ].join("\n");
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- {
- userMessageId: "msg-user-v1-context",
- assistantMessageId: "msg-assistant-v1-context",
- contentHead: "Original visible prompt",
- timestamp: 1_700_000_000_000,
- fileChangeCount: 0,
- },
- ]);
- vi.mocked(runtime.listMessagePage).mockResolvedValue({
- messages: [
- {
- id: "msg-user-v1-context",
- role: "user",
- content: transportContent,
- timestamp: 1_700_000_000_000,
- },
- ],
- hasMore: false,
- });
- vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Seed edit session");
- await app.submit("/edit");
- await vi.waitFor(() =>
- expect(app.editor.getExpandedText()).toBe("Original visible prompt"),
- );
- expect(app.editor.getExpandedText()).not.toContain("user-provided-context");
- app.editor.setText("Updated visible prompt");
- app.editor.handleInput("\r");
- await vi.waitFor(() =>
- expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
- );
- expect(runtime.editSessionMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- content: [
- "<user-provided-context>",
- "Referenced context",
- "</user-provided-context>",
- "",
- "Updated visible prompt",
- ].join("\n"),
- }),
- );
- await app.stop();
- });
- it("preserves hidden context and attachments when Edit recovery requires a new message", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const transportContent = [
- "<mavis-chat-context>",
- "Referenced context",
- "</mavis-chat-context>",
- "",
- "Original visible prompt",
- ].join("\n");
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- {
- userMessageId: "msg-user-v1-recovery",
- assistantMessageId: "msg-assistant-v1-recovery",
- contentHead: "Original visible prompt",
- timestamp: 1_700_000_000_000,
- fileChangeCount: 0,
- },
- ]);
- vi.mocked(runtime.listMessagePage).mockResolvedValue({
- messages: [
- {
- id: "msg-user-v1-recovery",
- role: "user",
- content: transportContent,
- attachments: [
- {
- type: "file",
- fileName: "context.md",
- mimeType: "text/markdown",
- sizeBytes: 42,
- assetId: "asset-context-md",
- },
- ],
- timestamp: 1_700_000_000_000,
- },
- ],
- hasMore: false,
- });
- vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
- vi.mocked(runtime.editSessionMessage).mockRejectedValueOnce(
- Object.assign(new Error("history already rewound"), {
- key: "EDIT_RESTART_NEEDS_RESUBMIT",
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Seed edit session");
- const sendCountBeforeEdit = vi.mocked(runtime.sendMessage).mock.calls
- .length;
- await app.submit("/edit");
- await vi.waitFor(() =>
- expect(app.editor.getExpandedText()).toBe(
- "Original visible prompt [File #1] ",
- ),
- );
- app.editor.setText("/help should remain message text");
- app.editor.handleInput("\r");
- await vi.waitFor(() =>
- expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
- );
- await vi.waitFor(() =>
- expect(app.editor.getExpandedText()).toBe(
- "/help should remain message text [File #1] ",
- ),
- );
- expect(app.editor.getExpandedText()).not.toContain("mavis-chat-context");
- expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
- let releaseAdmission!: () => void;
- vi.mocked(runtime.getAccountStatus).mockImplementationOnce(
- async () =>
- await new Promise((resolve) => {
- releaseAdmission = () =>
- resolve({
- status: "ready",
- defaultModel: "minimax/MiniMax-M2.7",
- providerId: "minimax",
- modelId: "MiniMax-M2.7",
- authMode: "managed-login",
- managedTokenPresent: true,
- warnings: [],
- });
- }),
- );
- app.editor.handleInput("\r");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().activeTurnId).toBeDefined(),
- );
- terminal.input?.("\u001b");
- releaseAdmission();
- await vi.waitFor(() =>
- expect(app.editor.getExpandedText()).toBe(
- "/help should remain message text [File #1] ",
- ),
- );
- expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
- app.editor.handleInput("\r");
- await vi.waitFor(() =>
- expect(runtime.sendMessage).toHaveBeenCalledTimes(
- sendCountBeforeEdit + 1,
- ),
- );
- expect(vi.mocked(runtime.sendMessage).mock.calls.at(-1)?.[0]).toMatchObject(
- {
- content: [
- "<mavis-chat-context>",
- "Referenced context",
- "</mavis-chat-context>",
- "",
- "/help should remain message text",
- ].join("\n"),
- attachments: [
- {
- meta: {
- attachmentType: "file",
- fileName: "context.md",
- mimeType: "text/markdown",
- sizeBytes: 42,
- },
- local: { assetId: "asset-context-md" },
- },
- ],
- },
- );
- expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1);
- expect(
- app.transcript
- .snapshot()
- .filter((cell) => cell.kind === "user")
- .map((cell) => cell.content)
- .join("\n"),
- ).toContain("/help should remain message text");
- expect(
- app.transcript
- .snapshot()
- .filter((cell) => cell.kind === "user")
- .map((cell) => cell.content)
- .join("\n"),
- ).not.toContain("mavis-chat-context");
- await app.stop();
- });
- it("allows an attachment-only committed message to enter Edit and gain a body", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- {
- userMessageId: "msg-user-v1-attachment-only",
- assistantMessageId: "msg-assistant-v1-attachment-only",
- timestamp: 1_700_000_000_000,
- fileChangeCount: 0,
- },
- ]);
- vi.mocked(runtime.listMessagePage).mockResolvedValue({
- messages: [
- {
- id: "msg-user-v1-attachment-only",
- role: "user",
- content: "",
- attachments: [
- {
- type: "image",
- fileName: "reference.png",
- mimeType: "image/png",
- filePath: "/workspace/reference.png",
- },
- ],
- timestamp: 1_700_000_000_000,
- },
- ],
- hasMore: false,
- });
- vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Seed edit session");
- const sendCountBeforeEdit = vi.mocked(runtime.sendMessage).mock.calls
- .length;
- await app.submit("/edit");
- await vi.waitFor(() =>
- expect(app.tui.render(100).join("\n")).toContain(
- "Editing the selected message",
- ),
- );
- expect(app.editor.getExpandedText()).toBe("[Image #1] ");
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "chat",
- id: "chat",
- });
- app.editor.setText("Describe this reference");
- app.editor.handleInput("\r");
- await vi.waitFor(() =>
- expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
- );
- expect(runtime.editSessionMessage).toHaveBeenCalledWith({
- sessionId: "session-1",
- userMessageId: "msg-user-v1-attachment-only",
- clientRequestId: expect.stringMatching(/^tui-edit_/u),
- content: "Describe this reference",
- attachments: [
- {
- type: "image",
- fileName: "reference.png",
- mimeType: "image/png",
- filePath: "/workspace/reference.png",
- },
- ],
- rewindTurnDiff: true,
- });
- expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
- await app.stop();
- });
- it("keeps a second composer submission while an edit request is still in flight", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- {
- userMessageId: "msg-user-v1-target",
- assistantMessageId: "msg-assistant-v1-target",
- contentHead: "Original prompt",
- timestamp: 1,
- fileChangeCount: 0,
- },
- ]);
- vi.mocked(runtime.listMessagePage).mockResolvedValue({
- messages: [
- {
- id: "msg-user-v1-target",
- role: "user",
- content: "Original prompt",
- timestamp: 1,
- },
- ],
- hasMore: false,
- });
- vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
- let resolveEdit!: (value: {
- rewound: boolean;
- turnId: string;
- userMessageId: string;
- }) => void;
- vi.mocked(runtime.editSessionMessage).mockImplementation(
- () =>
- new Promise((resolve) => {
- resolveEdit = resolve;
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Seed edit session");
- const sendCountBeforeEdit = vi.mocked(runtime.sendMessage).mock.calls
- .length;
- await app.submit("/edit");
- await vi.waitFor(() =>
- expect(app.editor.getText()).toBe("Original prompt"),
- );
- app.editor.setText("First edited prompt");
- app.editor.handleInput("\r");
- await vi.waitFor(() =>
- expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
- );
- app.editor.setText("Keep this until edit settles");
- app.editor.handleInput("\r");
- await vi.waitFor(() =>
- expect(app.editor.getText()).toBe("Keep this until edit settles"),
- );
- expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
- resolveEdit({
- rewound: true,
- turnId: "turn-edit-1",
- userMessageId: "msg-user-v1-edited",
- });
- await app.stop();
- });
- it("preserves the edit and retries the same operation when submission fails after rewind", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- {
- userMessageId: "msg-user-v1-target",
- assistantMessageId: "msg-assistant-v1-target",
- contentHead: "Original prompt",
- timestamp: 1,
- fileChangeCount: 0,
- },
- ]);
- vi.mocked(runtime.listMessagePage).mockResolvedValue({
- messages: [
- {
- id: "msg-user-v1-target",
- role: "user",
- content: "Original prompt",
- timestamp: 1,
- },
- ],
- hasMore: false,
- });
- vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
- vi.mocked(runtime.editSessionMessage)
- .mockRejectedValueOnce(
- Object.assign(new Error("submit failed"), {
- key: "EDIT_SUBMIT_FAILED_AFTER_REWIND",
- }),
- )
- .mockResolvedValueOnce({
- rewound: true,
- turnId: "turn-edit-retry",
- userMessageId: "msg-user-v1-edited",
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Seed edit session");
- await app.submit("/edit");
- await vi.waitFor(() =>
- expect(app.editor.getText()).toBe("Original prompt"),
- );
- app.editor.setText("Preserve this edited prompt");
- app.editor.handleInput("\r");
- await vi.waitFor(() =>
- expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
- );
- await vi.waitFor(() =>
- expect(app.editor.getText()).toBe("Preserve this edited prompt"),
- );
- expect(
- app.transcript
- .snapshot()
- .some((cell) => cell.content.includes("History was rewound")),
- ).toBe(true);
- const firstOperationId = vi.mocked(runtime.editSessionMessage).mock
- .calls[0]?.[0].clientRequestId;
- const sendCount = vi.mocked(runtime.sendMessage).mock.calls.length;
- app.editor.handleInput("\r");
- await vi.waitFor(() =>
- expect(runtime.editSessionMessage).toHaveBeenCalledTimes(2),
- );
- expect(runtime.editSessionMessage).toHaveBeenLastCalledWith(
- expect.objectContaining({ clientRequestId: firstOperationId }),
- );
- expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCount);
- await app.stop();
- });
- it("cancels /rewind preview and ignores duplicate scope submission", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
- ]);
- vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
- turns: [
- {
- turnId: "turn-1",
- files: [{ filePath: "a.ts", action: "modified", skipped: false }],
- },
- ],
- });
- let resolveRewind!: (value: { rewound: boolean }) => void;
- vi.mocked(runtime.rewindSession).mockImplementation(
- () =>
- new Promise((resolve) => {
- resolveRewind = resolve;
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Seed rewind session");
- await app.submit("/rewind");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:history",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:rewind-preview",
- }),
- );
- terminal.input?.("\u001b");
- expect(runtime.rewindSession).not.toHaveBeenCalled();
- await app.submit("/rewind");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:history",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:rewind-preview",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:scope",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:rewind-confirm",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
- );
- terminal.input?.("\u001b");
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:rewind-confirm",
- });
- resolveRewind({ rewound: true });
- await app.stop();
- });
- it("invalidates /rewind when the active session switches before mutation", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 0 },
- ]);
- vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Seed rewind session");
- await app.submit("/rewind");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:history",
- }),
- );
- const other = {
- sessionId: "session-other",
- title: "Other",
- workspaceDir: "/workspace",
- };
- vi.mocked(runtime.getSession).mockResolvedValue(other);
- await app.openSession(other.sessionId);
- terminal.input?.("\r");
- await new Promise((resolve) => setTimeout(resolve, 20));
- expect(runtime.getSessionRewindPreview).not.toHaveBeenCalled();
- expect(runtime.rewindSession).not.toHaveBeenCalled();
- expect(app.controller.snapshot().session?.sessionId).toBe(other.sessionId);
- await app.stop();
- });
- it("retries a failed file rewind with the same operation id", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
- ]);
- vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
- turns: [
- {
- turnId: "turn-1",
- files: [{ filePath: "a.ts", action: "modified", skipped: false }],
- },
- ],
- });
- vi.mocked(runtime.rewindSession)
- .mockRejectedValueOnce(new Error("temporary conflict"))
- .mockResolvedValueOnce({
- rewound: true,
- turnDiffRewind: { status: "rewound", revertedTurnIds: ["turn-1"] },
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Seed rewind session");
- await app.submit("/rewind");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:history",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:rewind-preview",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:scope",
- }),
- );
- terminal.input?.("\u001b[B");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:rewind-confirm",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
- );
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:rewind-confirm",
- });
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.rewindSession).toHaveBeenCalledTimes(2),
- );
- const ids = vi
- .mocked(runtime.rewindSession)
- .mock.calls.map(([input]) => input.clientRequestId);
- expect(ids[0]).toBe(ids[1]);
- await app.stop();
- });
- it.each([
- [
- "terminal busy failure",
- "CONVERSATION_MUTATION_BUSY",
- "Stop the running response and try again.",
- false,
- ],
- [
- "pending display publication",
- "REWIND_DISPLAY_COMMIT_FAILED",
- "retry with the same operation id",
- true,
- ],
- ] as const)(
- "keeps a failed conversation rewind open and retries %s with the correct operation id",
- async (_label, errorCode, expectedCopy, reuseOperationId) => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 0 },
- ]);
- vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
- turns: [],
- });
- vi.mocked(runtime.rewindSession)
- .mockRejectedValueOnce(
- Object.assign(new Error("rewind failed"), { key: errorCode }),
- )
- .mockResolvedValueOnce({ rewound: true });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Seed rewind session");
- await app.submit("/rewind");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:history",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:rewind-preview",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:scope",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:rewind-confirm",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
- );
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:rewind-confirm",
- });
- expect(renderTerminalViewport(app, terminal)).toContain(expectedCopy);
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.rewindSession).toHaveBeenCalledTimes(2),
- );
- const ids = vi
- .mocked(runtime.rewindSession)
- .mock.calls.map(([input]) => input.clientRequestId);
- if (reuseOperationId) expect(ids[0]).toBe(ids[1]);
- else expect(ids[0]).not.toBe(ids[1]);
- await app.stop();
- },
- );
- it.each([
- [
- "failed-after-rewind",
- {
- status: "failed-after-rewind",
- revertedTurnIds: ["turn-1"],
- errorCode: "conflict",
- },
- ],
- ["empty-reverted-ids", { status: "rewound", revertedTurnIds: [] }],
- [
- "unknown-status",
- { status: "future-runtime-status", revertedTurnIds: ["turn-1"] },
- ],
- ] as const)(
- "does not report %s as a successful file rewind",
- async (_label, turnDiffRewind) => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
- ]);
- vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
- turns: [
- {
- turnId: "turn-1",
- files: [{ filePath: "a.ts", action: "modified", skipped: false }],
- },
- ],
- });
- vi.mocked(runtime.rewindSession).mockResolvedValue({
- rewound: true,
- turnDiffRewind,
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Seed rewind session");
- await app.submit("/rewind");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:history",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:rewind-preview",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:scope",
- }),
- );
- terminal.input?.("\u001b[B");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:rewind-confirm",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
- );
- await vi.waitFor(() =>
- expect(app.transcript.snapshot().at(-1)?.content).toMatch(
- /did not complete|No file changes/,
- ),
- );
- expect(app.transcript.snapshot().at(-1)?.content).not.toContain(
- "Files rewound; conversation history was kept.",
- );
- await app.stop();
- },
- );
- it.each([
- [
- "MESSAGE_BOUNDARY_INVALID",
- "This conversation point is no longer available.",
- ],
- [
- "CONVERSATION_MUTATION_REQUEST_CONFLICT",
- "This action was already submitted or became stale.",
- ],
- ["CONVERSATION_MUTATION_BUSY", "Stop the running response and try again."],
- ] as const)(
- "maps rewind Runtime error %s to stable copy",
- async (code, expected) => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
- ]);
- vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
- turns: [
- {
- turnId: "turn-1",
- files: [{ filePath: "a.ts", action: "modified", skipped: false }],
- },
- ],
- });
- vi.mocked(runtime.rewindSession).mockRejectedValue(
- Object.assign(new Error("raw prompt token=secret"), { key: code }),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Seed rewind session");
- await app.submit("/rewind");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:history",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:rewind-preview",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:scope",
- }),
- );
- terminal.input?.("\u001b[B");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:rewind-confirm",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(
- app.transcript.snapshot().some((cell) => cell.content === expected),
- ),
- );
- expect(
- app.transcript
- .snapshot()
- .some((cell) => cell.content.includes("raw prompt token")),
- ).toBe(false);
- await app.stop();
- },
- );
- it("reports refresh failure without unhandled rejection after conversation-and-files rewind", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
- ]);
- vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
- turns: [
- {
- turnId: "turn-1",
- files: [{ filePath: "a.ts", action: "modified", skipped: false }],
- },
- ],
- });
- vi.mocked(runtime.rewindSession).mockResolvedValue({
- rewound: true,
- turnDiffRewind: { status: "rewound", revertedTurnIds: ["turn-1"] },
- });
- vi.mocked(runtime.getMessages).mockRejectedValueOnce(
- new Error("refresh unavailable"),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Seed rewind session");
- await app.submit("/rewind");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:history",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:rewind-preview",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:scope",
- }),
- );
- terminal.input?.("\u001b[B");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:rewind-confirm",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(
- app.transcript
- .snapshot()
- .some((cell) => cell.content.includes("could not be refreshed")),
- ),
- );
- await app.stop();
- });
- it("does not apply a pending rewind refresh result after switching sessions", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
- { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
- ]);
- vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
- turns: [
- {
- turnId: "turn-1",
- files: [{ filePath: "a.ts", action: "modified", skipped: false }],
- },
- ],
- });
- vi.mocked(runtime.rewindSession).mockResolvedValue({
- rewound: true,
- turnDiffRewind: { status: "rewound", revertedTurnIds: ["turn-1"] },
- });
- let resolveRefresh!: (messages: readonly TuiMessage[]) => void;
- const refreshPromise = new Promise<readonly TuiMessage[]>((resolve) => {
- resolveRefresh = resolve;
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Seed rewind session");
- vi.mocked(runtime.getMessages).mockImplementationOnce(() => refreshPromise);
- await app.submit("/rewind");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:history",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:rewind-preview",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:scope",
- }),
- );
- terminal.input?.("\u001b[B");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "session-mutation:rewind-confirm",
- }),
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
- );
- const other = {
- sessionId: "session-other",
- title: "Other",
- workspaceDir: "/workspace",
- };
- vi.mocked(runtime.getSession).mockResolvedValue(other);
- vi.mocked(runtime.getMessages).mockResolvedValue([]);
- const open = app.openSession(other.sessionId);
- resolveRefresh([
- {
- id: "stale-message",
- role: "assistant",
- content: "stale",
- timestamp: 3,
- },
- ]);
- await open;
- expect(app.controller.snapshot().session?.sessionId).toBe(other.sessionId);
- expect(
- app.transcript
- .snapshot()
- .some((cell) => cell.content.includes("Files rewound")),
- ).toBe(false);
- await app.stop();
- });
- it("redirects a hidden task child to its parent before rendering", async () => {
- const runtime = createRuntime();
- const parent = {
- sessionId: "session-parent",
- title: "CLI integration",
- workspaceDir: "/workspace",
- };
- const child = {
- sessionId: "session-child",
- parentSessionId: parent.sessionId,
- title: "Review recent CLI changes",
- workspaceDir: "/workspace",
- sessionType: "branch",
- sessionKind: "task",
- visibility: "hidden",
- purpose: "local-task:turn-1:tool-1",
- agentName: "verifier",
- };
- vi.mocked(runtime.listSessions).mockResolvedValue([parent]);
- vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
- sessionId === child.sessionId ? child : parent,
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- await app.openSession(child.sessionId);
- expect(runtime.getSession).toHaveBeenLastCalledWith(parent.sessionId);
- expect(app.controller.snapshot().session?.sessionId).toBe(parent.sessionId);
- expect(app.tui.render(140).join("\n")).not.toContain("Sub: verifier");
- expect(app.transcript.snapshot().at(-1)?.content).toBe(
- "Sub-agent Sessions are internal. Opened the parent Session instead.",
- );
- await app.stop();
- });
- it("shows compact Agent Team status without exposing child details or commands", async () => {
- const terminal = new FakeTerminal();
- terminal.rows = 24;
- const runtime = createRuntime();
- const parent = {
- sessionId: "session-parent",
- title: "Agent Team parent",
- workspaceDir: "/workspace",
- };
- const child = {
- sessionId: "session-child",
- parentSessionId: parent.sessionId,
- title: "Verify the TUI",
- workspaceDir: "/workspace",
- sessionType: "branch" as const,
- sessionKind: "task",
- visibility: "hidden" as const,
- purpose: "local-task:turn-1:tool-1",
- agentName: "verifier",
- status: "finished",
- };
- vi.mocked(runtime.listSessions).mockResolvedValue([parent]);
- vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
- sessionId === child.sessionId ? child : parent,
- );
- vi.mocked(runtime.getDelegationSnapshot).mockResolvedValue({
- schemaVersion: 1,
- rootSessionId: parent.sessionId,
- members: [
- {
- sessionId: child.sessionId,
- parentSessionId: parent.sessionId,
- agentName: child.agentName,
- task: child.title,
- status: "running",
- createdAtMs: 100,
- updatedAtMs: 200,
- },
- ],
- });
- vi.mocked(runtime.getMessages).mockImplementation(async (sessionId) =>
- sessionId === child.sessionId
- ? [
- {
- id: "child-answer",
- turnId: "turn-child",
- role: "assistant",
- content: "Child verification result",
- timestamp: 200,
- },
- ]
- : [],
- );
- vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
- schemaVersion: 1,
- sessionId,
- state: sessionId === child.sessionId ? "running" : "idle",
- ...(sessionId === child.sessionId ? { turnId: "turn-child" } : {}),
- actions: { steer: false },
- }));
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- await app.openSession(parent.sessionId);
- app.start();
- const summary = app.tui.render(100).join("\n");
- expect(summary).toContain("Tasks · 1 agent active · /tasks details");
- expect(summary).not.toContain("verifier");
- expect(summary).not.toContain("/agents");
- expect(
- app.transcript.snapshot().some((cell) => cell.kind === "agent-team"),
- ).toBe(false);
- await app.submit("/agents");
- await app.submit("/team");
- expect(app.controller.snapshot().session?.sessionId).toBe(parent.sessionId);
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.interaction.isActive()).toBe(false);
- expect(app.tui.render(100).join("\n")).not.toContain(
- "Child verification result",
- );
- expect(
- vi
- .mocked(runtime.sendMessage)
- .mock.calls.map(([request]) => request.content),
- ).toEqual(["/agents", "/team"]);
- await app.stop();
- });
- it("allocates enough standard-terminal space for ten session choices", async () => {
- const terminal = new FakeTerminal();
- terminal.rows = 24;
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionPage).mockResolvedValue({
- sessions: Array.from({ length: 12 }, (_, index) => ({
- sessionId: `session-${String(index + 1).padStart(2, "0")}`,
- title: `Session ${String(index + 1).padStart(2, "0")}`,
- workspaceDir: "/workspace",
- updatedAt: 12 - index,
- })),
- hasMore: false,
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.submit("/sessions");
- const lines = app.interaction.current()?.render(80) ?? [];
- const rendered = lines.join("\n");
- expect(lines.length).toBeLessThanOrEqual(terminal.rows);
- expect(rendered).toContain("Session 10");
- expect(rendered).not.toContain("Session 11");
- });
- it("switches, restores, and resumes archived Desktop sessions from the session manager", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let archived = true;
- const activeSession = {
- sessionId: "session-active",
- title: "Active session",
- workspaceDir: "/workspace",
- updatedAt: 200,
- };
- const archivedSession = {
- sessionId: "session-archived",
- title: "Archived session",
- workspaceDir: "/workspace",
- updatedAt: 100,
- archived: true,
- };
- vi.mocked(runtime.listSessions).mockResolvedValue([activeSession]);
- vi.mocked(runtime.listSessionPage).mockResolvedValue({
- sessions: [activeSession, archivedSession],
- hasMore: false,
- });
- vi.mocked(runtime.getSession).mockImplementation(async (sessionId) => ({
- ...(sessionId === archivedSession.sessionId
- ? archivedSession
- : activeSession),
- archived: sessionId === archivedSession.sessionId ? archived : false,
- }));
- vi.mocked(runtime.archiveSession).mockImplementation(
- async (_sessionId, value) => {
- archived = value;
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/sessions");
- expect(runtime.listSessionPage).toHaveBeenCalledWith({
- allAgents: true,
- workspaceDir: "/workspace",
- limit: 50,
- includeArchived: true,
- includeHidden: true,
- });
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.interaction.isActive()).toBe(true);
- terminal.input?.("\t");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.archiveSession).toHaveBeenCalledWith(
- "session-archived",
- false,
- ),
- );
- await vi.waitFor(() =>
- expect(runtime.getMessages).toHaveBeenCalledWith("session-archived"),
- );
- expect(app.getSurface()).toBe("conversation");
- expect(app.controller.snapshot().session?.sessionId).toBe(
- "session-archived",
- );
- expect(app.tui.hasOverlay()).toBe(false);
- await app.stop();
- });
- it("uses the resume alias to search every Desktop session page", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionPage)
- .mockResolvedValueOnce({
- sessions: [
- {
- sessionId: "session-page-1",
- title: "First page",
- workspaceDir: "/workspace",
- updatedAt: 200,
- },
- ],
- hasMore: true,
- nextCursor: "session-page-1",
- })
- .mockResolvedValueOnce({
- sessions: [
- {
- sessionId: "session-page-2",
- title: "Second page",
- workspaceDir: "/workspace",
- updatedAt: 100,
- },
- ],
- hasMore: false,
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/resume Second page");
- await vi.waitFor(() =>
- expect(runtime.listSessionPage).toHaveBeenNthCalledWith(2, {
- allAgents: true,
- workspaceDir: "/workspace",
- limit: 50,
- cursor: "session-page-1",
- includeArchived: true,
- includeHidden: true,
- }),
- );
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.interaction.isActive()).toBe(true);
- expect(app.interaction.current()?.render(100).join("\n")).toContain(
- "Second page",
- );
- await app.stop();
- });
- it("queries the current workspace first and reloads the global catalog on Ctrl+A", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessionPage).mockImplementation(
- async (input = {}) => {
- if (input.cursor === "all-page-2") {
- return {
- sessions: [
- {
- sessionId: "session-other-older",
- title: "Older session elsewhere",
- workspaceDir: "/other-workspace",
- updatedAt: 50,
- },
- ],
- hasMore: false,
- };
- }
- return input.workspaceDir
- ? {
- sessions: [
- {
- sessionId: "session-workspace-old",
- title: "Older workspace session",
- workspaceDir: "/workspace",
- updatedAt: 100,
- },
- ],
- hasMore: false,
- }
- : {
- sessions: [
- {
- sessionId: "session-other-new",
- title: "Newer session elsewhere",
- workspaceDir: "/other-workspace",
- updatedAt: 200,
- },
- {
- sessionId: "session-workspace-old",
- title: "Older workspace session",
- workspaceDir: "/workspace",
- updatedAt: 100,
- },
- ],
- hasMore: true,
- nextCursor: "all-page-2",
- };
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/sessions");
- expect(runtime.listSessionPage).toHaveBeenNthCalledWith(1, {
- allAgents: true,
- workspaceDir: "/workspace",
- limit: 50,
- includeArchived: true,
- includeHidden: true,
- });
- expect(app.interaction.current()?.render(100).join("\n")).toContain(
- "Older workspace session",
- );
- terminal.input?.("\x01");
- await vi.waitFor(() =>
- expect(runtime.listSessionPage).toHaveBeenNthCalledWith(2, {
- allAgents: true,
- limit: 50,
- includeArchived: true,
- includeHidden: true,
- }),
- );
- await vi.waitFor(() =>
- expect(app.interaction.current()?.render(100).join("\n")).toContain(
- "Newer session elsewhere",
- ),
- );
- expect(app.interaction.current()?.render(100).join("\n")).toContain(
- "All sessions",
- );
- terminal.input?.("\x0c");
- await vi.waitFor(() =>
- expect(runtime.listSessionPage).toHaveBeenNthCalledWith(3, {
- allAgents: true,
- limit: 50,
- cursor: "all-page-2",
- includeArchived: true,
- includeHidden: true,
- }),
- );
- await vi.waitFor(() =>
- expect(app.interaction.current()?.render(100).join("\n")).toContain(
- "Older session elsewhere",
- ),
- );
- await app.stop();
- });
- it("shows account status and resolves pending permission and questionnaire decisions", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-existing",
- title: "Existing session",
- workspaceDir: "/workspace",
- },
- ]);
- vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
- {
- requestId: "permission-1",
- sessionId: "session-existing",
- agentName: "mavis",
- toolName: "bash",
- reason: "Run tests",
- allowAlwaysSupported: true,
- },
- ]);
- vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
- id: "question-1",
- title: "Choose",
- steps: [
- {
- id: "step-1",
- question: "Proceed?",
- selectionMode: "single",
- options: [
- { id: "yes", label: "Yes" },
- { id: "no", label: "No" },
- ],
- },
- ],
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- await app.submit("/resume session-existing");
- expect(app.transcript.snapshot()).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ kind: "permission", status: "blocked" }),
- expect.objectContaining({ kind: "question", status: "blocked" }),
- ]),
- );
- expect(app.transcript.get("permission:permission-1")).toMatchObject({
- title: "bash",
- content: "Run tests",
- });
- expect(
- app.transcript.get("permission:permission-1")?.content,
- ).not.toContain("decision panel");
- expect(app.transcript.get("permission:permission-1")?.content).not.toMatch(
- /\/(?:allow|always|deny)\b/u,
- );
- expect(app.transcript.get("question:question-1")?.content).toBe("");
- await app.submit("/q1 1");
- expect(runtime.replyQuestionnaire).not.toHaveBeenCalled();
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.interaction.isActive()).toBe(true);
- expect(terminal.mouseTracking).toBe(false);
- await app.submit("/allow");
- await app.submit("/q1 1");
- await app.submit("/status");
- expect(runtime.replyPermission).toHaveBeenCalledWith(
- "mavis",
- "permission-1",
- "allowOnce",
- );
- expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
- "mavis",
- "question-1",
- [
- {
- stepId: "step-1",
- selectedOptionIds: ["yes"],
- selectedOther: false,
- },
- ],
- );
- expect(terminal.mouseTracking).toBe(false);
- expect(app.transcript.get("question:question-1")).toMatchObject({
- status: "resolved",
- title: "Answers sent",
- content: "Proceed? Yes",
- });
- expect(app.interaction.current()).toBeDefined();
- expect(app.tui.render(80).join("\n")).toContain("MCode status");
- expect(app.transcript.snapshot()).not.toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- kind: "inspection",
- inspection: expect.objectContaining({
- visualization: { kind: "status" },
- }),
- }),
- ]),
- );
- });
- it("does not let a stale permission response hide a newer decision surface", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-race",
- title: "Decision race",
- workspaceDir: "/workspace",
- },
- ]);
- const firstPermission = {
- requestId: "permission-first",
- sessionId: "session-race",
- agentName: "mavis",
- toolName: "bash",
- reason: "First request",
- allowAlwaysSupported: true,
- };
- const secondPermission = {
- requestId: "permission-second",
- sessionId: "session-race",
- agentName: "mavis",
- toolName: "write_file",
- reason: "Newer request",
- allowAlwaysSupported: false,
- };
- vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
- firstPermission,
- ]);
- let finishReply: ((value: boolean) => void) | undefined;
- vi.mocked(runtime.replyPermission).mockImplementation(
- async () =>
- await new Promise<boolean>((resolve) => {
- finishReply = resolve;
- }),
- );
- let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
- vi.mocked(runtime.watchEvents).mockImplementation(
- async function* watchEvents(signal) {
- const event = await new Promise<TuiRuntimeEvent | undefined>(
- (resolve) => {
- emitEvent = resolve;
- signal.addEventListener("abort", () => resolve(undefined), {
- once: true,
- });
- },
- );
- if (event) yield event;
- await new Promise<void>((resolve) => {
- signal.addEventListener("abort", resolve, { once: true });
- });
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/resume session-race");
- const resolving = app.submit("/allow");
- await vi.waitFor(() => expect(runtime.replyPermission).toHaveBeenCalled());
- await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
- emitEvent?.(
- runtimeEvent({
- type: "permission.ask",
- timestamp: Date.now(),
- source: "test",
- payload: secondPermission,
- }),
- );
- await vi.waitFor(() =>
- expect(app.tui.render(80).join("\n")).toContain("Newer request"),
- );
- finishReply?.(true);
- await resolving;
- const rendered = app.tui.render(80).join("\n");
- expect(rendered).toContain("Write file");
- expect(rendered).toContain("Newer request");
- expect(runtime.replyPermission).toHaveBeenCalledTimes(1);
- await app.stop();
- });
- it("closes a permission that another surface resolved before the reply arrived", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const permission = {
- requestId: "permission-stale",
- sessionId: "session-permission-stale",
- agentName: "mavis",
- toolName: "bash",
- reason: "Run tests",
- allowAlwaysSupported: true,
- };
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-permission-stale",
- title: "Permission race",
- workspaceDir: "/workspace",
- },
- ]);
- vi.mocked(runtime.listPendingPermissions)
- .mockResolvedValueOnce([permission])
- .mockResolvedValue([]);
- vi.mocked(runtime.replyPermission).mockResolvedValue(false);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- await app.submit("/resume session-permission-stale");
- await app.submit("/allow");
- expect(app.transcript.get("permission:permission-stale")).toMatchObject({
- status: "resolved",
- detail: "Resolved on another surface.",
- });
- expect(app.interaction.isActive()).toBe(false);
- });
- it("keeps an option-only questionnaire pending after an invalid slash answer", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-questionnaire",
- title: "Questionnaire session",
- workspaceDir: "/workspace",
- },
- ]);
- vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
- id: "question-options-only",
- title: "Choose",
- steps: [
- {
- id: "channel",
- question: "Choose a release channel",
- selectionMode: "single",
- options: [
- { id: "preview", label: "Preview" },
- { id: "stable", label: "Stable" },
- ],
- allowOther: false,
- },
- ],
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- await app.submit("/resume session-questionnaire");
- await app.submit("/q1 nightly");
- expect(runtime.replyQuestionnaire).not.toHaveBeenCalled();
- expect(app.transcript.get("question:question-options-only")).toMatchObject({
- status: "blocked",
- });
- expect(app.transcript.snapshot().at(-1)).toMatchObject({
- kind: "warning",
- content:
- "/q1 accepts only listed options. Use an option number, ID, or label.",
- });
- await app.submit("/q1 1");
- expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
- "mavis",
- "question-options-only",
- [
- {
- stepId: "channel",
- selectedOptionIds: ["preview"],
- selectedOther: false,
- },
- ],
- );
- });
- it("shows the first AskUser answer immediately while later questions remain pending", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-multi-question",
- title: "Multi question",
- workspaceDir: "/workspace",
- },
- ]);
- vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
- id: "question-multi-step",
- title: "Preferences",
- steps: [
- {
- id: "animal",
- question: "Favorite animal?",
- selectionMode: "single",
- options: [
- { id: "cat", label: "Cat" },
- { id: "dog", label: "Dog" },
- ],
- },
- {
- id: "color",
- question: "Favorite color?",
- selectionMode: "single",
- options: [
- { id: "blue", label: "Blue" },
- { id: "green", label: "Green" },
- ],
- },
- ],
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- app.start();
- await app.submit("/resume session-multi-question");
- const picker = app.interaction.current();
- expect(picker).toBeDefined();
- terminal.input?.("1");
- expect(runtime.replyQuestionnaire).not.toHaveBeenCalled();
- expect(app.interaction.current()).toBe(picker);
- expect(app.transcript.get("question:question-multi-step")).toMatchObject({
- status: "blocked",
- content: "Favorite animal? Cat",
- detail: "1 of 2 answered",
- });
- const rendered = app.tui.render(80).join("\n");
- expect(rendered).toContain("Answers so far");
- expect(rendered).toContain("Favorite animal? Cat");
- expect(rendered).toContain("Favorite color?");
- terminal.input?.("\u001B[B");
- expect(app.tui.render(80).join("\n")).toContain("› 2 Green");
- terminal.input?.("\r");
- await vi.waitFor(() => {
- expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
- "mavis",
- "question-multi-step",
- [
- {
- stepId: "animal",
- selectedOptionIds: ["cat"],
- selectedOther: false,
- },
- {
- stepId: "color",
- selectedOptionIds: ["green"],
- selectedOther: false,
- },
- ],
- );
- });
- await app.stop();
- });
- it("sends the selected answer immediately and refreshes the Agent continuation", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-review",
- title: "Questionnaire review",
- workspaceDir: "/workspace",
- },
- ]);
- vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
- id: "question-review",
- title: "Release setup",
- steps: [
- {
- id: "channel",
- question: "Choose a channel",
- selectionMode: "single",
- options: [
- { id: "preview", label: "Preview" },
- { id: "stable", label: "Stable" },
- ],
- },
- ],
- });
- const previousMessages = [
- {
- id: "previous-question-answer",
- role: "user" as const,
- content: [
- "<questionnaire-response>",
- " <requestId>question-previous</requestId>",
- " <answers />",
- "</questionnaire-response>",
- "",
- "Q: Choose a channel",
- "A: Preview",
- ].join("\n"),
- },
- ];
- vi.mocked(runtime.getMessages).mockResolvedValue(previousMessages);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- let releaseReply: ((result: boolean) => void) | undefined;
- let releaseContinuation: (() => void) | undefined;
- vi.mocked(runtime.replyQuestionnaire).mockImplementation(
- async () =>
- await new Promise<boolean>((resolve) => {
- releaseReply = resolve;
- }),
- );
- vi.mocked(runtime.watchEvents).mockImplementation(
- async function* watchEvents(signal) {
- await new Promise<void>((resolve) => {
- releaseContinuation = resolve;
- signal.addEventListener("abort", resolve, { once: true });
- });
- if (signal.aborted) return;
- yield runtimeEvent({
- type: "session.start",
- timestamp: Date.now(),
- source: "runtime",
- payload: {
- sessionId: "session-review",
- turnId: "turn-questionnaire-continuation",
- },
- });
- yield runtimeEvent({
- type: "session.finish",
- timestamp: Date.now(),
- source: "runtime",
- payload: {
- sessionId: "session-review",
- turnId: "turn-questionnaire-continuation",
- },
- });
- },
- );
- app.start();
- await app.ready;
- await app.submit("/resume session-review");
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.interaction.isActive()).toBe(true);
- terminal.input?.("2");
- await vi.waitFor(() =>
- expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
- "mavis",
- "question-review",
- [
- {
- stepId: "channel",
- selectedOptionIds: ["stable"],
- selectedOther: false,
- },
- ],
- ),
- );
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.transcript.get("question:question-review")).toMatchObject({
- status: "pending",
- detail: "Sending your answer…",
- });
- releaseReply?.(true);
- await vi.waitFor(() =>
- expect(app.transcript.get("question:question-review")).toMatchObject({
- status: "resolved",
- detail: "Answer sent · MCode is continuing…",
- }),
- );
- vi.mocked(runtime.getMessages).mockResolvedValue([
- ...previousMessages,
- {
- id: "assistant-after-question",
- role: "assistant",
- content: "Agent continued after your answer.",
- },
- ]);
- releaseContinuation?.();
- await vi.waitFor(() =>
- expect(
- app.transcript
- .snapshot()
- .map((cell) => cell.content)
- .join("\n"),
- ).toContain("Agent continued after your answer."),
- );
- expect(app.transcript.get("question:question-review")).toMatchObject({
- kind: "question",
- status: "resolved",
- title: "Answers sent",
- content: "Choose a channel Stable",
- detail: undefined,
- });
- expect(
- app.transcript
- .snapshot()
- .filter((cell) => cell.kind === "question")
- .map((cell) => cell.content),
- ).toEqual(["Choose a channel Preview", "Choose a channel Stable"]);
- expect(app.tui.render(80).join("\n")).not.toContain("Thinking · Message");
- expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
- await app.stop();
- });
- it("redraws after a delayed questionnaire reply resolves", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-delayed-reply",
- title: "Delayed questionnaire reply",
- workspaceDir: "/workspace",
- },
- ]);
- vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
- id: "question-delayed-reply",
- steps: [
- {
- id: "channel",
- question: "Choose a channel",
- selectionMode: "single",
- options: [{ id: "preview", label: "Preview" }],
- },
- ],
- });
- let finishReply: ((result: boolean) => void) | undefined;
- vi.mocked(runtime.replyQuestionnaire).mockImplementation(
- async () =>
- await new Promise<boolean>((resolve) => {
- finishReply = resolve;
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/resume session-delayed-reply");
- terminal.input?.("1");
- await vi.waitFor(() =>
- expect(runtime.replyQuestionnaire).toHaveBeenCalledTimes(1),
- );
- expect(app.tui.hasOverlay()).toBe(false);
- const writesBeforeResolution = terminal.writes.length;
- finishReply?.(true);
- await vi.waitFor(() =>
- expect(
- app.transcript.get("question:question-delayed-reply"),
- ).toMatchObject({
- status: "resolved",
- detail: "Answer sent · MCode is continuing…",
- }),
- );
- await vi.waitFor(() =>
- expect(terminal.writes.length).toBeGreaterThan(writesBeforeResolution),
- );
- await app.stop();
- });
- it("keeps the questionnaire interactive when the Runtime cannot start its continuation", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-retry-questionnaire",
- title: "Retry questionnaire",
- workspaceDir: "/workspace",
- },
- ]);
- vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
- id: "question-retry",
- title: "Choose a channel",
- steps: [
- {
- id: "channel",
- question: "Choose a channel",
- selectionMode: "single",
- options: [{ id: "preview", label: "Preview" }],
- },
- ],
- });
- vi.mocked(runtime.replyQuestionnaire).mockRejectedValue(
- new Error(
- "Questionnaire answer was saved, but the continuation could not start.",
- ),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- app.start();
- await app.ready;
- await app.submit("/resume session-retry-questionnaire");
- terminal.input?.("1");
- await vi.waitFor(() =>
- expect(app.transcript.get("question:question-retry")).toMatchObject({
- status: "blocked",
- title: "Choose a channel",
- detail: "Answer could not be sent · retry",
- }),
- );
- expect(app.interaction.isActive()).toBe(true);
- expect(app.transcript.snapshot().at(-1)).toMatchObject({
- kind: "error",
- content:
- "Couldn't send your answers: Questionnaire answer was saved, but the continuation could not start. Retry. The question remains open.",
- });
- await app.stop();
- });
- it("redraws after a delayed questionnaire dismissal resolves", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-delayed-dismiss",
- title: "Delayed questionnaire dismissal",
- workspaceDir: "/workspace",
- },
- ]);
- vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
- id: "question-delayed-dismiss",
- steps: [{ id: "confirmation", question: "Continue?" }],
- });
- let finishDismiss: ((result: boolean) => void) | undefined;
- vi.mocked(runtime.dismissQuestionnaire).mockImplementation(
- async () =>
- await new Promise<boolean>((resolve) => {
- finishDismiss = resolve;
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/resume session-delayed-dismiss");
- const dismissing = app.submit("/ask-cancel");
- await vi.waitFor(() =>
- expect(runtime.dismissQuestionnaire).toHaveBeenCalledTimes(1),
- );
- const writesBeforeResolution = terminal.writes.length;
- finishDismiss?.(true);
- await dismissing;
- expect(
- app.transcript.get("question:question-delayed-dismiss"),
- ).toMatchObject({
- status: "resolved",
- title: "Question dismissed",
- content: "",
- detail: undefined,
- });
- await vi.waitFor(() =>
- expect(terminal.writes.length).toBeGreaterThan(writesBeforeResolution),
- );
- await app.stop();
- });
- it.each([
- { keyName: "Escape", input: "\x1b" },
- { keyName: "Ctrl-C", input: "\x03" },
- ])(
- "keeps AskUser focused while $keyName dismisses the pending questionnaire",
- async ({ input }) => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-escape-dismiss",
- title: "Escape questionnaire dismissal",
- workspaceDir: "/workspace",
- },
- ]);
- vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
- id: "question-escape-dismiss",
- steps: [
- {
- id: "channel",
- question: "Choose a channel",
- selectionMode: "single",
- options: [{ id: "preview", label: "Preview" }],
- },
- ],
- });
- let finishDismiss: ((result: boolean) => void) | undefined;
- vi.mocked(runtime.dismissQuestionnaire).mockImplementation(
- async () =>
- await new Promise<boolean>((resolve) => {
- finishDismiss = resolve;
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/resume session-escape-dismiss");
- terminal.input?.(input);
- if (input === "\x1b") {
- expect(app.interaction.current()?.render(80).join("\n")).toContain(
- "Cancel this question?",
- );
- terminal.input?.("\r");
- }
- await vi.waitFor(() =>
- expect(runtime.dismissQuestionnaire).toHaveBeenCalledWith(
- "mavis",
- "question-escape-dismiss",
- ),
- );
- expect(app.interaction.isActive()).toBe(true);
- expect(app.interaction.current()?.render(80).join("\n")).toContain(
- "Closing question",
- );
- expect(
- app.state.snapshot().sessions.get("session-escape-dismiss")?.attention
- .question,
- ).toBe(true);
- finishDismiss?.(true);
- await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
- expect(
- app.transcript.get("question:question-escape-dismiss"),
- ).toMatchObject({
- status: "resolved",
- title: "Question dismissed",
- });
- expect(
- app.state.snapshot().sessions.get("session-escape-dismiss")?.attention
- .question,
- ).toBe(false);
- expect(app.tui.render(80).join("\n")).not.toContain("Reply required");
- await app.stop();
- },
- );
- it("denies a pending permission explicitly and releases the blocked interaction", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-pending",
- title: "Pending permission",
- workspaceDir: "/workspace",
- },
- ]);
- vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
- {
- requestId: "permission-pending",
- sessionId: "session-pending",
- agentName: "mavis",
- toolName: "bash",
- toolInput: "pnpm test",
- ruleContents: ["Bash(pnpm test:*)"],
- allowAlwaysSupported: true,
- },
- ]);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/resume session-pending");
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.interaction.isActive()).toBe(true);
- terminal.input?.("3");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.replyPermission).toHaveBeenCalledWith(
- "mavis",
- "permission-pending",
- "deny",
- ),
- );
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.interaction.isActive()).toBe(false);
- expect(app.transcript.get("permission:permission-pending")).toMatchObject({
- status: "resolved",
- detail: "Denied · bash",
- });
- expect(app.tui.render(80).join("\n")).not.toContain("Approval required");
- await app.stop();
- });
- it("resolves a regular inline permission without clearing the terminal viewport", async () => {
- const terminal = new FakeTerminal();
- terminal.rows = 8;
- const runtime = createRuntime();
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-permission-render",
- title: "Permission render",
- workspaceDir: "/workspace",
- },
- ]);
- vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
- {
- requestId: "permission-render",
- sessionId: "session-permission-render",
- agentName: "mavis",
- toolName: "bash",
- toolInput: "pnpm test",
- reason: "Run focused tests",
- allowAlwaysSupported: true,
- },
- ]);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.2.6",
- workspaceDir: "/workspace",
- tuiMode: "regular",
- });
- app.start();
- await app.ready;
- await app.submit("/resume session-permission-render");
- await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
- app.tui.renderNow();
- terminal.writes.length = 0;
- terminal.input?.("\r");
- await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
- await vi.waitFor(() => expect(terminal.writes.length).toBeGreaterThan(0));
- expect(runtime.replyPermission).toHaveBeenCalledWith(
- "mavis",
- "permission-render",
- "allowOnce",
- );
- expect(app.transcript.get("permission:permission-render")).toMatchObject({
- status: "resolved",
- detail: "Allowed for this conversation · bash",
- });
- expect(terminal.writes.join("")).not.toContain("\x1b[2J");
- expect(terminal.writes.join("")).not.toContain("\x1b[3J");
- await app.stop();
- });
- it("keeps a submission retryable when a pending decision blocks admission", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-draft-blocked",
- title: "Pending decision",
- workspaceDir: "/workspace",
- },
- ]);
- vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
- {
- requestId: "permission-draft-blocked",
- sessionId: "session-draft-blocked",
- agentName: "mavis",
- toolName: "bash",
- allowAlwaysSupported: true,
- },
- ]);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/resume session-draft-blocked");
- app.editor.setText("Keep this draft for later");
- app.editor.handleInput("\r");
- await vi.waitFor(() => expect(app.editor.getText()).toBe(""));
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- expect(app.tui.render(80).join("\n")).toContain("Approval required");
- expect(app.tui.render(80).join("\n")).not.toContain("Message · Enter");
- await app.stop();
- });
- it("keeps a pending questionnaire when Runtime rejects dismissal", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-existing",
- title: "Existing session",
- workspaceDir: "/workspace",
- },
- ]);
- vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
- id: "question-rejected",
- steps: [{ id: "step-1", question: "Proceed?" }],
- });
- vi.mocked(runtime.dismissQuestionnaire).mockResolvedValue(false);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- await app.submit("/resume session-existing");
- await app.submit("/ask-cancel");
- expect(app.transcript.get("question:question-rejected")).toMatchObject({
- status: "blocked",
- });
- expect(app.transcript.snapshot().at(-1)).toMatchObject({
- kind: "error",
- content: "Couldn't dismiss this question. It remains open; retry.",
- });
- });
- it("restores the questionnaire panel when an Escape dismissal request fails", async () => {
- const runtime = createRuntime();
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-dismiss-retry",
- title: "Dismiss retry",
- workspaceDir: "/workspace",
- },
- ]);
- vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
- id: "question-dismiss-retry",
- steps: [
- {
- id: "step-1",
- question: "Proceed?",
- selectionMode: "single",
- options: [{ id: "yes", label: "Yes" }],
- },
- ],
- });
- vi.mocked(runtime.dismissQuestionnaire).mockRejectedValue(
- new Error("connection lost"),
- );
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- await app.submit("/resume session-dismiss-retry");
- app.interaction.current()?.handleInput("\u001b");
- app.interaction.current()?.handleInput("\r");
- await vi.waitFor(() =>
- expect(runtime.dismissQuestionnaire).toHaveBeenCalledOnce(),
- );
- await vi.waitFor(() => {
- const panel = app.interaction.current();
- expect(panel).toBeDefined();
- expect(panel?.render(80).join("\n")).toContain("Ask");
- });
- expect(app.transcript.get("question:question-dismiss-retry")).toMatchObject(
- {
- status: "blocked",
- },
- );
- });
- it("settles a questionnaire dismissal that already reached a terminal Runtime state", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-terminal-dismiss",
- title: "Terminal dismissal",
- workspaceDir: "/workspace",
- },
- ]);
- vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
- id: "question-terminal-dismiss",
- steps: [{ id: "step-1", question: "Proceed?" }],
- });
- vi.mocked(runtime.dismissQuestionnaire).mockRejectedValue(
- Object.assign(new Error("already superseded"), {
- status: 410,
- code: "QUESTIONNAIRE_NOT_PENDING",
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- await app.submit("/resume session-terminal-dismiss");
- await app.submit("/ask-cancel");
- expect(
- app.transcript.get("question:question-terminal-dismiss"),
- ).toMatchObject({
- status: "resolved",
- title: "Question closed",
- detail: "Question is no longer pending.",
- });
- expect(app.interaction.isActive()).toBe(false);
- });
- it("projects live Desktop permission events into the transcript", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.watchEvents).mockImplementation(
- async function* watchEvents() {
- yield runtimeEvent({
- type: "permission.ask",
- timestamp: 100,
- source: "runtime",
- payload: {
- requestId: "permission-live",
- sessionId: "session-1",
- agentName: "mavis",
- toolName: "bash",
- toolDescription: "Run a shell command",
- reason: "Run checks",
- ruleContents: ["Bash(pnpm test:*)"],
- allowAlwaysSupported: true,
- },
- });
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- await app.submit("Start the current session");
- await app.submit("/transcript");
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "transcript",
- });
- app.start();
- await vi.waitFor(() =>
- expect(app.transcript.get("permission:permission-live")).toMatchObject({
- kind: "permission",
- status: "blocked",
- content: expect.stringContaining("Run checks"),
- }),
- );
- expect(app.transcript.get("permission:permission-live")).toMatchObject({
- title: "bash",
- content: "Run checks",
- });
- expect(
- app.transcript.get("permission:permission-live")?.content,
- ).not.toContain("Rules:");
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "chat",
- id: "chat",
- });
- await app.submit("/allow");
- expect(app.surfaceHost.getActiveSurface()).toEqual({
- kind: "feature",
- id: "transcript",
- });
- await app.stop();
- });
- it("ignores Desktop interaction events until their session is active", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let resolveEventsDelivered: (() => void) | undefined;
- const eventsDelivered = new Promise<void>((resolve) => {
- resolveEventsDelivered = resolve;
- });
- vi.mocked(runtime.watchEvents).mockImplementation(
- async function* watchEvents(signal) {
- yield runtimeEvent({
- type: "permission.ask",
- timestamp: 100,
- source: "runtime",
- payload: {
- requestId: "permission-other-session",
- sessionId: "session-other",
- agentName: "mavis",
- toolName: "bash",
- },
- });
- yield runtimeEvent({
- type: "questionnaire.ask",
- timestamp: 101,
- source: "runtime",
- payload: {
- sessionId: "session-other",
- agentName: "mavis",
- request: {
- id: "question-other-session",
- steps: [
- { id: "step-1", question: "Proceed?", selectionMode: "single" },
- ],
- },
- },
- });
- resolveEventsDelivered?.();
- await new Promise<void>((resolve) => {
- signal.addEventListener("abort", () => resolve(), { once: true });
- });
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await eventsDelivered;
- expect(
- app.transcript.get("permission:permission-other-session"),
- ).toBeUndefined();
- expect(
- app.transcript.get("question:question-other-session"),
- ).toBeUndefined();
- expect(
- app.state.snapshot().sessions.get("session-other")?.interactions
- .permission?.requestId,
- ).toBe("permission-other-session");
- expect(
- app.state.snapshot().sessions.get("session-other")?.interactions
- .questionnaire?.request.id,
- ).toBe("question-other-session");
- await app.stop();
- });
- it("surfaces only descendant permissions while keeping explicit Deny separate from Stop", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const rootSession = {
- sessionId: "session-root",
- title: "Root session",
- workspaceDir: "/workspace",
- status: "started",
- };
- vi.mocked(runtime.listSessions).mockResolvedValue([rootSession]);
- vi.mocked(runtime.getSession).mockResolvedValue(rootSession);
- vi.mocked(runtime.getDelegationSnapshot).mockResolvedValue({
- schemaVersion: 1,
- rootSessionId: "session-root",
- members: [
- {
- sessionId: "session-child",
- parentSessionId: "session-root",
- agentName: "worker",
- task: "Delegate nested work",
- status: "running",
- },
- {
- sessionId: "session-grandchild",
- parentSessionId: "session-child",
- agentName: "verifier",
- task: "Verify the result",
- status: "running",
- },
- ],
- });
- vi.mocked(runtime.getActiveRun).mockImplementation(
- async (sessionId: string) => ({
- schemaVersion: 1,
- sessionId,
- state:
- sessionId === rootSession.sessionId ? "decision-blocked" : "running",
- turnId:
- sessionId === rootSession.sessionId
- ? "turn-root"
- : `turn-${sessionId}`,
- actions: { steer: false },
- }),
- );
- const deniedPermissionIds = new Set<string>();
- vi.mocked(runtime.replyPermission).mockImplementation(
- async (_agentName, requestId) => {
- deniedPermissionIds.add(requestId);
- return true;
- },
- );
- vi.mocked(runtime.listPendingPermissions).mockImplementation(async () =>
- deniedPermissionIds.has("permission-grandchild")
- ? [
- {
- requestId: "permission-unrelated-next",
- sessionId: "session-unrelated",
- agentName: "worker",
- toolName: "bash",
- reason: "Must remain hidden",
- },
- {
- requestId: deniedPermissionIds.has("permission-child-next")
- ? "permission-child-stop"
- : "permission-child-next",
- sessionId: "session-child",
- agentName: "worker",
- toolName: "read",
- reason: deniedPermissionIds.has("permission-child-next")
- ? "Wait for an explicit Stop"
- : "Inspect the delegated output",
- },
- ]
- : [],
- );
- vi.mocked(runtime.watchEvents).mockImplementation(
- async function* watchEvents(signal) {
- yield runtimeEvent({
- type: "permission.ask",
- timestamp: 100,
- source: "runtime",
- payload: {
- requestId: "permission-unrelated",
- sessionId: "session-unrelated",
- agentName: "worker",
- toolName: "bash",
- reason: "Must stay hidden",
- },
- });
- yield runtimeEvent({
- type: "permission.ask",
- timestamp: 101,
- source: "runtime",
- payload: {
- requestId: "permission-grandchild",
- sessionId: "session-grandchild",
- agentName: "verifier",
- toolName: "write",
- reason: "Update the verification report",
- allowAlwaysSupported: true,
- },
- });
- await new Promise<void>((resolve) => {
- signal.addEventListener("abort", resolve, { once: true });
- });
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- await app.submit("/resume session-root");
- vi.mocked(runtime.abortSession).mockClear();
- vi.mocked(runtime.stopDelegation).mockClear();
- app.start();
- await vi.waitFor(() =>
- expect(
- app.transcript.get("permission:permission-grandchild"),
- ).toMatchObject({
- kind: "permission",
- status: "blocked",
- }),
- );
- expect(
- app.transcript.get("permission:permission-unrelated"),
- ).toBeUndefined();
- expect(app.interaction.current()?.render(80).join("\n")).toContain(
- "Update the verification report",
- );
- app.interaction.current()?.handleInput?.("3");
- app.interaction.current()?.handleInput?.("\r");
- await vi.waitFor(() =>
- expect(runtime.replyPermission).toHaveBeenCalledWith(
- "verifier",
- "permission-grandchild",
- "deny",
- ),
- );
- expect(runtime.stopDelegation).not.toHaveBeenCalled();
- expect(runtime.abortSession).not.toHaveBeenCalled();
- await vi.waitFor(() =>
- expect(app.interaction.current()?.render(80).join("\n")).toContain(
- "Inspect the delegated output",
- ),
- );
- expect(
- app.transcript.get("permission:permission-unrelated-next"),
- ).toBeUndefined();
- terminal.input?.("\x1b");
- await vi.waitFor(() =>
- expect(runtime.replyPermission).toHaveBeenCalledWith(
- "worker",
- "permission-child-next",
- "deny",
- ),
- );
- expect(runtime.abortSession).not.toHaveBeenCalled();
- expect(runtime.stopDelegation).not.toHaveBeenCalled();
- await vi.waitFor(() =>
- expect(app.interaction.current()?.render(80).join("\n")).toContain(
- "Wait for an explicit Stop",
- ),
- );
- terminal.input?.("\x03");
- await vi.waitFor(() =>
- expect(runtime.abortSession).toHaveBeenCalledWith({
- id: rootSession.sessionId,
- turnId: "turn-root",
- reason: "user_stop",
- }),
- );
- expect(runtime.stopDelegation).toHaveBeenCalledOnce();
- expect(runtime.stopDelegation).toHaveBeenCalledWith(rootSession.sessionId);
- expect(runtime.replyPermission).not.toHaveBeenCalledWith(
- "worker",
- "permission-child-stop",
- "deny",
- );
- await app.stop();
- });
- it("recovers a descendant permission from the Runtime pending list without leaking unrelated requests", async () => {
- const runtime = createRuntime();
- const rootSession = {
- sessionId: "session-recovery-root",
- title: "Recovery root",
- workspaceDir: "/workspace",
- };
- vi.mocked(runtime.listSessions).mockResolvedValue([rootSession]);
- vi.mocked(runtime.getSession).mockResolvedValue(rootSession);
- vi.mocked(runtime.getDelegationSnapshot).mockResolvedValue({
- schemaVersion: 1,
- rootSessionId: rootSession.sessionId,
- members: [
- {
- sessionId: "session-recovery-child",
- parentSessionId: rootSession.sessionId,
- agentName: "worker",
- task: "Resume delegated work",
- status: "running",
- },
- ],
- });
- vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
- {
- requestId: "permission-recovery-unrelated",
- sessionId: "session-other-root",
- agentName: "worker",
- toolName: "bash",
- reason: "Do not show this request",
- },
- {
- requestId: "permission-recovery-child",
- sessionId: "session-recovery-child",
- agentName: "worker",
- toolName: "write",
- reason: "Resume the child request",
- },
- ]);
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- await app.submit("/resume session-recovery-root");
- expect(
- app.transcript.get("permission:permission-recovery-child"),
- ).toMatchObject({
- kind: "permission",
- status: "blocked",
- });
- expect(
- app.transcript.get("permission:permission-recovery-unrelated"),
- ).toBeUndefined();
- expect(app.interaction.current()?.render(80).join("\n")).toContain(
- "Resume the child request",
- );
- await app.stop();
- });
- it("reconnects the Runtime event stream after a transient disconnect", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const observability = createObservability();
- let attempt = 0;
- vi.mocked(runtime.watchEvents).mockImplementation(
- async function* watchEvents() {
- attempt += 1;
- if (attempt === 1) throw new Error("connection reset");
- yield runtimeEvent({
- type: "permission.ask",
- timestamp: 101,
- source: "runtime",
- payload: {
- requestId: "permission-after-reconnect",
- sessionId: "session-1",
- toolName: "read",
- },
- });
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- observability,
- });
- await app.ready;
- await app.submit("Start the current session");
- app.start();
- await vi.waitFor(
- () =>
- expect(
- app.transcript.get("permission:permission-after-reconnect"),
- ).toMatchObject({
- status: "blocked",
- }),
- { timeout: 1500 },
- );
- expect(runtime.watchEvents).toHaveBeenCalledTimes(2);
- expect(observability.recordEventStream).toHaveBeenCalledWith(
- expect.objectContaining({
- state: "retry-scheduled",
- attempt: 1,
- retryDelayMs: 250,
- errorKind: "Error",
- }),
- );
- expect(observability.recordEventStream).toHaveBeenCalledWith(
- expect.objectContaining({
- state: "reconnected",
- attempt: 1,
- downtimeMs: expect.any(Number),
- }),
- );
- expect(app.transcript.snapshot()).not.toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- kind: "warning",
- content: expect.stringContaining("Runtime event stream"),
- }),
- ]),
- );
- await app.stop();
- });
- it("sends pasted local attachments and restores failed sends to the Composer", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const readClipboardImage = vi.fn(async () => ({
- attachment: {
- type: "image" as const,
- filePath: "/tmp/minimax-code-clipboard/diagram.png",
- fileName: "diagram.png",
- mimeType: "image/png",
- sizeBytes: 2048,
- },
- dispose: vi.fn(async () => undefined),
- }));
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- readClipboardImage,
- readClipboardText: async () => null,
- });
- app.start();
- await app.ready;
- terminal.input?.("\u001bv");
- await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(1));
- await app.submit("Inspect the diagram");
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- id: "session-1",
- content: "Inspect the diagram",
- attachments: [
- expect.objectContaining({
- local: { filePath: "/tmp/minimax-code-clipboard/diagram.png" },
- meta: expect.objectContaining({ mimeType: "image/png" }),
- }),
- ],
- }),
- expect.any(AbortSignal),
- );
- expect(app.tui.render(80).join("\n")).not.toContain("[Image #1]");
- vi.mocked(runtime.sendMessage).mockImplementationOnce(
- async function* sendMessage() {
- yield { type: "error", message: "provider unavailable" };
- },
- );
- terminal.input?.("\x16");
- await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(2));
- app.editor.setText("Try again");
- app.editor.handleInput("\r");
- await vi.waitFor(() => expect(app.editor.getText()).toContain("Try again"));
- expect(app.tui.render(80).join("\n")).toContain(
- "Error The model provider is temporarily unavailable.",
- );
- expect(app.tui.render(80).join("\n")).not.toContain("Request failed");
- expect(app.editor.getText()).toContain("[Image #1]");
- expect(app.tui.render(80).join("\n")).not.toContain(
- "Message kept under Failed",
- );
- await app.submit("/retry");
- expect(runtime.sendMessage).toHaveBeenLastCalledWith(
- expect.objectContaining({
- content: "Try again",
- attachments: [
- expect.objectContaining({
- local: { filePath: "/tmp/minimax-code-clipboard/diagram.png" },
- }),
- ],
- }),
- expect.any(AbortSignal),
- );
- await app.submit("A fresh turn");
- expect(app.tui.render(80).join("\n")).not.toContain("Couldn't send");
- await app.stop();
- });
- it.each([
- ['content', 'Content review withdrew this response. Rephrase your request, then retry.'],
- ['network', 'Content review did not return a usable result, so this response stopped.'],
- ] as const)("presents a %s review stop without a failed Queue item", async (variant, notice) => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const busEvents: TuiRuntimeEvent[] = [];
- let wakeBus: (() => void) | undefined;
- vi.mocked(runtime.watchEvents).mockImplementation(
- async function* watchEvents(signal) {
- while (!signal.aborted) {
- if (busEvents.length === 0) {
- await new Promise<void>((resolve) => {
- wakeBus = resolve;
- signal.addEventListener("abort", resolve, { once: true });
- });
- }
- const event = busEvents.shift();
- if (event) yield event;
- }
- },
- );
- let releaseTurn: (() => void) | undefined;
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage() {
- await new Promise<void>((resolve) => {
- releaseTurn = resolve;
- });
- yield { type: "done" };
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- terminal.input?.("review this response");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().activeTurnId).toBeTruthy(),
- );
- busEvents.push(
- runtimeEvent({
- type: "content.retry.exceeded",
- timestamp: 100,
- source: "runtime-v2",
- payload: { sessionId: "session-1", variant },
- }),
- runtimeEvent({
- type: "message.rewind",
- timestamp: 101,
- source: "runtime-v2",
- payload: { sessionId: "session-1", contextReset: true },
- }),
- );
- wakeBus?.();
- releaseTurn?.();
- await vi.waitFor(() =>
- expect(app.editor.getText()).toBe("review this response"),
- );
- const rendered = app.tui.render(100).join("\n");
- expect(rendered).toContain(notice);
- expect(rendered).not.toContain('Check your network');
- expect(rendered).not.toContain("Message kept under Failed");
- await app.submit("/queue");
- expect(app.interaction.current()).toBeUndefined();
- await app.stop();
- });
- it("sends editable @directory/ input as ordinary text", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.submit("Review @src/");
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- { id: "session-1", content: "Review @src/", turnId: expect.any(String) },
- expect.any(AbortSignal),
- );
- await expect(app.submit("Review @generated/")).resolves.toBeUndefined();
- expect(runtime.sendMessage).toHaveBeenCalledTimes(2);
- });
- it("pastes a clipboard image without replacing the text draft and cleans it after send", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const dispose = vi.fn(async () => undefined);
- const readClipboardImage = vi.fn(async () => ({
- attachment: {
- type: "image" as const,
- filePath: "/tmp/minimax-code-clipboard/clipboard-1.png",
- fileName: "clipboard-1.png",
- mimeType: "image/png",
- sizeBytes: 4096,
- },
- dispose,
- }));
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- readClipboardImage,
- readClipboardText: async () => null,
- });
- app.start();
- await app.ready;
- app.editor.setText("Keep this draft");
- terminal.input?.("\u001B[118;9u");
- terminal.input?.("\u001B[118;9:3u");
- await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledOnce());
- await vi.waitFor(() =>
- expect(app.editor.getText()).toContain("[Image #1]"),
- );
- expect(app.editor.getText()).toBe("Keep this draft [Image #1] ");
- expect(app.tui.render(100).join("\n")).not.toContain(
- "A clipboard media paste is already in progress.",
- );
- await app.submit("Keep this draft");
- expect(runtime.sendMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- id: "session-1",
- content: "Keep this draft",
- attachments: [
- expect.objectContaining({
- local: { filePath: "/tmp/minimax-code-clipboard/clipboard-1.png" },
- meta: expect.objectContaining({ mimeType: "image/png" }),
- }),
- ],
- }),
- expect.any(AbortSignal),
- );
- expect(dispose).toHaveBeenCalledOnce();
- await app.stop();
- });
- it("retains existing draft state when clipboard read or send fails", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const dispose = vi.fn(async () => undefined);
- const readClipboardImage = vi
- .fn()
- .mockResolvedValueOnce({
- attachment: {
- type: "image" as const,
- filePath: "/tmp/minimax-code-clipboard/clipboard-2.png",
- fileName: "clipboard-2.png",
- mimeType: "image/png",
- sizeBytes: 1024,
- },
- dispose,
- })
- .mockRejectedValueOnce(new Error("clipboard has no image"));
- vi.mocked(runtime.sendMessage).mockImplementationOnce(
- async function* sendMessage() {
- yield { type: "error", message: "provider unavailable" };
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- readClipboardImage,
- readClipboardText: async () => null,
- });
- app.start();
- await app.ready;
- app.editor.setText("Do not clear me");
- terminal.input?.("\x16");
- await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(1));
- terminal.input?.("\x16");
- await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(2));
- expect(app.editor.getText()).toBe("Do not clear me [Image #1] ");
- await app.submit("Try the image");
- expect(dispose).not.toHaveBeenCalled();
- expect(app.tui.render(80).join("\n")).toContain("[Image #1]");
- terminal.input?.("\x7f");
- expect(app.tui.render(80).join("\n")).not.toContain("[Image #1]");
- expect(dispose).not.toHaveBeenCalled();
- await app.stop();
- expect(dispose).toHaveBeenCalledOnce();
- });
- it("cancels an in-flight clipboard read with Ctrl+C and keeps the draft", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let observedSignal: AbortSignal | undefined;
- const readClipboardImage = vi.fn(
- async (signal?: AbortSignal) =>
- await new Promise<never>((_resolve, reject) => {
- observedSignal = signal;
- signal?.addEventListener(
- "abort",
- () => reject(new Error("cancelled")),
- { once: true },
- );
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- readClipboardImage,
- readClipboardText: async () => null,
- });
- app.start();
- await app.ready;
- app.editor.setText("Draft survives");
- terminal.input?.("\x16");
- await vi.waitFor(() => expect(observedSignal).toBeDefined());
- terminal.input?.("\x03");
- await vi.waitFor(() => expect(observedSignal?.aborted).toBe(true));
- expect(app.editor.getText()).toBe("Draft survives");
- await app.stop();
- });
- it("keeps queued clipboard files alive until the Runtime reports a terminal queue state", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const dispose = vi.fn(async () => undefined);
- let finishTurn: (() => void) | undefined;
- let deliverQueueEvent: ((event: TuiRuntimeEvent) => void) | undefined;
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage() {
- await new Promise<void>((resolve) => {
- finishTurn = resolve;
- });
- yield { type: "done" };
- },
- );
- vi.mocked(runtime.watchEvents).mockImplementation(
- async function* watchEvents() {
- const event = await new Promise<TuiRuntimeEvent>((resolve) => {
- deliverQueueEvent = resolve;
- });
- yield event;
- },
- );
- const readClipboardImage = vi.fn(async () => ({
- attachment: {
- type: "image" as const,
- filePath: "/tmp/minimax-code-clipboard/clipboard-queue.png",
- fileName: "clipboard-queue.png",
- mimeType: "image/png",
- sizeBytes: 2048,
- },
- dispose,
- }));
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- productFeatures: { queue: true },
- readClipboardImage,
- });
- app.start();
- await app.ready;
- const first = app.submit("First turn");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().status).toBe("running"),
- );
- terminal.input?.("\x16");
- await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledOnce());
- await app.submit("Queued with image");
- expect(runtime.enqueueMessage).toHaveBeenCalledWith(
- "session-1",
- "Queued with image",
- expect.objectContaining({
- attachments: [
- expect.objectContaining({ fileName: "clipboard-queue.png" }),
- ],
- }),
- );
- expect(dispose).not.toHaveBeenCalled();
- deliverQueueEvent?.(
- runtimeEvent({
- type: "session.queue.updated",
- timestamp: Date.now(),
- source: "runtime",
- payload: {
- sessionId: "session-1",
- itemId: "queue-1",
- status: "completed",
- queuedCount: 0,
- },
- }),
- );
- await vi.waitFor(() => expect(dispose).toHaveBeenCalledOnce());
- finishTurn?.();
- await first;
- await app.stop();
- });
- it("opens the Desktop model picker and applies the selected session model", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listModels).mockResolvedValue([
- {
- providerId: "minimax",
- modelId: "MiniMax-M3",
- displayName: "MiniMax M3",
- variant: "thinking",
- thinkingConfig: { mode: "switchable", defaultValue: "true" },
- providerKind: "minimax-managed",
- selected: true,
- },
- ]);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("Create a session");
- await app.submit("/model");
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.interaction.isActive()).toBe(true);
- terminal.input?.("\x1b");
- expect(app.tui.hasOverlay()).toBe(false);
- await app.submit("/model");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.selectModel).toHaveBeenCalledWith(
- expect.objectContaining({
- providerId: "minimax",
- modelId: "MiniMax-M3",
- variant: "thinking",
- }),
- "session-1",
- ),
- );
- await vi.waitFor(() => {
- const rendered = app.tui.render(120).join("\n");
- expect(rendered).toContain("✦ MiniMax M3");
- expect(rendered).toContain("Thinking On");
- expect(rendered).not.toContain("MiniMax M3#thinking");
- });
- await app.stop();
- });
- it("queues a thinking-on model with the configured effort even when the Session stored none", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let finishTurn: (() => void) | undefined;
- vi.mocked(runtime.listModels).mockResolvedValue([
- {
- providerId: "minimax",
- modelId: "deep-reasoner-1",
- displayName: "deep-reasoner-1",
- selected: true,
- variant: "thinking",
- thinkingConfig: { mode: "switchable", defaultValue: "true" },
- effortOptions: ["xhigh"],
- },
- ]);
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage() {
- await new Promise<void>((resolve) => {
- finishTurn = resolve;
- });
- yield { type: "done" };
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- productFeatures: { queue: true },
- });
- app.start();
- await app.ready;
- const first = app.submit("First turn");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().status).toBe("running"),
- );
- await app.submit("Queued turn");
- // The Session echo carries no stored effort, so the per-Turn selection has to
- // resolve the configured level. Sending only `variant: thinking` makes Runtime
- // drop the effort and the provider apply its own default.
- expect(runtime.enqueueMessage).toHaveBeenCalledWith(
- "session-1",
- "Queued turn",
- expect.objectContaining({
- model: expect.objectContaining({
- providerId: "minimax",
- modelId: "deep-reasoner-1",
- variant: "thinking",
- thinking: { effort: "xhigh" },
- }),
- }),
- );
- finishTurn?.();
- await first;
- await app.stop();
- });
- it("applies a welcome-screen effort to the new Session before sending its first message", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listModels).mockResolvedValue([
- {
- providerId: "custom_provider:byok",
- modelId: "byok-large-5",
- displayName: "BYOK Large 5",
- selected: true,
- variant: "",
- thinkingConfig: { mode: "switchable", defaultValue: "false" },
- effortOptions: ["low", "medium", "high"],
- },
- ]);
- let releaseDefaultSelection: ((selected: boolean) => void) | undefined;
- let releaseSessionSelection: ((selected: boolean) => void) | undefined;
- vi.mocked(runtime.selectModel)
- .mockImplementationOnce(
- async () =>
- await new Promise<boolean>((resolve) => {
- releaseDefaultSelection = resolve;
- }),
- )
- .mockImplementationOnce(
- async () =>
- await new Promise<boolean>((resolve) => {
- releaseSessionSelection = resolve;
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/model");
- terminal.input?.("\u001b[C");
- terminal.input?.("\r");
- const firstTurn = app.submit("First turn");
- await vi.waitFor(() =>
- expect(runtime.selectModel).toHaveBeenNthCalledWith(
- 1,
- expect.objectContaining({ thinking: { effort: "high" }, variant: "" }),
- undefined,
- ),
- );
- expect(runtime.selectModel).toHaveBeenCalledOnce();
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- releaseDefaultSelection?.(true);
- await vi.waitFor(() =>
- expect(runtime.selectModel).toHaveBeenNthCalledWith(
- 2,
- expect.objectContaining({ thinking: { effort: "high" }, variant: "" }),
- "session-1",
- ),
- );
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- releaseSessionSelection?.(true);
- await firstTurn;
- expect(runtime.sendMessage).toHaveBeenCalledOnce();
- expect(runtime.selectModel.mock.invocationCallOrder[1]).toBeLessThan(
- runtime.sendMessage.mock.invocationCallOrder[0] ??
- Number.POSITIVE_INFINITY,
- );
- await app.stop();
- });
- it("does not send the first message when Runtime rejects its pending effort", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listModels).mockResolvedValue([
- {
- providerId: "custom_provider:byok",
- modelId: "byok-large-5",
- displayName: "BYOK Large 5",
- selected: true,
- effortOptions: ["low", "medium", "high"],
- },
- ]);
- vi.mocked(runtime.selectModel)
- .mockResolvedValueOnce(true)
- .mockResolvedValueOnce(false);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/model");
- terminal.input?.("\r");
- await vi.waitFor(() => expect(runtime.selectModel).toHaveBeenCalledOnce());
- await app.submit("First turn");
- expect(runtime.selectModel).toHaveBeenCalledTimes(2);
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- await app.stop();
- });
- it("lets Escape cancel the first turn while Desktop is creating its session", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let finishSessionCreation:
- | ((session: { sessionId: string; workspaceDir: string }) => void)
- | undefined;
- vi.mocked(runtime.createSession).mockImplementation(
- async () =>
- await new Promise<{ sessionId: string; workspaceDir: string }>(
- (resolve) => {
- finishSessionCreation = resolve;
- },
- ),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- const submitting = app.submit("Wait for the session");
- await vi.waitFor(() =>
- expect(app.controller.snapshot()).toMatchObject({
- status: "starting",
- activeTurnId: expect.any(String),
- }),
- );
- expect(app.tui.render(80).join("\n")).toContain("Loading");
- expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
- expect(app.tui.render(80).join("\n")).not.toContain("MCode ·");
- terminal.input?.("\x1b");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
- );
- finishSessionCreation?.({
- sessionId: "session-created",
- workspaceDir: "/workspace",
- });
- await submitting;
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- expect(app.transcript.snapshot()).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ kind: "assistant", status: "cancelled" }),
- ]),
- );
- await app.stop();
- });
- it("restores a submission attempted while the previous cancellation fence is active", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let releaseCancelledStream: (() => void) | undefined;
- let sendCount = 0;
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage(_req: SendMessageReq, signal?: AbortSignal) {
- sendCount += 1;
- if (sendCount === 1) {
- await new Promise<void>((resolve) => {
- signal?.addEventListener("abort", resolve, { once: true });
- });
- await new Promise<void>((resolve) => {
- releaseCancelledStream = resolve;
- });
- } else {
- yield { type: "delta", content: "Second response" };
- }
- yield { type: "done" };
- },
- );
- vi.mocked(runtime.abortSession).mockImplementation(async () => {
- setTimeout(() => releaseCancelledStream?.(), 10);
- return true;
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- terminal.input?.("First request");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().status).toBe("running"),
- );
- terminal.input?.("\x1b");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().cancelling).toBe(true),
- );
- terminal.input?.("Second request");
- terminal.input?.("\r");
- await vi.waitFor(() => expect(app.editor.getText()).toBe("Second request"));
- expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
- await vi.waitFor(() =>
- expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
- );
- await vi.waitFor(() =>
- expect(app.controller.snapshot().retiringTurnId).toBeUndefined(),
- );
- expect(app.controller.snapshot().cancelling).toBe(false);
- expect(app.tui.render(80).join("\n")).not.toContain(
- "Stopping the current response",
- );
- app.editor.handleInput("\r");
- await vi.waitFor(() =>
- expect(runtime.sendMessage).toHaveBeenCalledTimes(2),
- );
- expect(runtime.sendMessage).toHaveBeenCalledTimes(2);
- expect(runtime.enqueueMessage).not.toHaveBeenCalled();
- expect(app.transcript.snapshot()).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ kind: "assistant", status: "cancelled" }),
- ]),
- );
- await app.stop();
- });
- it("restores a failed submission before text typed while cancellation is retiring", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let releaseRuntimeOwnership: (() => void) | undefined;
- const runtimeOwnershipReleased = new Promise<void>((resolve) => {
- releaseRuntimeOwnership = resolve;
- });
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage(_req: SendMessageReq, signal?: AbortSignal) {
- await new Promise<void>((resolve) => {
- signal?.addEventListener("abort", resolve, { once: true });
- });
- await runtimeOwnershipReleased;
- yield { type: "done" };
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- terminal.input?.("First request");
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().status).toBe("running"),
- );
- terminal.input?.("\x1b");
- await vi.waitFor(
- () => expect(app.controller.snapshot().retiringTurnId).toBeTruthy(),
- {
- timeout: 2_000,
- },
- );
- expect(app.controller.snapshot()).toMatchObject({
- status: "idle",
- activeTurnId: undefined,
- cancelling: false,
- });
- terminal.input?.("Second request");
- terminal.input?.("\r");
- terminal.input?.("extra detail");
- await vi.waitFor(() => expect(app.editor.getText()).toBe("extra detail"));
- expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
- await vi.waitFor(() =>
- expect(app.tui.render(160).join("\n")).toContain("Second request"),
- );
- expect(app.editor.getText()).toBe("Second request\nextra detail");
- releaseRuntimeOwnership?.();
- await vi.waitFor(() =>
- expect(app.controller.snapshot().retiringTurnId).toBeUndefined(),
- );
- expect(app.tui.render(160).join("\n")).not.toContain(
- "Runtime is still stopping; your draft is preserved",
- );
- await app.stop();
- });
- it("aborts session creation when the TUI stops during its first turn", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let finishSessionCreation:
- | ((session: { sessionId: string; workspaceDir: string }) => void)
- | undefined;
- vi.mocked(runtime.createSession).mockImplementation(
- async () =>
- await new Promise<{ sessionId: string; workspaceDir: string }>(
- (resolve) => {
- finishSessionCreation = resolve;
- },
- ),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- const submitting = app.submit("Wait for the session");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().activeTurnId).toEqual(
- expect.any(String),
- ),
- );
- const stopping = app.stop();
- finishSessionCreation?.({
- sessionId: "session-created",
- workspaceDir: "/workspace",
- });
- await Promise.all([submitting, stopping]);
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- expect(app.transcript.snapshot()).toEqual(
- expect.arrayContaining([
- expect.objectContaining({ kind: "assistant", status: "cancelled" }),
- ]),
- );
- expect(terminal.stopped).toBe(true);
- });
- it.each(["minimax", "custom_provider:work"])(
- "hydrates the Runtime-selected startup model for %s",
- async (providerId) => {
- const runtime = createRuntime();
- vi.mocked(runtime.listModels).mockResolvedValue([
- { providerId, modelId: "MiniMax-M3", selected: true },
- ]);
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- try {
- await app.ready;
- expect(runtime.listModels).toHaveBeenCalled();
- expect(runtime.selectModel).not.toHaveBeenCalled();
- await app.submit("/model");
- expect(runtime.selectModel).not.toHaveBeenCalled();
- } finally {
- await app.stop();
- }
- },
- );
- it("offers provider onboarding when Desktop has no models", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listModels).mockResolvedValue([]);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- await app.submit("/model unavailable");
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.interaction.isActive()).toBe(true);
- const rendered = app.tui.render(120).join("\n");
- expect(rendered).toContain("No matching models");
- expect(rendered).toContain("Add 3rd-party provider");
- terminal.input?.("\x1b");
- await app.stop();
- });
- it("keeps the TUI usable when the Runtime model catalog fails to load", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- vi.mocked(runtime.listModels).mockRejectedValue(
- new Error("catalog unavailable"),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- await expect(app.submit("/model")).resolves.toBeUndefined();
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.transcript.snapshot().at(-1)).toMatchObject({
- kind: "warning",
- content: "Couldn't load models: catalog unavailable. Retry /model.",
- });
- });
- it("shows a follow-up as queued while Runtime admission is pending", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let finishFirstTurn: (() => void) | undefined;
- let finishEnqueue: (() => void) | undefined;
- let admitted = false;
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage() {
- await new Promise<void>((resolve) => {
- finishFirstTurn = resolve;
- });
- yield { type: "done" };
- },
- );
- vi.mocked(runtime.enqueueMessage).mockImplementation(async () => {
- await new Promise<void>((resolve) => {
- finishEnqueue = resolve;
- });
- admitted = true;
- return { itemId: "queue-pending-1", status: "queued", position: 1 };
- });
- vi.mocked(runtime.listQueuedMessages).mockImplementation(async () =>
- admitted
- ? [
- {
- itemId: "queue-pending-1",
- sessionId: "session-1",
- status: "queued",
- content: "Second turn",
- },
- ]
- : [],
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- const first = app.submit("First turn");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().activeTurnId).toEqual(
- expect.any(String),
- ),
- );
- terminal.input?.("Second turn");
- terminal.input?.("\x1b\r");
- await vi.waitFor(() =>
- expect(runtime.enqueueMessage).toHaveBeenCalledOnce(),
- );
- try {
- expect(
- app.transcript
- .snapshot()
- .find((cell) => cell.content.includes("Second turn")),
- ).toBeUndefined();
- const rendered = app.tui.render(100).join("\n");
- expect(rendered).not.toContain("Adding to Queue");
- expect(rendered).toContain("Next · after current response");
- expect(rendered).toContain("Second turn");
- finishEnqueue?.();
- await vi.waitFor(() => {
- const confirmed = app.tui.render(100).join("\n");
- expect(confirmed).not.toContain("Adding to Queue");
- expect(confirmed).toContain("Next · after current response");
- expect(confirmed).toContain("Second turn");
- });
- } finally {
- finishEnqueue?.();
- finishFirstTurn?.();
- await first;
- await app.stop();
- }
- });
- it("removes the local Queue admission and restores the Draft when Runtime rejects it", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let finishFirstTurn: (() => void) | undefined;
- let rejectEnqueue: ((error: Error) => void) | undefined;
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage() {
- await new Promise<void>((resolve) => {
- finishFirstTurn = resolve;
- });
- yield { type: "done" };
- },
- );
- vi.mocked(runtime.enqueueMessage).mockImplementation(
- async () =>
- await new Promise<never>((_resolve, reject) => {
- rejectEnqueue = reject;
- }),
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- const first = app.submit("First turn");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().activeTurnId).toEqual(
- expect.any(String),
- ),
- );
- terminal.input?.("Keep this Draft");
- terminal.input?.("\x1b\r");
- await vi.waitFor(() =>
- expect(app.tui.render(100).join("\n")).toContain(
- "Next · after current response",
- ),
- );
- await vi.waitFor(() =>
- expect(runtime.enqueueMessage).toHaveBeenCalledOnce(),
- );
- rejectEnqueue?.(new Error("queue unavailable"));
- await vi.waitFor(() =>
- expect(app.editor.getText()).toBe("Keep this Draft"),
- );
- const rendered = app.tui.render(100).join("\n");
- expect(rendered).not.toContain("Next · after current response");
- expect(rendered).toContain("Couldn't add this message to the Queue");
- finishFirstTurn?.();
- await first;
- await app.stop();
- });
- it("shows every rapid follow-up as queued while Runtime admissions are serialized", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let finishFirstTurn: (() => void) | undefined;
- const releaseAdmissions: Array<() => void> = [];
- const queued: TuiQueuedMessage[] = [];
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage() {
- await new Promise<void>((resolve) => {
- finishFirstTurn = resolve;
- });
- yield { type: "done" };
- },
- );
- vi.mocked(runtime.enqueueMessage).mockImplementation(
- async (sessionId, content) => {
- await new Promise<void>((resolve) => releaseAdmissions.push(resolve));
- const item = {
- itemId: `queue-rapid-${String(queued.length + 1)}`,
- sessionId,
- status: "queued",
- content,
- } satisfies TuiQueuedMessage;
- queued.push(item);
- return {
- itemId: item.itemId,
- status: item.status,
- position: queued.length,
- };
- },
- );
- vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
- ...queued,
- ]);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- const first = app.submit("First turn");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().activeTurnId).toEqual(
- expect.any(String),
- ),
- );
- terminal.input?.("Second turn");
- terminal.input?.("\x1b\r");
- terminal.input?.("Third turn");
- terminal.input?.("\x1b\r");
- await vi.waitFor(() => {
- const rendered = app.tui.render(100).join("\n");
- expect(rendered).not.toContain("Adding");
- expect(rendered).toContain("Queue · 2 next");
- expect(rendered).toContain("Second turn");
- expect(rendered).toContain("Third turn");
- });
- expect(
- app.transcript
- .snapshot()
- .filter(
- (cell) =>
- cell.content.includes("Second turn") ||
- cell.content.includes("Third turn"),
- ),
- ).toEqual([]);
- await vi.waitFor(() =>
- expect(runtime.enqueueMessage).toHaveBeenCalledOnce(),
- );
- releaseAdmissions[0]?.();
- await vi.waitFor(() =>
- expect(runtime.enqueueMessage).toHaveBeenCalledTimes(2),
- );
- const partiallyConfirmed = app.tui.render(100).join("\n");
- expect(partiallyConfirmed).toContain("Queue · 2 next");
- expect(partiallyConfirmed.indexOf("Second turn")).toBeLessThan(
- partiallyConfirmed.indexOf("Third turn"),
- );
- releaseAdmissions[1]?.();
- await vi.waitFor(() =>
- expect(app.tui.render(100).join("\n")).toContain("Queue · 2 next"),
- );
- finishFirstTurn?.();
- await first;
- await app.stop();
- });
- it("submits follow-ups to the runtime-owned queue and never drains them in the CLI", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let finishFirstTurn: (() => void) | undefined;
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage(req: SendMessageReq) {
- const content = req.content ?? "";
- if (content === "First turn") {
- await new Promise<void>((resolve) => {
- finishFirstTurn = resolve;
- });
- }
- yield { type: "delta", content: `Reply to ${content || "attachment"}` };
- yield { type: "done" };
- },
- );
- const attachment = {
- type: "file" as const,
- filePath: "/workspace/notes.md",
- fileName: "notes.md",
- mimeType: "text/markdown",
- sizeBytes: 32,
- };
- const queued: Array<{
- itemId: string;
- sessionId: string;
- status: string;
- content: string;
- }> = [];
- vi.mocked(runtime.enqueueMessage).mockImplementation(
- async (sessionId, content) => {
- const item = {
- itemId: `queue-${queued.length + 1}`,
- sessionId,
- status: "queued",
- content,
- };
- queued.push(item);
- return {
- itemId: item.itemId,
- status: item.status,
- position: queued.length,
- };
- },
- );
- vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
- ...queued,
- ]);
- vi.mocked(runtime.deleteQueuedMessage).mockImplementation(
- async (_sessionId, itemId) => {
- const index = queued.findIndex((item) => item.itemId === itemId);
- if (index < 0) return undefined;
- return queued.splice(index, 1)[0];
- },
- );
- const readClipboardImage = vi.fn(async () => ({
- attachment,
- dispose: vi.fn(async () => undefined),
- }));
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- readClipboardImage,
- });
- app.start();
- await app.ready;
- const first = app.submit("First turn");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().activeTurnId).toEqual(
- expect.any(String),
- ),
- );
- terminal.input?.("\x16");
- await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledOnce());
- await app.submit("Second turn");
- await app.submit("Third turn");
- expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
- expect(runtime.enqueueMessage).toHaveBeenNthCalledWith(
- 1,
- "session-1",
- "Second turn",
- {
- attachments: [attachment],
- model: { providerId: "minimax", modelId: "MiniMax-M2.7" },
- },
- );
- expect(runtime.enqueueMessage).toHaveBeenNthCalledWith(
- 2,
- "session-1",
- "Third turn",
- {
- attachments: [],
- model: { providerId: "minimax", modelId: "MiniMax-M2.7" },
- },
- );
- expect(app.transcript.get("queue:queue-1")).toBeUndefined();
- expect(app.transcript.get("queue:queue-2")).toBeUndefined();
- const queuedUi = app.tui.render(80).join("\n");
- expect(queuedUi).toContain("Queue · 2 next");
- expect(queuedUi).toContain("after current response");
- expect(queuedUi).toContain("Second turn");
- expect(queuedUi).toContain("Third turn");
- expect(queuedUi).toContain("/queue manage");
- await app.submit("/queue");
- expect(app.interaction.render(80).join("\n")).toContain("Queue");
- expect(app.interaction.render(80).join("\n")).toContain("2 next");
- expect(app.interaction.render(80).join("\n")).toContain("› 2. Third turn");
- expect(app.editor.getText()).toBe("");
- terminal.input?.("d");
- expect(app.interaction.render(80).join("\n")).toContain(
- "Remove this next message?",
- );
- terminal.input?.("\r");
- await vi.waitFor(() =>
- expect(runtime.deleteQueuedMessage).toHaveBeenCalledWith(
- "session-1",
- "queue-2",
- ),
- );
- await vi.waitFor(() =>
- expect(app.tui.render(80).join("\n")).not.toContain("Third turn"),
- );
- expect(app.tui.render(80).join("\n")).toContain("Second turn");
- terminal.input?.("\x1b");
- finishFirstTurn?.();
- await first;
- expect(
- vi.mocked(runtime.sendMessage).mock.calls.map((call) => call[0].content),
- ).toEqual(["First turn"]);
- expect(app.tui.render(80).join("\n")).toContain(
- "Next · after current response",
- );
- expect(app.tui.render(80).join("\n")).toContain("Second turn");
- expect(app.tui.render(80).join("\n")).not.toContain("Sending next");
- await app.stop();
- });
- it("uses the Runtime queue when a resumed started session is active before queue/model hydration finishes", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let releaseQueue: ((items: TuiQueuedMessage[]) => void) | undefined;
- const slowQueue = new Promise<TuiQueuedMessage[]>((resolve) => {
- releaseQueue = resolve;
- });
- let releaseModels: ((models: TuiModel[]) => void) | undefined;
- const slowModels = new Promise<TuiModel[]>((resolve) => {
- releaseModels = resolve;
- });
- const session = {
- sessionId: "session-running",
- title: "Running session",
- workspaceDir: "/workspace",
- status: "started",
- };
- vi.mocked(runtime.listSessions).mockResolvedValue([session]);
- vi.mocked(runtime.getSession).mockResolvedValue(session);
- vi.mocked(runtime.getActiveRun).mockResolvedValue({
- schemaVersion: 1,
- sessionId: "session-running",
- state: "running",
- turnId: "turn-running",
- actions: { steer: true },
- });
- vi.mocked(runtime.listQueuedMessages).mockImplementation(
- async () => slowQueue,
- );
- vi.mocked(runtime.listModels).mockImplementation(async (sessionId) =>
- sessionId ? slowModels : [],
- );
- vi.mocked(runtime.enqueueMessage).mockResolvedValue({
- itemId: "queue-running-1",
- status: "queued",
- position: 1,
- });
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- productFeatures: { queue: true },
- });
- await app.ready;
- const resuming = app.submit("/resume session-running");
- await vi.waitFor(() =>
- expect(app.tui.render(80).join("\n")).toContain("Loading"),
- );
- expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
- const followUp = app.submit("Send this through the Runtime queue");
- await vi.waitFor(() =>
- expect(runtime.enqueueMessage).toHaveBeenCalledWith(
- "session-running",
- "Send this through the Runtime queue",
- { attachments: [] },
- ),
- );
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- releaseQueue?.([]);
- releaseModels?.([]);
- await Promise.all([resuming, followUp]);
- await app.stop();
- });
- it("does not recover a terminal session as an active turn", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const session = {
- sessionId: "session-finished",
- title: "Finished session",
- workspaceDir: "/workspace",
- status: "finished",
- };
- vi.mocked(runtime.listSessions).mockResolvedValue([session]);
- vi.mocked(runtime.getSession).mockResolvedValue(session);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- await app.submit("/resume session-finished");
- expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
- expect(app.tui.render(80).join("\n")).toContain("Message · Enter send");
- await app.stop();
- });
- it("does not recover a stale started Session when Runtime is already idle", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const session = {
- sessionId: "session-stale",
- title: "Stale session",
- workspaceDir: "/workspace",
- status: "started",
- };
- vi.mocked(runtime.listSessions).mockResolvedValue([session]);
- vi.mocked(runtime.getSession).mockResolvedValue(session);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/resume session-stale");
- await vi.waitFor(() =>
- expect(app.tui.render(80).join("\n")).not.toContain("Loading"),
- );
- const rendered = app.tui.render(80).join("\n");
- expect(rendered).not.toContain("Thinking");
- expect(rendered).not.toContain("Stopping response");
- expect(rendered).not.toContain("Stopping the current response");
- expect(rendered).toContain("Message · Enter send");
- await app.stop();
- });
- it("stops a recovered Runtime turn with /stop and Escape through abortSession", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const session = {
- sessionId: "session-running",
- title: "Running session",
- workspaceDir: "/workspace",
- status: "started",
- };
- vi.mocked(runtime.listSessions).mockResolvedValue([session]);
- vi.mocked(runtime.getSession).mockResolvedValue(session);
- vi.mocked(runtime.getActiveRun).mockResolvedValue({
- schemaVersion: 1,
- sessionId: "session-running",
- state: "running",
- turnId: "turn-running",
- actions: { steer: true },
- });
- vi.mocked(runtime.abortSession).mockResolvedValue(true);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/resume session-running");
- await app.submit("/stop");
- expect(runtime.abortSession).toHaveBeenCalledWith(
- expect.objectContaining({ id: "session-running" }),
- );
- expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
- vi.mocked(runtime.abortSession).mockClear();
- await app.submit("/resume session-running");
- terminal.input?.("\x1b");
- await vi.waitFor(() =>
- expect(runtime.abortSession).toHaveBeenCalledWith(
- expect.objectContaining({ id: "session-running" }),
- ),
- );
- await vi.waitFor(() =>
- expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt"),
- );
- expect(app.tui.render(80).join("\n")).not.toMatch(
- /Stopped after|Interrupted after/u,
- );
- await app.stop();
- });
- it.each([
- [
- "rejects the abort",
- async () => false,
- "Runtime did not confirm that the active response stopped.",
- ],
- [
- "fails the abort request",
- async () => Promise.reject(new Error("connection lost")),
- "Couldn't stop the current response:",
- ],
- ])(
- "clears the recovered foreground projection and reports when Runtime %s",
- async (_label, abort, expectedError) => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const session = {
- sessionId: "session-running",
- title: "Running session",
- workspaceDir: "/workspace",
- status: "started",
- };
- vi.mocked(runtime.listSessions).mockResolvedValue([session]);
- vi.mocked(runtime.getSession).mockResolvedValue(session);
- vi.mocked(runtime.getActiveRun).mockResolvedValue({
- schemaVersion: 1,
- sessionId: "session-running",
- state: "running",
- turnId: "turn-running",
- actions: { steer: false },
- });
- vi.mocked(runtime.abortSession).mockImplementation(abort);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/resume session-running");
- terminal.input?.("\x1b");
- await vi.waitFor(() =>
- expect(runtime.abortSession).toHaveBeenCalledWith(
- expect.objectContaining({ id: "session-running" }),
- ),
- );
- await vi.waitFor(() =>
- expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt"),
- );
- await vi.waitFor(() =>
- expect(app.tui.render(80).join("\n")).toContain(expectedError),
- );
- await app.stop();
- },
- );
- it("keeps Request failed visible when Runtime still has queued follow-ups", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let finishTurn: (() => void) | undefined;
- const queued = [
- {
- itemId: "queue-after-error",
- sessionId: "session-1",
- status: "queued",
- content: "Continue after failure",
- },
- ];
- vi.mocked(runtime.listQueuedMessages).mockResolvedValue(queued);
- vi.mocked(runtime.enqueueMessage).mockResolvedValue({
- itemId: "queue-after-error",
- status: "queued",
- position: 1,
- });
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage() {
- await new Promise<void>((resolve) => {
- finishTurn = resolve;
- });
- yield { type: "error", message: "provider unavailable" };
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- productFeatures: { queue: true },
- });
- await app.ready;
- const first = app.submit("First turn");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().activeTurnId).toEqual(
- expect.any(String),
- ),
- );
- await app.submit("Continue after failure");
- finishTurn?.();
- await first;
- expect(app.tui.render(80).join("\n")).toContain(
- "Error The model provider is temporarily unavailable.",
- );
- expect(app.tui.render(80).join("\n")).not.toContain("Request failed");
- await app.stop();
- });
- it("converges a recovered running state after the Runtime emits a terminal event", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const session = {
- sessionId: "session-recovered",
- title: "Recovered session",
- workspaceDir: "/workspace",
- status: "started",
- };
- const busEvents: TuiRuntimeEvent[] = [];
- let wakeBus: (() => void) | undefined;
- const waitForNextBusEvent = (signal: AbortSignal) =>
- new Promise<void>((resolve) => {
- wakeBus = resolve;
- signal.addEventListener("abort", resolve, { once: true });
- });
- vi.mocked(runtime.listSessions).mockResolvedValue([session]);
- vi.mocked(runtime.getSession).mockResolvedValue(session);
- let activeRecoveredTurn = true;
- vi.mocked(runtime.getActiveRun).mockImplementation(async () =>
- activeRecoveredTurn
- ? {
- schemaVersion: 1,
- sessionId: "session-recovered",
- state: "running",
- turnId: "turn-recovered",
- actions: { steer: true },
- }
- : {
- schemaVersion: 1,
- sessionId: "session-recovered",
- state: "terminal",
- turnId: "turn-recovered",
- actions: { steer: false },
- },
- );
- let durableMessages: Awaited<ReturnType<TuiRuntime["getMessages"]>> = [];
- vi.mocked(runtime.getMessages).mockImplementation(
- async () => durableMessages,
- );
- vi.mocked(runtime.watchEvents).mockImplementation(
- async function* watchEvents(signal) {
- while (!signal.aborted) {
- if (busEvents.length === 0) await waitForNextBusEvent(signal);
- if (signal.aborted) return;
- const event = busEvents.shift();
- if (event) yield event;
- }
- },
- );
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/resume session-recovered");
- expect(app.tui.render(80).join("\n")).toContain("Loading");
- expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
- await vi.waitFor(() =>
- expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
- "session-recovered",
- "turn-recovered",
- expect.any(AbortSignal),
- ),
- );
- activeRecoveredTurn = false;
- const historyCallsBeforeTerminal = vi.mocked(runtime.getMessages).mock.calls
- .length;
- durableMessages = [
- {
- id: "message-recovered-assistant",
- turnId: "turn-recovered",
- role: "assistant",
- content: "Recovered answer",
- timestamp: 101,
- },
- ];
- busEvents.push(
- runtimeEvent({
- type: "session.finish",
- timestamp: 101,
- source: "runtime",
- payload: {
- sessionId: "session-recovered",
- turnId: "turn-recovered",
- status: "finished",
- },
- }),
- );
- wakeBus?.();
- wakeBus = undefined;
- await vi.waitFor(() =>
- expect(vi.mocked(runtime.getMessages).mock.calls.length).toBeGreaterThan(
- historyCallsBeforeTerminal,
- ),
- );
- await vi.waitFor(() => {
- const rendered = app.tui.render(80).join("\n");
- expect(rendered).not.toContain("Esc to interrupt");
- expect(app.transcript.snapshot()).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- kind: "assistant",
- content: "Recovered answer",
- }),
- ]),
- );
- });
- await app.stop();
- });
- it("clears a recovered decision block when switching to a session without a pending decision", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- let controllerSessionId = "";
- const firstSession = {
- sessionId: "session-blocked",
- title: "Blocked session",
- workspaceDir: "/workspace",
- status: "started",
- };
- const secondSession = {
- sessionId: "session-clear",
- title: "Clear session",
- workspaceDir: "/workspace",
- status: "finished",
- };
- vi.mocked(runtime.listSessions).mockResolvedValue([
- firstSession,
- secondSession,
- ]);
- vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
- sessionId === firstSession.sessionId ? firstSession : secondSession,
- );
- vi.mocked(runtime.listPendingPermissions).mockImplementation(async () =>
- controllerSessionId === firstSession.sessionId
- ? [
- {
- requestId: "permission-blocked",
- sessionId: firstSession.sessionId,
- agentName: "mavis",
- toolName: "bash",
- reason: "Run checks",
- allowAlwaysSupported: true,
- },
- ]
- : [],
- );
- vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue(undefined);
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- controllerSessionId = firstSession.sessionId;
- await app.submit("/resume session-blocked");
- expect(app.tui.hasOverlay()).toBe(false);
- expect(app.interaction.isActive()).toBe(true);
- expect(app.tui.render(80).join("\n")).toContain("Approval required");
- controllerSessionId = secondSession.sessionId;
- await app.submit("/resume session-clear");
- expect(app.tui.hasOverlay()).toBe(false);
- const rendered = app.tui.render(80).join("\n");
- expect(rendered).not.toContain("Approval required");
- expect(rendered).not.toContain("Reply required");
- await app.stop();
- });
- it("moves a sending follow-up from the Composer area into the user transcript", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const busEvents: TuiRuntimeEvent[] = [];
- let wakeBus: (() => void) | undefined;
- const waitForNextBusEvent = (signal: AbortSignal) =>
- new Promise<void>((resolve) => {
- wakeBus = resolve;
- signal.addEventListener("abort", resolve, { once: true });
- });
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-existing",
- title: "Existing",
- workspaceDir: "/workspace",
- },
- ]);
- vi.mocked(runtime.listQueuedMessages).mockResolvedValue([
- {
- itemId: "queue-with-attachment",
- sessionId: "session-existing",
- status: "queued",
- content: "Review the attached plan",
- attachments: [
- {
- meta: {
- attachmentType: "file",
- fileName: "plan.md",
- mimeType: "text/markdown",
- sizeBytes: 42,
- },
- local: { filePath: "/workspace/plan.md" },
- },
- ],
- },
- {
- itemId: "queue-that-fails",
- sessionId: "session-existing",
- status: "queued",
- content: "Run the failing follow-up",
- },
- ]);
- vi.mocked(runtime.watchEvents).mockImplementation(
- async function* watchEvents(signal) {
- while (!signal.aborted) {
- if (busEvents.length === 0) await waitForNextBusEvent(signal);
- if (signal.aborted) return;
- const event = busEvents.shift();
- if (event) yield event;
- }
- },
- );
- const emitQueueStatus = (
- itemId: string,
- status: string,
- failedReason?: string,
- ) => {
- busEvents.push(
- runtimeEvent({
- type: "session.queue.updated",
- timestamp: Date.now(),
- source: "runtime",
- payload: {
- sessionId: "session-existing",
- itemId,
- status,
- queuedCount: status === "queued" ? 1 : 0,
- ...(failedReason ? { failedReason } : {}),
- },
- }),
- );
- wakeBus?.();
- wakeBus = undefined;
- };
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- productFeatures: { queue: true },
- });
- app.start();
- await app.ready;
- await app.submit("/resume session-existing");
- expect(app.tui.render(80).join("\n")).toContain("Queue · 2 next");
- expect(app.tui.render(80).join("\n")).toContain("Review the attached plan");
- expect(app.transcript.get("queue:queue-with-attachment")).toBeUndefined();
- emitQueueStatus("queue-with-attachment", "running");
- await vi.waitFor(() =>
- expect(app.transcript.get("queue:queue-with-attachment")).toMatchObject({
- kind: "user",
- status: "succeeded",
- content: expect.stringContaining("Review the attached plan"),
- }),
- );
- expect(app.tui.render(80).join("\n")).not.toContain("SENDING");
- expect(app.tui.render(80).join("\n")).toContain(
- "Next · after current response",
- );
- expect(app.tui.render(80).join("\n")).toContain(
- "Run the failing follow-up",
- );
- expect(
- app.transcript.get("queue:queue-with-attachment")?.attachments,
- ).toEqual([
- expect.objectContaining({
- fileName: "plan.md",
- mimeType: "text/markdown",
- sizeBytes: 42,
- }),
- ]);
- emitQueueStatus("queue-with-attachment", "completed");
- await vi.waitFor(() =>
- expect(app.transcript.get("queue:queue-with-attachment")).toMatchObject({
- kind: "user",
- status: "succeeded",
- content: expect.stringContaining("Review the attached plan"),
- }),
- );
- emitQueueStatus("queue-that-fails", "running");
- await vi.waitFor(() =>
- expect(app.transcript.get("queue:queue-that-fails")).toMatchObject({
- kind: "user",
- status: "succeeded",
- }),
- );
- emitQueueStatus(
- "queue-that-fails",
- "admission-rejected",
- "provider unavailable",
- );
- await vi.waitFor(() =>
- expect(app.editor.getText()).toBe("Run the failing follow-up"),
- );
- expect(app.tui.render(80).join("\n")).toContain(
- "Error Message was not added to the Queue: provider unavailable.",
- );
- expect(app.transcript.get("queue:queue-that-fails")).toMatchObject({
- kind: "user",
- status: "succeeded",
- });
- expect(app.tui.render(80).join("\n")).toContain(
- "Run the failing follow-up",
- );
- await app.stop();
- });
- it("refreshes history when Desktop Runtime finishes an auto-drained queued turn", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const busEvents: TuiRuntimeEvent[] = [];
- let wakeBus: (() => void) | undefined;
- const waitForNextBusEvent = (signal: AbortSignal) =>
- new Promise<void>((resolve) => {
- wakeBus = resolve;
- signal.addEventListener("abort", resolve, { once: true });
- });
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-existing",
- title: "Existing",
- workspaceDir: "/workspace",
- },
- ]);
- vi.mocked(runtime.getMessages)
- .mockResolvedValueOnce([])
- .mockResolvedValue([
- {
- id: "message-user-queued",
- turnId: "turn-queued",
- role: "user",
- content: "Runtime follow-up",
- timestamp: 100,
- },
- {
- id: "message-assistant-queued",
- turnId: "turn-queued",
- role: "assistant",
- content: "Runtime follow-up answer",
- timestamp: 101,
- },
- ]);
- vi.mocked(runtime.watchEvents).mockImplementation(
- async function* watchEvents(signal) {
- while (!signal.aborted) {
- if (busEvents.length === 0) {
- await waitForNextBusEvent(signal);
- }
- if (signal.aborted) return;
- const event = busEvents.shift();
- if (event) yield event;
- }
- },
- );
- const emit = (event: RawTuiRuntimeEvent) => {
- busEvents.push(runtimeEvent(event));
- wakeBus?.();
- wakeBus = undefined;
- };
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- app.start();
- await app.ready;
- await app.submit("/resume session-existing");
- emit({
- type: "session.start",
- timestamp: 100,
- source: "runtime",
- payload: {
- sessionId: "session-existing",
- turnId: "turn-queued",
- source: "queued-drain",
- queueItemIds: ["queue-1"],
- },
- });
- await vi.waitFor(() =>
- expect(app.tui.render(80).join("\n")).toContain("Loading"),
- );
- expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
- expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
- "session-existing",
- "turn-queued",
- expect.any(AbortSignal),
- );
- emit({
- type: "session.finish",
- timestamp: 101,
- source: "runtime",
- payload: {
- sessionId: "session-existing",
- turnId: "turn-queued",
- status: "finished",
- },
- });
- await vi.waitFor(() =>
- expect(app.transcript.snapshot()).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- kind: "assistant",
- content: "Runtime follow-up answer",
- }),
- ]),
- ),
- );
- const historyProjectionCalls = vi
- .mocked(runtime.getMessages)
- .mock.calls.filter(
- ([sessionId, limit]) =>
- sessionId === "session-existing" && limit === undefined,
- );
- expect(historyProjectionCalls).toHaveLength(2);
- await app.stop();
- });
- it("writes one structured result when an auto-drained queued turn finishes", async () => {
- const dataDir = await mkdtemp(join(tmpdir(), "mcode-queued-result-"));
- const resultPath = join(dataDir, "results.jsonl");
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const busEvents: TuiRuntimeEvent[] = [];
- let wakeBus: (() => void) | undefined;
- let durableMessages: Awaited<ReturnType<TuiRuntime["getMessages"]>> = [];
- vi.mocked(runtime.listSessions).mockResolvedValue([
- {
- sessionId: "session-existing",
- title: "Existing",
- workspaceDir: "/workspace",
- },
- ]);
- vi.mocked(runtime.getMessages).mockImplementation(
- async () => durableMessages,
- );
- const waitForBusEvent = (signal: AbortSignal) =>
- new Promise<void>((resolve) => {
- wakeBus = resolve;
- signal.addEventListener("abort", resolve, { once: true });
- });
- vi.mocked(runtime.watchEvents).mockImplementation(
- async function* watchEvents(signal) {
- while (!signal.aborted) {
- if (busEvents.length === 0) await waitForBusEvent(signal);
- if (signal.aborted) return;
- const event = busEvents.shift();
- if (event) yield event;
- }
- },
- );
- const emit = (event: RawTuiRuntimeEvent) => {
- busEvents.push(runtimeEvent(event));
- wakeBus?.();
- wakeBus = undefined;
- };
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- statusLineItems: ["build-mode"],
- automationResultPath: resultPath,
- });
- try {
- app.start();
- await app.ready;
- await app.submit("/resume session-existing");
- emit({
- type: "session.start",
- timestamp: 100,
- source: "runtime",
- payload: {
- sessionId: "session-existing",
- turnId: "turn-queued-result",
- source: "queued-drain",
- queueItemIds: ["queue-result"],
- },
- });
- await vi.waitFor(() =>
- expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
- "session-existing",
- "turn-queued-result",
- expect.any(AbortSignal),
- ),
- );
- durableMessages = [
- {
- id: "message-user-result",
- turnId: "turn-queued-result",
- role: "user",
- content: "Queued request",
- timestamp: 101,
- },
- {
- id: "message-assistant-result",
- turnId: "turn-queued-result",
- role: "assistant",
- content: "Queued structured answer",
- timestamp: 102,
- },
- ];
- emit({
- type: "session.finish",
- timestamp: 103,
- source: "runtime",
- payload: {
- sessionId: "session-existing",
- turnId: "turn-queued-result",
- status: "finished",
- },
- });
- await vi.waitFor(async () => {
- const records = (await readFile(resultPath, "utf8"))
- .trim()
- .split("\n")
- .map(JSON.parse);
- expect(records).toEqual([
- expect.objectContaining({
- type: "exec.result",
- sessionId: "session-existing",
- turnId: "turn-queued-result",
- status: "succeeded",
- answer: "Queued structured answer",
- }),
- ]);
- });
- expect(app.controller.snapshot().lastSettledTurn).toEqual({
- sessionId: "session-existing",
- turnId: "turn-queued-result",
- status: "succeeded",
- });
- } finally {
- await app.stop();
- await rm(dataDir, { recursive: true, force: true });
- }
- });
- it("settles an auto-drained follow-up once and replaces waiting state with run duration", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const busEvents: TuiRuntimeEvent[] = [];
- const queuedItems: TuiQueuedMessage[] = [];
- let wakeBus: (() => void) | undefined;
- let finishFirstTurn: (() => void) | undefined;
- let finishQueuedStream: (() => void) | undefined;
- const queuedStreamClosed = vi.fn();
- let durableMessages: Awaited<ReturnType<TuiRuntime["getMessages"]>> = [];
- const waitForNextBusEvent = (signal: AbortSignal) =>
- new Promise<void>((resolve) => {
- wakeBus = resolve;
- signal.addEventListener("abort", resolve, { once: true });
- });
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage() {
- await new Promise<void>((resolve) => {
- finishFirstTurn = resolve;
- });
- yield { type: "delta", content: "First answer" };
- yield { type: "done" };
- },
- );
- vi.mocked(runtime.watchSessionTurn).mockImplementation(
- async function* watchSessionTurn() {
- try {
- await new Promise<void>((resolve) => {
- finishQueuedStream = resolve;
- });
- yield { type: "delta", content: "Queued answer" };
- yield { type: "done" };
- } finally {
- queuedStreamClosed();
- }
- },
- );
- vi.mocked(runtime.enqueueMessage).mockImplementation(
- async (sessionId, content) => {
- const item: TuiQueuedMessage = {
- itemId: "queue-b",
- sessionId,
- status: "queued",
- content,
- };
- queuedItems.push(item);
- return { itemId: item.itemId, status: item.status, position: 1 };
- },
- );
- vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
- ...queuedItems,
- ]);
- vi.mocked(runtime.getMessages).mockImplementation(
- async () => durableMessages,
- );
- vi.mocked(runtime.watchEvents).mockImplementation(
- async function* watchEvents(signal) {
- while (!signal.aborted) {
- if (busEvents.length === 0) await waitForNextBusEvent(signal);
- if (signal.aborted) return;
- const event = busEvents.shift();
- if (event) yield event;
- }
- },
- );
- const emit = (event: RawTuiRuntimeEvent) => {
- busEvents.push(runtimeEvent(event));
- wakeBus?.();
- wakeBus = undefined;
- };
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- productFeatures: { queue: true },
- });
- app.start();
- await app.ready;
- const first = app.submit("A");
- await vi.waitFor(() =>
- expect(app.controller.snapshot().activeTurnId).toBeDefined(),
- );
- await app.submit("B");
- expect(app.tui.render(80).join("\n")).toContain(
- "Next · after current response",
- );
- expect(app.tui.render(80).join("\n")).toContain("B");
- finishFirstTurn?.();
- await first;
- const queuedItem = queuedItems[0];
- expect(queuedItem).toBeDefined();
- if (!queuedItem) throw new Error("Expected B to be queued.");
- queuedItems[0] = { ...queuedItem, status: "running" };
- emit({
- type: "session.queue.updated",
- timestamp: 200,
- source: "runtime",
- payload: {
- sessionId: "session-1",
- itemId: "queue-b",
- status: "running",
- queuedCount: 0,
- },
- });
- emit({
- type: "session.start",
- timestamp: 201,
- source: "runtime",
- payload: {
- sessionId: "session-1",
- turnId: "turn_queue_b",
- source: "queued-drain",
- queueItemIds: ["queue-b"],
- },
- });
- await vi.waitFor(() =>
- expect(app.tui.render(80).join("\n")).toContain("Loading"),
- );
- expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
- queuedItems.length = 0;
- durableMessages = [
- {
- id: "history-user-b",
- turnId: "turn_queue_b",
- role: "user",
- content: "B",
- timestamp: 202,
- },
- {
- id: "history-assistant-b",
- turnId: "turn_queue_b",
- role: "assistant",
- content: "Queued answer",
- timestamp: 203,
- },
- ];
- finishQueuedStream?.();
- await vi.waitFor(() => expect(queuedStreamClosed).toHaveBeenCalledOnce());
- emit({
- type: "session.finish",
- timestamp: 3_201,
- source: "runtime",
- payload: {
- sessionId: "session-1",
- turnId: "turn_queue_b",
- status: "finished",
- },
- });
- await vi.waitFor(() =>
- expect(
- app.transcript
- .snapshot()
- .filter((cell) => cell.content === "Queued answer"),
- ).toHaveLength(1),
- );
- await vi.waitFor(() =>
- expect(app.transcript.get("turn-duration:turn_queue_b")).toMatchObject({
- status: "succeeded",
- durationMs: 3_000,
- }),
- );
- const settledUi = app.tui.render(80).join("\n");
- expect(settledUi).toContain("Completed in 3s");
- expect(settledUi.indexOf("Completed in 3s")).toBeGreaterThan(
- settledUi.indexOf("Queued answer"),
- );
- expect(settledUi).not.toContain("message waiting");
- expect(settledUi).not.toContain("Next · after current response");
- await app.stop();
- });
- it("records submitted drafts in editor history", async () => {
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal,
- version: "0.1.0",
- workspaceDir: "/workspace",
- });
- await app.ready;
- app.editor.setText("Remember this draft");
- app.editor.handleInput("\r");
- await vi.waitFor(() =>
- expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
- );
- app.editor.handleInput("\u001b[A");
- expect(app.editor.getText()).toBe("Remember this draft");
- });
- it("continues sending and switching sessions when draft cleanup fails", async () => {
- const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-warning-"));
- const runtime = createRuntime();
- const app = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- dataDir,
- workspaceDir: "/workspace",
- });
- const flush = vi.spyOn(TuiDraftRecovery.prototype, "flush");
- try {
- await app.ready;
- flush.mockRejectedValue(
- new TuiDraftRecoveryError("cleanup", new Error("deletion denied")),
- );
- app.editor.setText("hello");
- app.editor.handleInput("\r");
- await vi.waitFor(() =>
- expect(
- app.transcript.snapshot().filter((cell) => cell.kind === "warning"),
- ).toHaveLength(1),
- );
- const warnings = app.transcript
- .snapshot()
- .filter((cell) => cell.kind === "warning");
- expect(warnings[0]?.content).toContain(
- composerText("draftCleanupNextStep"),
- );
- expect(warnings[0]?.content).not.toContain(
- composerText("draftRecoveryUnavailable"),
- );
- expect(warnings[0]?.content).toContain("deletion denied");
- await vi.waitFor(() =>
- expect(runtime.sendMessage).toHaveBeenCalledOnce(),
- );
- await vi.waitFor(() =>
- expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
- );
- await expect(app.openSession("session-2")).resolves.toBeUndefined();
- expect(app.controller.snapshot().session?.sessionId).toBe("session-2");
- app.editor.setText("after switching");
- app.editor.handleInput("\r");
- await vi.waitFor(() =>
- expect(runtime.sendMessage).toHaveBeenCalledTimes(2),
- );
- await expect(app.stop()).resolves.toBeUndefined();
- } finally {
- await app.stop();
- flush.mockRestore();
- await rm(dataDir, { recursive: true, force: true });
- }
- });
- it("does not read or restore a persisted Draft during TUI startup", async () => {
- const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-"));
- try {
- const first = createTuiApp({
- runtime: createRuntime(),
- terminal: new FakeTerminal(),
- version: "0.1.0",
- dataDir,
- workspaceDir: "/workspace/recovery",
- });
- await first.ready;
- first.editor.setText("/exit");
- await first.stop();
- const loadDraft = vi.spyOn(TuiDraftRecovery.prototype, "load");
- const restored = createTuiApp({
- runtime: createRuntime(),
- terminal: new FakeTerminal(),
- version: "0.1.0",
- dataDir,
- workspaceDir: "/workspace/recovery",
- });
- await restored.ready;
- expect(loadDraft).not.toHaveBeenCalled();
- expect(restored.editor.getText()).toBe("");
- expect(restored.tui.render(80).join("\n")).not.toContain(
- "Draft restored",
- );
- loadDraft.mockRestore();
- restored.editor.setText("");
- await restored.stop();
- } finally {
- await rm(dataDir, { recursive: true, force: true });
- }
- });
- it("does not resume a persisted Draft during startup when login recovery is enabled", async () => {
- const dataDir = await mkdtemp(join(tmpdir(), "mcode-login-restart-draft-"));
- try {
- const first = createTuiApp({
- runtime: createRuntime(),
- terminal: new FakeTerminal(),
- version: "0.1.0",
- dataDir,
- workspaceDir: "/workspace/login-recovery",
- });
- await first.ready;
- first.editor.setText("send after Global login");
- await first.stop();
- const restored = createTuiApp({
- runtime: createRuntime(),
- terminal: new FakeTerminal(),
- version: "0.1.0",
- dataDir,
- workspaceDir: "/workspace/login-recovery",
- resumeDraftAfterLogin: true,
- });
- await restored.ready;
- restored.start();
- expect(restored.editor.getText()).toBe("");
- expect(restored.getSurface()).toBe("welcome");
- expect(restored.tui.render(80).join("\n")).toContain(
- "Tips for getting started",
- );
- await restored.stop();
- } finally {
- await rm(dataDir, { recursive: true, force: true });
- }
- });
- it("keeps the submitted Draft recoverable when shutdown wins before Runtime admission", async () => {
- const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-pending-draft-"));
- try {
- const runtime = createRuntime();
- vi.spyOn(runtime, "sendMessage").mockImplementation(
- async function* sendMessage(
- _req: SendMessageReq,
- signal?: AbortSignal,
- ) {
- yield* [];
- await new Promise<void>((_resolve, reject) => {
- signal?.addEventListener(
- "abort",
- () => reject(new Error("admission aborted")),
- {
- once: true,
- },
- );
- });
- throw new Error("unreachable");
- },
- );
- const first = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- dataDir,
- workspaceDir: "/workspace/pending-recovery",
- });
- await first.ready;
- first.editor.setText("recover me until Runtime accepts");
- await new Promise((resolve) => setTimeout(resolve, 300));
- first.editor.handleInput("\r");
- await vi.waitFor(() =>
- expect(runtime.sendMessage).toHaveBeenCalledOnce(),
- );
- await first.stop();
- const restored = createTuiApp({
- runtime: createRuntime(),
- terminal: new FakeTerminal(),
- version: "0.1.0",
- dataDir,
- workspaceDir: "/workspace/pending-recovery",
- });
- await restored.ready;
- await restored.openSession("session-1");
- expect(restored.editor.getText()).toBe(
- "recover me until Runtime accepts",
- );
- const rendered = restored.tui.render(80).join("\n");
- expect(rendered).toContain("recover me until Runtime accepts");
- expect(rendered).not.toContain("Message kept under Failed");
- await restored.stop();
- } finally {
- await rm(dataDir, { recursive: true, force: true });
- }
- });
- it("does not restore a submitted Draft after Runtime accepts the turn", async () => {
- const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-accepted-draft-"));
- try {
- const runtime = createRuntime();
- vi.mocked(runtime.sendMessage).mockImplementation(
- async function* sendMessage(
- _req: SendMessageReq,
- signal?: AbortSignal,
- ) {
- await new Promise<void>((resolve) => {
- signal?.addEventListener("abort", resolve, { once: true });
- });
- yield { type: "done" };
- },
- );
- const first = createTuiApp({
- runtime,
- terminal: new FakeTerminal(),
- version: "0.1.0",
- dataDir,
- workspaceDir: "/workspace/accepted-recovery",
- });
- await first.ready;
- first.editor.setText("already accepted by Runtime");
- await new Promise((resolve) => setTimeout(resolve, 300));
- first.editor.handleInput("\r");
- await vi.waitFor(() =>
- expect(runtime.sendMessage).toHaveBeenCalledOnce(),
- );
- await first.stop();
- const restored = createTuiApp({
- runtime: createRuntime(),
- terminal: new FakeTerminal(),
- version: "0.1.0",
- dataDir,
- workspaceDir: "/workspace/accepted-recovery",
- });
- await restored.ready;
- expect(restored.editor.getText()).toBe("");
- await restored.stop();
- } finally {
- await rm(dataDir, { recursive: true, force: true });
- }
- });
- it("serializes rapid Session switches without mixing their Drafts", async () => {
- const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-"));
- try {
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal: new FakeTerminal(),
- version: "0.1.0",
- dataDir,
- workspaceDir: "/workspace/recovery",
- });
- await app.ready;
- await app.openSession("session-a");
- app.editor.setText("Draft for Session A");
- await app.openSession("session-b");
- app.editor.setText("Draft for Session B");
- await Promise.all([
- app.openSession("session-a"),
- app.openSession("session-b"),
- ]);
- expect(app.controller.snapshot().session?.sessionId).toBe("session-b");
- expect(app.editor.getText()).toBe("Draft for Session B");
- await app.openSession("session-a");
- expect(app.editor.getText()).toBe("Draft for Session A");
- await app.openSession("session-b");
- expect(app.editor.getText()).toBe("Draft for Session B");
- await app.stop();
- } finally {
- await rm(dataDir, { recursive: true, force: true });
- }
- });
- it("moves to the new-session Draft namespace after archiving the current Session", async () => {
- const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-"));
- try {
- const app = createTuiApp({
- runtime: createRuntime(),
- terminal: new FakeTerminal(),
- version: "0.1.0",
- dataDir,
- workspaceDir: "/workspace/recovery",
- });
- await app.ready;
- await app.openSession("session-a");
- app.editor.setText("Archived Session Draft");
- await app.submit("/archive");
- app.editor.setText("Fresh Session Draft");
- await app.openSession("session-a");
- expect(app.editor.getText()).toBe("Archived Session Draft");
- await app.submit("/new");
- expect(app.editor.getText()).toBe("Fresh Session Draft");
- await app.stop();
- } finally {
- await rm(dataDir, { recursive: true, force: true });
- }
- });
- });
- describe("interactive CLI model startup", () => {
- it.each([
- [
- "new with prompt",
- ["-m", "custom_provider:relay/vendor/model#thinking", "hello"],
- "session-1",
- true,
- ],
- [
- "new without prompt",
- ["--model=custom_provider:relay/vendor/model#thinking"],
- "session-1",
- false,
- ],
- [
- "explicit session",
- ["--session", "existing", "--model", "custom_provider:relay/vendor/model#thinking", "hello"],
- "existing",
- true,
- ],
- [
- "continue",
- ["--continue", "--model", "custom_provider:relay/vendor/model#thinking", "hello"],
- "existing",
- true,
- ],
- [
- "missing session",
- ["--session", "missing", "-m", "custom_provider:relay/vendor/model#thinking", "hello"],
- "missing",
- false,
- ],
- [
- "empty continue",
- ["--continue", "-m", "custom_provider:relay/vendor/model#thinking", "hello"],
- "existing",
- false,
- ],
- ["invalid provider", ["--model", "missing/model", "hello"], "session-1", false],
- ["invalid model", ["--model", "custom_provider:relay/missing", "hello"], "session-1", false],
- ] as const)(
- "routes %s through launch, hydration and submission",
- async (_name, args, sessionId, hasPrompt) => {
- const dataDir = await mkdtemp(join(tmpdir(), "mcode-model-startup-"));
- const terminal = new FakeTerminal();
- const runtime = createRuntime();
- runtime.listBackgroundTasks = vi.fn(async () => []);
- const models = new Map<string, { providerId: string; modelId: string; variant?: string }>();
- const requested = {
- providerId: "custom_provider:relay",
- modelId: "vendor/model",
- variant: "thinking",
- };
- const existing = { sessionId: "existing", workspaceDir: "/workspace", updatedAt: 10 };
- vi.mocked(runtime.listSessions).mockResolvedValue([existing]);
- vi.mocked(runtime.listSessionPage).mockResolvedValue({
- sessions: [existing],
- hasMore: false,
- });
- vi.mocked(runtime.getSession).mockImplementation(async (id) => ({
- sessionId: id,
- workspaceDir: "/workspace",
- model: models.get(id),
- }));
- const failedResume = _name === "missing session" || _name === "empty continue";
- if (_name === "missing session")
- vi.mocked(runtime.getSession).mockRejectedValue(new Error("Session not found"));
- if (_name === "empty continue") vi.mocked(runtime.listSessions).mockResolvedValue([]);
- runtime.selectModel = vi.fn(async () => true);
- runtime.selectSessionModel = vi.fn(async (model, id) => {
- if (model.providerId !== requested.providerId || model.modelId !== requested.modelId) {
- throw new Error("Unknown provider or model");
- }
- models.set(id, model);
- return true;
- });
- vi.mocked(runtime.listModels).mockImplementation(async (id) => [
- { ...requested, name: "Startup model", selected: Boolean(id && models.has(id)) },
- ]);
- // A global managed default needs login; the selected BYOK Session does not.
- vi.mocked(runtime.getAccountStatus).mockImplementation(async (id) => ({
- status: id && models.has(id) ? "ready" : "needs-login",
- modelSource: id && models.has(id) ? "byok" : "token-plan",
- managedTokenPresent: false,
- warnings: [],
- }));
- const sentModels: unknown[] = [];
- vi.mocked(runtime.sendMessage).mockImplementation(async function* (request) {
- sentModels.push(models.get(request.id));
- yield { type: "delta", content: "offline reply" };
- yield { type: "done" };
- });
- const invalid = _name.startsWith("invalid");
- const stderr = vi.fn((_text: string, callback?: () => void) => callback?.());
- const processRef = {
- title: "test",
- argv: ["node", "cli.js", ...args],
- env: {},
- versions: { node: "24.2.0" },
- stdout: {
- destroyed: false,
- writableEnded: false,
- write: vi.fn((_text: string, cb?: () => void) => cb?.()),
- },
- stderr: { destroyed: false, writableEnded: false, write: stderr },
- exit: vi.fn(),
- exitCode: 0,
- };
- let app: ReturnType<typeof createTuiApp> | undefined;
- const running = runTuiCli({
- processRef,
- configureNetworkProxy: () => undefined,
- launchTui: (input) =>
- launchTui(
- { ...input, dataDir, terminal, workspaceDir: "/workspace" },
- {
- createObservability,
- readTelemetryEnabled: () => false,
- installProcessGuards: () => () => undefined,
- loadRuntimeLifecycle: async () => ({
- createTuiRuntime: async () => ({ adapter: runtime }) as never,
- shutdownTuiRuntime: async () => false,
- }),
- loadUpdateApplication: async () =>
- ({ inspect: async () => ({ status: "up-to-date" }) }) as never,
- createApp: (options) => {
- app = createTuiApp({ ...options, productFeatures: { queue: false } });
- return app;
- },
- writeExitMessage: () => undefined,
- },
- ),
- });
- try {
- if (invalid) {
- await running;
- expect(processRef.exitCode).toBe(1);
- expect(stderr.mock.calls.flat().join(" ")).toContain("Unknown provider or model");
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- } else if (failedResume) {
- await vi.waitFor(() => expect(app?.editor.disableSubmit).toBe(false));
- expect(runtime.selectSessionModel).not.toHaveBeenCalled();
- expect(runtime.createSession).not.toHaveBeenCalled();
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- } else {
- await vi.waitFor(() => {
- expect(app?.editor.disableSubmit).toBe(false);
- expect(app?.controller.snapshot().session?.model).toEqual(requested);
- if (hasPrompt) expect(sentModels).toEqual([requested]);
- });
- expect(runtime.selectSessionModel).toHaveBeenCalledWith(requested, sessionId);
- expect(app?.controller.snapshot().account?.modelSource).toBe("byok");
- if (sessionId === "existing") expect(runtime.createSession).not.toHaveBeenCalled();
- if (!hasPrompt) {
- expect(runtime.sendMessage).not.toHaveBeenCalled();
- await app?.submit("later prompt");
- expect(sentModels).toEqual([requested]);
- }
- await vi.waitFor(() => expect(app?.controller.snapshot().status).toBe("idle"));
- await app?.submit("/new");
- expect(app?.controller.snapshot().session).toBeUndefined();
- expect(runtime.selectSessionModel).toHaveBeenCalledOnce();
- }
- expect(runtime.selectModel).not.toHaveBeenCalled();
- } finally {
- await app?.stop();
- await running;
- await rm(dataDir, { recursive: true, force: true });
- }
- },
- );
- });
- describe("interactive model argument contract", () => {
- function program() {
- const launch = vi.fn(async () => undefined);
- const command = createTuiProgram({
- version: "test",
- launchTui: launch,
- runExec: vi.fn(),
- runLogin: vi.fn(),
- runLogout: vi.fn(),
- runUpdate: vi.fn(),
- })
- .exitOverride()
- .configureOutput({ writeErr: () => undefined });
- return { command, launch };
- }
- it.each(["-m", "--model"])("rejects missing values for %s", async (flag) => {
- const { command, launch } = program();
- await expect(command.parseAsync([flag], { from: "user" })).rejects.toThrow();
- expect(launch).not.toHaveBeenCalled();
- });
- it.each(["", "bare-model", "provider/", "/model", "provider/model#"])(
- "rejects malformed model %j before launch",
- async (model) => {
- const { command, launch } = program();
- await expect(command.parseAsync(["--model", model], { from: "user" })).rejects.toThrow(
- "--model must use provider/model",
- );
- expect(launch).not.toHaveBeenCalled();
- },
- );
- it("rejects a model with an untargeted Session picker", async () => {
- const { command, launch } = program();
- await expect(
- command.parseAsync(["--session", "--model", "provider/model"], { from: "user" }),
- ).rejects.toThrow("requires a Session id");
- expect(launch).not.toHaveBeenCalled();
- });
- it("retains the default launch contract without a model", async () => {
- const { command, launch } = program();
- await command.parseAsync(["hello"], { from: "user" });
- expect(launch).toHaveBeenCalledWith({ initialPrompt: "hello" });
- });
- it.each(["-m", "--model"])("scans startup environment after %s values", (flag) => {
- expect(
- resolveTuiStartupEnvironmentOption([flag, "provider/model", "--env", "staging"], true),
- ).toBe("staging");
- expect(() =>
- resolveTuiStartupEnvironmentOption([flag, "provider/model", "--env", "prod"], false),
- ).toThrow("only available");
- expect(
- resolveTuiStartupEnvironmentOption(
- [flag, "provider/model", "exec", "--env", "staging"],
- true,
- ),
- ).toBeUndefined();
- });
- });
|