tui-app.test.ts 413 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418
  1. import { describe, expect, it, vi } from "vitest";
  2. import { mkdtemp, readFile, rm, writeFile, mkdir } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import type { TerminalCapabilities } from "../../src/tui/platform/terminal-capabilities.js";
  6. import {
  7. TuiAltScreen,
  8. VStack,
  9. type Terminal,
  10. } from "../../src/tui/engine/public.js";
  11. import { createTuiProgram } from "../../src/cli/program.js";
  12. import { resolveTuiStartupEnvironmentOption } from "../../src/cli/environment.js";
  13. import { runTuiCli } from "../../src/cli/main.js";
  14. import { launchTui } from "../../src/tui/launcher.js";
  15. import { createTuiApp } from "../../src/tui/app.js";
  16. import type {
  17. TuiModel,
  18. TuiQuestionnaireRequest,
  19. TuiQueuedMessage,
  20. TuiRuntimeEvent,
  21. TuiRuntime,
  22. TuiSessionForkPort,
  23. TuiStreamEvent,
  24. } from "../../src/runtime/port.js";
  25. import {
  26. normalizeTuiRuntimeEvent,
  27. type RawTuiRuntimeEvent,
  28. } from "../../src/runtime/event-normalizer.js";
  29. import type { SendMessageReq } from "@mavis/local-runtime-v2/cli-service";
  30. import type { TuiObservability } from "../../src/observability/local-observability.js";
  31. import type { McodeAuthProgress } from "../../src/auth/application.js";
  32. import { formatTuiShortcut } from "../../src/tui/shell/shortcut-labels.js";
  33. import { createTuiHostKeybindings } from "../../src/tui/shell/keybindings.js";
  34. import { stripAnsi } from "../../src/tui/rendering/text.js";
  35. import {
  36. TuiDraftRecovery,
  37. TuiDraftRecoveryError,
  38. } from "../../src/tui/features/composer/draft-recovery.js";
  39. import { composerText } from "../../src/tui/features/composer/copy.js";
  40. import type {
  41. McodeBusinessEvent,
  42. McodeBusinessTelemetry,
  43. } from "../../src/analytics/business-telemetry.js";
  44. import { VirtualTerminalScreen } from "../helpers/virtual-terminal.js";
  45. import { TuiFailure } from "../../src/failure.js";
  46. const runtimeEvent = (event: RawTuiRuntimeEvent): TuiRuntimeEvent =>
  47. normalizeTuiRuntimeEvent(event);
  48. function planReviewEventRequest(id: string) {
  49. return {
  50. schemaVersion: 2,
  51. id,
  52. mode: "plan",
  53. modePayload: {
  54. planReview: {
  55. markdown: "# Frozen plan\n\nImplement and verify the change.",
  56. path: "/history/session-1/artifacts/plan.md",
  57. },
  58. },
  59. presentation: {
  60. replaceComposer: true,
  61. showProgress: true,
  62. allowBackNavigation: true,
  63. },
  64. steps: [
  65. {
  66. id: "plan-review",
  67. question: "Approve?",
  68. selectionMode: "single",
  69. options: [{ id: "approve", label: "Approve" }],
  70. allowOther: true,
  71. required: true,
  72. },
  73. ],
  74. } as const;
  75. }
  76. function planEntryEventRequest(id: string) {
  77. return {
  78. schemaVersion: 2,
  79. id,
  80. mode: "plan",
  81. presentation: {
  82. replaceComposer: true,
  83. showProgress: true,
  84. allowBackNavigation: true,
  85. },
  86. steps: [
  87. {
  88. id: "plan-enter",
  89. question: "Enter Plan Mode for this task?",
  90. selectionMode: "single",
  91. options: [
  92. { id: "confirm", label: "Confirm" },
  93. { id: "decline", label: "Decline" },
  94. ],
  95. allowOther: true,
  96. otherPlaceholder: "Others...",
  97. required: true,
  98. },
  99. ],
  100. } as const;
  101. }
  102. function createObservability(): TuiObservability {
  103. return {
  104. recordStartup: vi.fn(),
  105. recordAccess: vi.fn(),
  106. recordEventStream: vi.fn(),
  107. recordTerminal: vi.fn(),
  108. recordProcessStop: vi.fn(),
  109. observeRender: vi.fn(),
  110. snapshot: vi.fn(() => ({
  111. filePath: "/tmp/mcode-observability.jsonl",
  112. eventCounts: {
  113. startup: 0,
  114. runtimeAccess: 0,
  115. eventStream: 0,
  116. terminal: 0,
  117. },
  118. accessSources: {},
  119. reconnects: 0,
  120. render: {
  121. frames: 0,
  122. averageDurationMs: 0,
  123. maxDurationMs: 0,
  124. p95DurationMs: 0,
  125. },
  126. })),
  127. flush: vi.fn(async () => undefined),
  128. };
  129. }
  130. class FakeTerminal implements Terminal {
  131. columns = 80;
  132. rows = 18;
  133. kittyProtocolActive = false;
  134. started = false;
  135. stopped = false;
  136. startCount = 0;
  137. stopCount = 0;
  138. drainCount = 0;
  139. title = "";
  140. titleUpdates: string[] = [];
  141. mouseTracking = false;
  142. mouseTrackingUpdates: boolean[] = [];
  143. writes: string[] = [];
  144. input?: (data: string) => void;
  145. start(onInput: (data: string) => void): void {
  146. this.started = true;
  147. this.stopped = false;
  148. this.startCount += 1;
  149. this.input = onInput;
  150. }
  151. stop(): void {
  152. this.stopped = true;
  153. this.stopCount += 1;
  154. }
  155. drainInput(): Promise<void> {
  156. this.drainCount += 1;
  157. return Promise.resolve();
  158. }
  159. write(data: string): void {
  160. this.writes.push(data);
  161. }
  162. moveBy(): void {}
  163. hideCursor(): void {}
  164. showCursor(): void {}
  165. clearLine(): void {}
  166. clearFromCursor(): void {}
  167. clearScreen(): void {}
  168. setProgress(): void {}
  169. setMouseTracking(enabled: boolean): void {
  170. this.mouseTracking = enabled;
  171. this.mouseTrackingUpdates.push(enabled);
  172. }
  173. setTitle(title: string): void {
  174. this.title = title;
  175. this.titleUpdates.push(title);
  176. }
  177. }
  178. function renderTerminalViewport(
  179. app: ReturnType<typeof createTuiApp>,
  180. terminal: FakeTerminal,
  181. ): string {
  182. app.tui.renderNow();
  183. const screen = new VirtualTerminalScreen(terminal.columns, terminal.rows);
  184. try {
  185. for (const write of terminal.writes) screen.feed(write);
  186. return screen.viewportText();
  187. } finally {
  188. screen.dispose();
  189. }
  190. }
  191. function createRuntime(): TuiRuntime {
  192. const abortSession = vi.fn(async () => true);
  193. let currentGoal: Awaited<ReturnType<TuiRuntime["getGoal"]>>;
  194. let createdSession:
  195. | {
  196. sessionId: string;
  197. title: string;
  198. workspaceDir: string;
  199. interactionMode?: "plan";
  200. }
  201. | undefined;
  202. const runtime: TuiRuntime = {
  203. createSession: vi.fn(async () => {
  204. createdSession = {
  205. sessionId: "session-1",
  206. title: "New session",
  207. workspaceDir: "/workspace",
  208. };
  209. return { ...createdSession };
  210. }),
  211. listSessions: vi.fn(async () => []),
  212. listSessionPage: vi.fn(async () => ({
  213. sessions: [],
  214. hasMore: false,
  215. })),
  216. getSession: vi.fn(async (sessionId: string) =>
  217. createdSession?.sessionId === sessionId
  218. ? { ...createdSession }
  219. : {
  220. sessionId,
  221. title: "Existing session",
  222. workspaceDir: "/workspace",
  223. },
  224. ),
  225. getMessages: vi.fn(async () => []),
  226. listMessagePage: vi.fn(async () => ({ messages: [], hasMore: false })),
  227. getSessionForkOptions: vi.fn(async () => ({
  228. canFork: true,
  229. worktreeVisible: false,
  230. worktreeEligible: false,
  231. })),
  232. forkSession: vi.fn(async () => ({
  233. session: {
  234. sessionId: "session-fork",
  235. parentSessionId: "session-1",
  236. title: "New session (fork 1)",
  237. workspaceDir: "/workspace",
  238. },
  239. })),
  240. getWorkspaceGitMetadata: vi.fn(async () => ({
  241. isGitRepo: false,
  242. branch: "",
  243. detached: false,
  244. isWorktree: false,
  245. })),
  246. renameSession: vi.fn(async (sessionId: string, title: string) => ({
  247. sessionId,
  248. title,
  249. workspaceDir: "/workspace",
  250. })),
  251. archiveSession: vi.fn(async () => undefined),
  252. listSessionInputSummaries: vi.fn(async () => []),
  253. getSessionRewindPreview: vi.fn(async () => ({ turns: [] })),
  254. rewindSession: vi.fn(async () => ({ rewound: true })),
  255. editSessionMessage: vi.fn(async () => ({
  256. rewound: true,
  257. turnId: "turn-edit-1",
  258. userMessageId: "msg-user-v1-edited",
  259. })),
  260. isGoalEnabled: vi.fn(() => true),
  261. getGoal: vi.fn(async () => currentGoal),
  262. createGoal: vi.fn(async ({ sessionId, objective, attachments }) => {
  263. currentGoal = {
  264. goalId: "goal-1",
  265. sessionId,
  266. objective,
  267. status: "active",
  268. createdAt: 10,
  269. updatedAt: 10,
  270. tokensUsed: 0,
  271. turnsUsed: 0,
  272. timeUsedSeconds: 0,
  273. tokenBudget: null,
  274. statusReason: null,
  275. hasKickoffAttachments: Boolean(attachments?.length),
  276. };
  277. return currentGoal;
  278. }),
  279. patchGoal: vi.fn(async (_sessionId, patch) => {
  280. if (!currentGoal) throw new Error("Goal not found");
  281. currentGoal = {
  282. ...currentGoal,
  283. ...patch,
  284. updatedAt: currentGoal.updatedAt + 1,
  285. };
  286. return currentGoal;
  287. }),
  288. clearGoal: vi.fn(async () => {
  289. const existed = Boolean(currentGoal);
  290. currentGoal = undefined;
  291. return existed;
  292. }),
  293. getInstructionSources: vi.fn(async () => []),
  294. getRuntimeDiagnostics: vi.fn(async () => ({
  295. status: "ok",
  296. surface: "cli-standalone",
  297. runtimeMode: "clean",
  298. runtimeOwnerKind: "cli",
  299. runtimeOwnerId: "minimax-code",
  300. dataDir: "/home/dev/.minimax",
  301. configPath: "/home/dev/.minimax/config.yaml",
  302. configPresent: true,
  303. authCachePresent: true,
  304. defaultModel: "minimax/MiniMax-M2.7",
  305. providerId: "minimax",
  306. modelId: "MiniMax-M2.7",
  307. authMode: "managed-login",
  308. authModeSource: "explicit",
  309. managedTokenPresent: true,
  310. apiKeyPresent: false,
  311. customProviderCount: 0,
  312. warnings: [],
  313. })),
  314. prepareFeedback: vi.fn(async ({ description, sessionId }) => ({
  315. schemaVersion: 1 as const,
  316. draftId: "feedback-draft-1",
  317. description,
  318. diagnostics: [
  319. { label: "Client", value: "mcode 0.1.0" },
  320. { label: "Runtime", value: "clean · cli" },
  321. { label: "Session", value: sessionId ?? "not included" },
  322. ],
  323. included: ["redacted feedback description"],
  324. excluded: ["credentials and tokens", "conversation prompts and messages"],
  325. expiresAtMs: Date.now() + 60_000,
  326. })),
  327. submitFeedback: vi.fn(async () => ({
  328. schemaVersion: 1 as const,
  329. ticketId: "ticket-1",
  330. status: "processing" as const,
  331. createdAtMs: Date.now(),
  332. })),
  333. cancelFeedback: vi.fn(async () => true),
  334. runDailyCheckin: vi.fn(async () => ({
  335. status: "claimed" as const,
  336. dayNo: 2,
  337. points: 20,
  338. expireAtMs: 1_800_000_000_000,
  339. panel: {
  340. scene: 2,
  341. days: Array.from({ length: 7 }, (_, index) => ({
  342. day_no: index + 1,
  343. points: (index + 1) * 10,
  344. status: index <= 1 ? 3 : 1,
  345. is_today: index === 1,
  346. })),
  347. },
  348. })),
  349. getAccountStatus: vi.fn(async () => ({
  350. status: "ready",
  351. defaultModel: "minimax/MiniMax-M2.7",
  352. providerId: "minimax",
  353. modelId: "MiniMax-M2.7",
  354. authMode: "managed-login",
  355. managedTokenPresent: true,
  356. warnings: [],
  357. })),
  358. listProviderPresets: vi.fn(async () => []),
  359. getCodexOAuthStatus: vi.fn(async () => ({
  360. state: "hidden" as const,
  361. providerId: "openai-codex" as const,
  362. })),
  363. startCodexOAuthLogin: vi.fn(async () => ({
  364. state: "hidden" as const,
  365. providerId: "openai-codex" as const,
  366. })),
  367. getPermissionMode: vi.fn(async () => "auto" as const),
  368. setPermissionMode: vi.fn(async (mode) => mode),
  369. getPlanModeCapabilities: vi.fn(async () => ({ entryEnabled: true })),
  370. getPendingQuestionnaire: vi.fn(async () => undefined),
  371. getLatestPlanReview: vi.fn(async () => undefined),
  372. replyQuestionnaire: vi.fn(async () => true),
  373. dismissQuestionnaire: vi.fn(async () => true),
  374. listPendingPermissions: vi.fn(async () => []),
  375. replyPermission: vi.fn(async () => true),
  376. listModels: vi.fn(async () => [
  377. {
  378. providerId: "minimax",
  379. modelId: "MiniMax-M2.7",
  380. displayName: "MiniMax M2.7",
  381. providerKind: "minimax-managed",
  382. selected: true,
  383. },
  384. ]),
  385. selectModel: vi.fn(async () => true),
  386. getSessionUsage: vi.fn(async () => ({
  387. summary: {
  388. inputTokens: 100,
  389. outputTokens: 20,
  390. totalTokens: 120,
  391. turns: 1,
  392. },
  393. rows: [],
  394. })),
  395. requestCompaction: vi.fn(async () => ({
  396. success: true,
  397. sessionId: "session-1",
  398. compactionId: "compact-1",
  399. messagesBefore: 12,
  400. messagesAfter: 4,
  401. tokensBefore: 4000,
  402. tokensAfter: 1200,
  403. })),
  404. getContextSnapshot: vi.fn(async () => ({ status: "empty" as const })),
  405. getActiveRun: vi.fn(async (sessionId: string) => ({
  406. schemaVersion: 1 as const,
  407. sessionId,
  408. state: "idle" as const,
  409. actions: { steer: false },
  410. })),
  411. getDelegationSnapshot: vi.fn(async (rootSessionId: string) => ({
  412. schemaVersion: 1 as const,
  413. rootSessionId,
  414. members: [],
  415. })),
  416. stopDelegation: vi.fn(async (rootSessionId: string) => ({
  417. schemaVersion: 1 as const,
  418. rootSessionId,
  419. rootStopped: await abortSession({ id: rootSessionId }),
  420. stoppedSessionIds: [],
  421. activeSessionIds: [],
  422. failedSessionIds: [],
  423. })),
  424. steer: vi.fn(async (input) => ({
  425. turnId: input.requestedTurnId ?? "turn-steer",
  426. mode: input.requestedTurnId
  427. ? ("steered" as const)
  428. : ("activated" as const),
  429. ...(input.requestedTurnId
  430. ? {}
  431. : {
  432. completion:
  433. (async function* completion(): AsyncGenerator<TuiStreamEvent> {
  434. yield { type: "done", turnId: "turn-steer" };
  435. })(),
  436. }),
  437. })),
  438. listSkills: vi.fn(async () => ({
  439. skills: [
  440. {
  441. name: "docs",
  442. displayName: "Docs",
  443. description: "Read project docs",
  444. enabled: true,
  445. sourceKind: "builtin",
  446. },
  447. ],
  448. hasMore: false,
  449. })),
  450. inspectProjectMcp: vi.fn(async () => undefined),
  451. listMcpServers: vi.fn(async () => [
  452. {
  453. name: "browser",
  454. enabled: true,
  455. transport: "stdio",
  456. description: "Browser tools",
  457. configJson: '{"env":{"TOKEN":"hidden"}}',
  458. },
  459. ]),
  460. listQueuedMessages: vi.fn(async () => []),
  461. getQueueSnapshot: vi.fn(async (sessionId: string) => {
  462. const items = await runtime.listQueuedMessages(sessionId);
  463. return {
  464. items,
  465. paused: items.some((item) => item.status === "paused"),
  466. pendingCount: items.length,
  467. };
  468. }),
  469. continueQueue: vi.fn(async () => undefined),
  470. steerQueuedMessage: vi.fn(async (_sessionId: string, itemId: string) => ({
  471. queueItemId: itemId,
  472. turnId: "turn-steered-queue",
  473. })),
  474. enqueueMessage: vi.fn(async () => ({
  475. itemId: "queue-1",
  476. status: "queued",
  477. position: 1,
  478. })),
  479. updateQueuedMessageContent: vi.fn(async () => undefined),
  480. deleteQueuedMessage: vi.fn(async () => undefined),
  481. watchEvents: vi.fn(async function* watchEvents(signal) {
  482. await new Promise<void>((resolve) => {
  483. signal.addEventListener("abort", resolve, { once: true });
  484. });
  485. for (const event of [] as TuiRuntimeEvent[]) yield event;
  486. }),
  487. watchSessionTurn: vi.fn(async function* watchSessionTurn() {}),
  488. sendMessage: vi.fn(
  489. async function* sendMessage(request): AsyncGenerator<TuiStreamEvent> {
  490. if (createdSession?.sessionId === request.id) {
  491. if (request.clientIntent === "plan-entry")
  492. createdSession.interactionMode = "plan";
  493. if (request.clientIntent === "plan-exit")
  494. delete createdSession.interactionMode;
  495. }
  496. yield { type: "delta", content: "Hello from the Agent" };
  497. yield { type: "done" };
  498. },
  499. ),
  500. abortSession,
  501. };
  502. return runtime;
  503. }
  504. describe("createTuiApp", () => {
  505. it.each(["regular", "fullscreen"] as const)(
  506. "configures /statusline from terminal input and reopens the saved selection in %s mode",
  507. async (tuiMode) => {
  508. const terminal = new FakeTerminal();
  509. const runtime = createRuntime();
  510. const persistStatusLineItems = vi.fn(async () => undefined);
  511. const app = createTuiApp({
  512. runtime,
  513. terminal,
  514. version: "test",
  515. workspaceDir: "/workspace",
  516. tuiMode,
  517. statusLineItems: ["current-dir"],
  518. persistStatusLineItems,
  519. });
  520. try {
  521. app.start();
  522. await app.ready;
  523. app.editor.setText("/statusline");
  524. terminal.input?.("\r");
  525. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  526. expect(stripAnsi(app.interaction.render(80).join("\n"))).toContain(
  527. "[x] current-dir",
  528. );
  529. terminal.input?.(" ");
  530. terminal.input?.("\r");
  531. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  532. expect(persistStatusLineItems).toHaveBeenCalledWith([]);
  533. app.editor.setText("/statusline");
  534. terminal.input?.("\r");
  535. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  536. expect(stripAnsi(app.interaction.render(80).join("\n"))).toContain(
  537. "[ ] current-dir",
  538. );
  539. terminal.input?.("\x1b");
  540. expect(app.interaction.isActive()).toBe(false);
  541. expect(persistStatusLineItems).toHaveBeenCalledOnce();
  542. expect(runtime.sendMessage).not.toHaveBeenCalled();
  543. } finally {
  544. await app.stop();
  545. }
  546. },
  547. );
  548. it.each([
  549. ["regular", false],
  550. ["regular", true],
  551. ["fullscreen", false],
  552. ["fullscreen", true],
  553. ] as const)(
  554. "runs ls unchanged in %s mode after empty-prefix Tab: %s",
  555. async (tuiMode, pressTab) => {
  556. const directory = await mkdtemp(join(tmpdir(), "tui-ls-enter-"));
  557. await mkdir(join(directory, "aaa-directory"));
  558. await writeFile(join(directory, "root-only.txt"), "root");
  559. const terminal = new FakeTerminal();
  560. const runtime = createRuntime();
  561. const app = createTuiApp({
  562. runtime,
  563. terminal,
  564. version: "0.1.0",
  565. workspaceDir: directory,
  566. tuiMode,
  567. });
  568. try {
  569. app.start();
  570. await app.ready;
  571. app.editor.setText("!ls");
  572. terminal.input?.(" ");
  573. expect(stripAnsi(app.editor.render(100).join("\n"))).not.toContain(
  574. "aaa-directory/",
  575. );
  576. if (pressTab) {
  577. terminal.input?.("\t");
  578. await vi.waitFor(() =>
  579. expect(stripAnsi(app.editor.render(100).join("\n"))).toContain(
  580. "aaa-directory/",
  581. ),
  582. );
  583. }
  584. expect(app.editor.getText()).toBe("!ls ");
  585. terminal.input?.("\r");
  586. await vi.waitFor(
  587. () =>
  588. expect(
  589. app.transcript.snapshot().find((cell) => cell.kind === "shell")
  590. ?.status,
  591. ).toBe("succeeded"),
  592. { timeout: 5000 },
  593. );
  594. expect(
  595. app.transcript.snapshot().find((cell) => cell.kind === "shell"),
  596. ).toMatchObject({
  597. title: "! ls",
  598. content: expect.stringContaining("root-only.txt"),
  599. });
  600. expect(runtime.sendMessage).not.toHaveBeenCalled();
  601. } finally {
  602. await app.stop();
  603. await rm(directory, { recursive: true, force: true });
  604. }
  605. },
  606. );
  607. it.each(["regular", "fullscreen"] as const)(
  608. "completes a shell path from terminal input in %s mode before executing",
  609. async (tuiMode) => {
  610. const directory = await mkdtemp(
  611. join(tmpdir(), "tui-shell-completion-app-"),
  612. );
  613. await writeFile(
  614. join(directory, "report file.txt"),
  615. "completed-shell-output",
  616. );
  617. const terminal = new FakeTerminal();
  618. const runtime = createRuntime();
  619. const app = createTuiApp({
  620. runtime,
  621. terminal,
  622. version: "0.1.0",
  623. workspaceDir: directory,
  624. tuiMode,
  625. });
  626. try {
  627. app.start();
  628. await app.ready;
  629. app.editor.setText(
  630. process.platform === "win32" ? "!Get-Content " : "!cat ",
  631. );
  632. for (const char of "rep") terminal.input?.(char);
  633. expect(app.editor.getText()).toBe(
  634. process.platform === "win32" ? "!Get-Content rep" : "!cat rep",
  635. );
  636. terminal.input?.("\t");
  637. await vi.waitFor(() =>
  638. expect(app.editor.getText()).toBe(
  639. process.platform === "win32"
  640. ? "!Get-Content report` file.txt "
  641. : "!cat report\\ file.txt ",
  642. ),
  643. );
  644. expect(
  645. app.transcript
  646. .snapshot()
  647. .some((cell) => cell.id.startsWith("local:bash:")),
  648. ).toBe(false);
  649. terminal.input?.("\r");
  650. await vi.waitFor(
  651. () =>
  652. expect(
  653. app.transcript
  654. .snapshot()
  655. .some(
  656. (cell) =>
  657. cell.id.startsWith("local:bash:") &&
  658. cell.status === "succeeded" &&
  659. cell.content.includes("completed-shell-output"),
  660. ),
  661. ).toBe(true),
  662. { timeout: 5000 },
  663. );
  664. expect(runtime.sendMessage).not.toHaveBeenCalled();
  665. } finally {
  666. await app.stop();
  667. await rm(directory, { recursive: true, force: true });
  668. }
  669. },
  670. );
  671. it("runs an editor ! command locally and carries its result into the next model message", async () => {
  672. const directory = await mkdtemp(join(tmpdir(), "tui-bash-app-"));
  673. const runtime = createRuntime();
  674. const app = createTuiApp({
  675. runtime,
  676. terminal: new FakeTerminal(),
  677. version: "0.1.0",
  678. workspaceDir: directory,
  679. });
  680. try {
  681. await app.ready;
  682. app.editor.setText(
  683. process.platform === "win32"
  684. ? "!Write-Output shell-result"
  685. : "!printf shell-result",
  686. );
  687. app.editor.submit();
  688. await vi.waitFor(
  689. () =>
  690. expect(
  691. app.transcript
  692. .snapshot()
  693. .some(
  694. (cell) =>
  695. cell.id.startsWith("local:bash:") &&
  696. cell.status === "succeeded",
  697. ),
  698. ).toBe(true),
  699. { timeout: 5000 },
  700. );
  701. expect(runtime.sendMessage).not.toHaveBeenCalled();
  702. expect(
  703. app.transcript
  704. .snapshot()
  705. .find((cell) => cell.id.startsWith("local:bash:"))?.content,
  706. ).toContain("shell-result");
  707. expect(stripAnsi(app.tui.render(100).join("\n"))).toContain(
  708. "shell-result",
  709. );
  710. await app.submit("Explain the output");
  711. expect(runtime.sendMessage).toHaveBeenCalledWith(
  712. expect.objectContaining({
  713. content: expect.stringContaining("shell-result"),
  714. }),
  715. expect.anything(),
  716. );
  717. } finally {
  718. await app.stop();
  719. await rm(directory, { recursive: true, force: true });
  720. }
  721. });
  722. it("shows shell output before the command exits and drains it when the app stops", async () => {
  723. const directory = await mkdtemp(join(tmpdir(), "tui-bash-stream-"));
  724. const app = createTuiApp({
  725. runtime: createRuntime(),
  726. terminal: new FakeTerminal(),
  727. version: "0.1.0",
  728. workspaceDir: directory,
  729. });
  730. try {
  731. await app.ready;
  732. const running = app.submit(
  733. process.platform === "win32"
  734. ? "!Write-Output streamed-result; Start-Sleep -Seconds 30"
  735. : "!printf streamed-result; sleep 30",
  736. );
  737. await vi.waitFor(
  738. () =>
  739. expect(
  740. app.transcript
  741. .snapshot()
  742. .some(
  743. (cell) =>
  744. cell.status === "running" &&
  745. cell.content.includes("streamed-result"),
  746. ),
  747. ).toBe(true),
  748. { timeout: 5000 },
  749. );
  750. expect(stripAnsi(app.tui.render(100).join("\n"))).toContain(
  751. "streamed-result",
  752. );
  753. await app.stop();
  754. await running;
  755. expect(
  756. app.transcript
  757. .snapshot()
  758. .find((cell) => cell.id.startsWith("local:bash:"))?.status,
  759. ).toBe("cancelled");
  760. } finally {
  761. await app.stop();
  762. await rm(directory, { recursive: true, force: true });
  763. }
  764. });
  765. it("continues a restored paused Queue from its manager without sending a new message", async () => {
  766. const terminal = new FakeTerminal();
  767. const runtime = createRuntime();
  768. let paused = true;
  769. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  770. {
  771. itemId: "paused-follow-up",
  772. sessionId: "session-1",
  773. status: paused ? "paused" : "queued",
  774. content: "Existing queued work",
  775. },
  776. ]);
  777. vi.mocked(runtime.continueQueue).mockImplementation(async () => {
  778. paused = false;
  779. });
  780. const app = createTuiApp({
  781. runtime,
  782. terminal,
  783. version: "test",
  784. workspaceDir: "/workspace",
  785. productFeatures: { queue: true },
  786. });
  787. app.start();
  788. try {
  789. await app.ready;
  790. await app.openSession("session-1");
  791. await app.submit("/queue");
  792. expect(app.tui.render(120).join("\n")).toContain("c continue queue");
  793. terminal.input?.("c");
  794. await vi.waitFor(() =>
  795. expect(runtime.continueQueue).toHaveBeenCalledWith("session-1"),
  796. );
  797. await vi.waitFor(() =>
  798. expect(app.tui.render(120).join("\n")).toContain("Queue continued."),
  799. );
  800. expect(runtime.sendMessage).not.toHaveBeenCalled();
  801. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  802. expect(runtime.deleteQueuedMessage).not.toHaveBeenCalled();
  803. } finally {
  804. await app.stop();
  805. }
  806. });
  807. it.each(["keep", "clear", "cancel-enter", "cancel-escape"] as const)(
  808. "recovers a restored paused Queue when sending a message: %s",
  809. async (decision) => {
  810. const dataDir = await mkdtemp(join(tmpdir(), "tui-paused-queue-draft-"));
  811. const terminal = new FakeTerminal();
  812. const runtime = createRuntime();
  813. let items: TuiQueuedMessage[] = [
  814. {
  815. itemId: "paused-follow-up",
  816. sessionId: "session-1",
  817. status: "paused",
  818. content: "Existing queued work",
  819. },
  820. ];
  821. let emitQueueChange:
  822. | ((event: TuiRuntimeEvent | undefined) => void)
  823. | undefined;
  824. vi.mocked(runtime.watchEvents).mockImplementation(
  825. async function* (signal) {
  826. const event = await new Promise<TuiRuntimeEvent | undefined>(
  827. (resolve) => {
  828. emitQueueChange = resolve;
  829. signal.addEventListener("abort", () => resolve(undefined), {
  830. once: true,
  831. });
  832. },
  833. );
  834. if (!event || signal.aborted) return;
  835. yield event;
  836. if (!signal.aborted) {
  837. await new Promise<void>((resolve) => {
  838. signal.addEventListener("abort", () => resolve(), { once: true });
  839. });
  840. }
  841. },
  842. );
  843. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  844. ...items,
  845. ]);
  846. vi.mocked(runtime.sendMessage).mockImplementation(
  847. async function* (request, _signal, options) {
  848. if (!options?.pausedQueueAction) {
  849. throw new TuiFailure("runtime", "Queue paused", {
  850. code: "local_session_queue_paused",
  851. });
  852. }
  853. items =
  854. options.pausedQueueAction === "clear"
  855. ? []
  856. : items.map((item) => ({ ...item, status: "queued" }));
  857. emitQueueChange?.({
  858. type: "session.queue.updated",
  859. sessionId: "session-1",
  860. source: "runtime-v2",
  861. timestampMs: Date.now(),
  862. });
  863. yield { type: "done", turnId: request.turnId };
  864. },
  865. );
  866. const appOptions = {
  867. runtime,
  868. terminal,
  869. version: "test",
  870. dataDir,
  871. workspaceDir: "/workspace",
  872. productFeatures: { queue: true },
  873. };
  874. let app = createTuiApp(appOptions);
  875. app.start();
  876. try {
  877. await app.ready;
  878. await app.openSession("session-1");
  879. await vi.waitFor(() => expect(emitQueueChange).toBeTypeOf("function"));
  880. await vi.waitFor(() =>
  881. expect(app.tui.render(120).join("\n")).toContain(
  882. "Existing queued work",
  883. ),
  884. );
  885. terminal.input?.("Resume safely");
  886. terminal.input?.("\r");
  887. await vi.waitFor(() =>
  888. expect(app.tui.render(120).join("\n")).toContain("Keep my draft"),
  889. );
  890. const cancelled = decision.startsWith("cancel");
  891. if (decision === "cancel-escape") terminal.input?.("\u001b");
  892. else {
  893. if (decision === "clear") terminal.input?.("\u001b[B");
  894. if (decision === "cancel-enter") {
  895. terminal.input?.("\u001b[B");
  896. terminal.input?.("\u001b[B");
  897. }
  898. terminal.input?.("\r");
  899. }
  900. await vi.waitFor(() =>
  901. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  902. );
  903. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  904. if (cancelled) {
  905. await vi.waitFor(() =>
  906. expect(app.editor.getText()).toBe("Resume safely"),
  907. );
  908. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  909. expect(runtime.continueQueue).not.toHaveBeenCalled();
  910. expect(runtime.deleteQueuedMessage).not.toHaveBeenCalled();
  911. expect(
  912. app.transcript.snapshot().filter((cell) => cell.kind === "user"),
  913. ).toEqual([]);
  914. expect(
  915. app.transcript.snapshot().filter((cell) => cell.kind === "error"),
  916. ).toEqual([]);
  917. expect(app.tui.render(120).join("\n")).toContain("Queue paused");
  918. expect(app.tui.render(120).join("\n")).not.toContain("Keep my draft");
  919. await vi.waitFor(async () => {
  920. const recovered = await new TuiDraftRecovery({
  921. dataDir,
  922. workspaceDir: "/workspace",
  923. sessionKey: "session-1",
  924. }).load();
  925. expect(recovered?.editor.text).toBe("Resume safely");
  926. expect(recovered?.retrySubmissions ?? []).toEqual([]);
  927. });
  928. app.editor.setText("Edited draft");
  929. await app.stop();
  930. app = createTuiApp(appOptions);
  931. app.start();
  932. await app.ready;
  933. await app.openSession("session-1");
  934. await vi.waitFor(() =>
  935. expect(app.editor.getText()).toBe("Edited draft"),
  936. );
  937. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  938. terminal.input?.("\r");
  939. await vi.waitFor(() =>
  940. expect(app.tui.render(120).join("\n")).toContain("Keep my draft"),
  941. );
  942. terminal.input?.("\r");
  943. await vi.waitFor(() =>
  944. expect(runtime.sendMessage).toHaveBeenCalledTimes(3),
  945. );
  946. await vi.waitFor(() =>
  947. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  948. );
  949. expect(
  950. vi.mocked(runtime.sendMessage).mock.calls[2]?.[0],
  951. ).toMatchObject({
  952. content: "Edited draft",
  953. });
  954. expect(vi.mocked(runtime.sendMessage).mock.calls[2]?.[2]).toEqual({
  955. pausedQueueAction: "keep",
  956. });
  957. await vi.waitFor(() =>
  958. expect(app.tui.render(120).join("\n")).not.toContain(
  959. "Queue paused",
  960. ),
  961. );
  962. expect(app.editor.getText()).toBe("");
  963. expect(app.tui.render(120).join("\n")).toContain(
  964. "Existing queued work",
  965. );
  966. } else {
  967. expect(runtime.sendMessage).toHaveBeenCalledTimes(2);
  968. expect(
  969. vi.mocked(runtime.sendMessage).mock.calls[1]?.[0],
  970. ).toMatchObject({
  971. content: "Resume safely",
  972. });
  973. expect(vi.mocked(runtime.sendMessage).mock.calls[1]?.[2]).toEqual({
  974. pausedQueueAction: decision,
  975. });
  976. await vi.waitFor(() =>
  977. expect(app.tui.render(120).join("\n")).not.toContain(
  978. "Queue paused",
  979. ),
  980. );
  981. const rendered = app.tui.render(120).join("\n");
  982. if (decision === "clear")
  983. expect(rendered).not.toContain("Existing queued work");
  984. else expect(rendered).toContain("Existing queued work");
  985. }
  986. } finally {
  987. await app.stop();
  988. await rm(dataDir, { recursive: true, force: true });
  989. }
  990. },
  991. );
  992. it.each([
  993. ["plan-entry", "keep"],
  994. ["plan-entry", "clear"],
  995. ["plan-entry", "cancel"],
  996. ["plan-entry", "busy"],
  997. ["plan-exit", "keep"],
  998. ["plan-exit", "clear"],
  999. ["plan-exit", "cancel"],
  1000. ["plan-exit", "busy"],
  1001. ] as const)(
  1002. "recovers a paused Queue with %s and decision %s",
  1003. async (clientIntent, decision) => {
  1004. const terminal = new FakeTerminal();
  1005. const runtime = createRuntime();
  1006. let interactionMode: "plan" | undefined =
  1007. clientIntent === "plan-exit" ? "plan" : undefined;
  1008. let rejectRecovery = decision === "busy";
  1009. vi.mocked(runtime.getSession).mockImplementation(async () => ({
  1010. sessionId: "session-1",
  1011. interactionMode,
  1012. }));
  1013. vi.mocked(runtime.listQueuedMessages).mockResolvedValue([
  1014. {
  1015. itemId: "paused-work",
  1016. sessionId: "session-1",
  1017. status: "paused",
  1018. content: "Existing work",
  1019. },
  1020. ]);
  1021. vi.mocked(runtime.sendMessage).mockImplementation(
  1022. async function* (request, _signal, options) {
  1023. if (!options?.pausedQueueAction || rejectRecovery) {
  1024. throw new TuiFailure("runtime", "Admission rejected", {
  1025. code: options?.pausedQueueAction
  1026. ? "local_session_busy"
  1027. : "local_session_queue_paused",
  1028. });
  1029. }
  1030. interactionMode =
  1031. request.clientIntent === "plan-entry" ? "plan" : undefined;
  1032. yield { type: "done", turnId: request.turnId };
  1033. },
  1034. );
  1035. const app = createTuiApp({
  1036. runtime,
  1037. terminal,
  1038. version: "test",
  1039. workspaceDir: "/workspace",
  1040. productFeatures: { queue: true },
  1041. });
  1042. app.start();
  1043. try {
  1044. await app.ready;
  1045. await app.openSession("session-1");
  1046. await app.submit(
  1047. clientIntent === "plan-entry" ? "/plan on" : "/plan off",
  1048. );
  1049. terminal.input?.("Change mode and continue");
  1050. terminal.input?.("\r");
  1051. await vi.waitFor(() =>
  1052. expect(app.tui.render(120).join("\n")).toContain("Keep my draft"),
  1053. );
  1054. if (decision === "clear" || decision === "cancel")
  1055. terminal.input?.("\u001b[B");
  1056. if (decision === "cancel") terminal.input?.("\u001b[B");
  1057. terminal.input?.("\r");
  1058. await vi.waitFor(() =>
  1059. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  1060. );
  1061. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  1062. if (decision === "cancel" || decision === "busy") {
  1063. await vi.waitFor(() =>
  1064. expect(app.editor.getText()).toBe("Change mode and continue"),
  1065. );
  1066. expect(interactionMode === "plan").toBe(clientIntent === "plan-exit");
  1067. rejectRecovery = false;
  1068. app.editor.setText("Edited mode instruction");
  1069. terminal.input?.("\r");
  1070. await vi.waitFor(() =>
  1071. expect(app.tui.render(120).join("\n")).toContain("Keep my draft"),
  1072. );
  1073. terminal.input?.("\r");
  1074. await vi.waitFor(() =>
  1075. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  1076. );
  1077. }
  1078. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  1079. expect.objectContaining({ clientIntent }),
  1080. expect.any(AbortSignal),
  1081. { pausedQueueAction: decision === "clear" ? "clear" : "keep" },
  1082. );
  1083. expect(interactionMode === "plan").toBe(clientIntent === "plan-entry");
  1084. expect(app.editor.getText()).toBe("");
  1085. } finally {
  1086. await app.stop();
  1087. }
  1088. },
  1089. );
  1090. it("shows the MCode prompt in an empty Composer and hides it after input", async () => {
  1091. const app = createTuiApp({
  1092. runtime: createRuntime(),
  1093. terminal: new FakeTerminal(),
  1094. version: "0.1.0",
  1095. workspaceDir: "/workspace",
  1096. });
  1097. try {
  1098. app.start();
  1099. await app.ready;
  1100. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  1101. "Ask Mcode to do anything",
  1102. );
  1103. app.editor.handleInput("R");
  1104. expect(stripAnsi(app.tui.render(80).join("\n"))).not.toContain(
  1105. "Ask Mcode to do anything",
  1106. );
  1107. expect(app.editor.getText()).toBe("R");
  1108. } finally {
  1109. await app.stop();
  1110. }
  1111. });
  1112. it("copies the last Assistant reply to the client clipboard over SSH", async () => {
  1113. vi.stubEnv("SSH_CONNECTION", "10.0.0.1 50100 10.0.0.2 22");
  1114. vi.stubEnv("SSH_TTY", "/dev/pts/1");
  1115. Object.defineProperty(process.stdin, "isTTY", {
  1116. configurable: true,
  1117. value: true,
  1118. });
  1119. Object.defineProperty(process.stdout, "isTTY", {
  1120. configurable: true,
  1121. value: true,
  1122. });
  1123. const terminal = new FakeTerminal();
  1124. let app: ReturnType<typeof createTuiApp> | undefined;
  1125. try {
  1126. app = createTuiApp({
  1127. runtime: createRuntime(),
  1128. terminal,
  1129. version: "0.1.0",
  1130. workspaceDir: "/workspace",
  1131. });
  1132. app.start();
  1133. await app.ready;
  1134. await app.submit("Say hello");
  1135. await app.submit("/copy");
  1136. expect(terminal.writes).toContain(
  1137. "\u001B]52;c;SGVsbG8gZnJvbSB0aGUgQWdlbnQ=\u0007",
  1138. );
  1139. } finally {
  1140. await app?.stop();
  1141. Reflect.deleteProperty(process.stdin, "isTTY");
  1142. Reflect.deleteProperty(process.stdout, "isTTY");
  1143. vi.unstubAllEnvs();
  1144. }
  1145. });
  1146. it("runs /goal through Runtime ownership and renders the active Goal above the Composer", async () => {
  1147. const runtime = createRuntime();
  1148. const app = createTuiApp({
  1149. runtime,
  1150. terminal: new FakeTerminal(),
  1151. version: "0.1.0",
  1152. workspaceDir: "/workspace",
  1153. });
  1154. app.start();
  1155. await app.ready;
  1156. await app.submit("/goal Ship TUI Goal support");
  1157. expect(runtime.createSession).toHaveBeenCalledOnce();
  1158. expect(runtime.createGoal).toHaveBeenCalledWith({
  1159. sessionId: "session-1",
  1160. objective: "Ship TUI Goal support",
  1161. });
  1162. expect(runtime.sendMessage).not.toHaveBeenCalled();
  1163. expect(app.surfaceHost.render(100).join("\n")).toContain("Goal · Active");
  1164. expect(app.surfaceHost.render(100).join("\n")).toContain(
  1165. "Ship TUI Goal support",
  1166. );
  1167. await app.submit("/goal pause");
  1168. expect(runtime.patchGoal).toHaveBeenCalledWith("session-1", {
  1169. status: "paused",
  1170. });
  1171. expect(app.surfaceHost.render(100).join("\n")).toContain("Goal · Paused");
  1172. await app.stop();
  1173. });
  1174. it("wires complete chat and autocomplete business events into the TUI surface", async () => {
  1175. const events: McodeBusinessEvent[] = [];
  1176. const businessTelemetry: McodeBusinessTelemetry = {
  1177. track: (event, properties) =>
  1178. events.push({ event, properties } as McodeBusinessEvent),
  1179. flush: async () => undefined,
  1180. };
  1181. const app = createTuiApp({
  1182. runtime: createRuntime(),
  1183. terminal: new FakeTerminal(),
  1184. version: "0.1.0",
  1185. workspaceDir: "/workspace/agent-archon",
  1186. businessTelemetry,
  1187. });
  1188. await app.ready;
  1189. await app.submit("First prompt");
  1190. await app.submit("Second prompt");
  1191. for (const character of "/he") app.editor.handleInput(character);
  1192. await vi.waitFor(() =>
  1193. expect(
  1194. events.some((item) => item.event === "slash_command_menu_view"),
  1195. ).toBe(true),
  1196. );
  1197. app.editor.handleInput("\r");
  1198. expect(events.filter((item) => item.event === "chat_send")).toEqual([
  1199. {
  1200. event: "chat_send",
  1201. properties: {
  1202. chat_type: "chat",
  1203. is_first_message: 1,
  1204. is_attachment: "text",
  1205. },
  1206. },
  1207. {
  1208. event: "chat_send",
  1209. properties: {
  1210. chat_type: "chat",
  1211. is_first_message: 0,
  1212. is_attachment: "text",
  1213. },
  1214. },
  1215. ]);
  1216. expect(events).toContainEqual({
  1217. event: "slash_command_click",
  1218. properties: {
  1219. chat_type: "chat",
  1220. command_type: "other",
  1221. },
  1222. });
  1223. await app.stop();
  1224. });
  1225. it("releases the terminal on suspend and reconciles Runtime state after resume", async () => {
  1226. const terminal = new FakeTerminal();
  1227. const runtime = createRuntime();
  1228. const requestProcessSuspend = vi.fn();
  1229. vi.mocked(runtime.watchEvents).mockImplementation(
  1230. async function* watchEvents(signal) {
  1231. await new Promise<void>((resolve) => {
  1232. signal.addEventListener("abort", resolve, { once: true });
  1233. });
  1234. yield* [];
  1235. },
  1236. );
  1237. const app = createTuiApp({
  1238. runtime,
  1239. terminal,
  1240. version: "0.1.0",
  1241. workspaceDir: "/workspace",
  1242. requestProcessSuspend,
  1243. });
  1244. app.start();
  1245. await app.ready;
  1246. await app.openSession("session-1");
  1247. await vi.waitFor(() => expect(runtime.watchEvents).toHaveBeenCalledOnce());
  1248. terminal.input?.("\x1a");
  1249. expect(requestProcessSuspend).toHaveBeenCalledOnce();
  1250. await app.suspend();
  1251. expect(terminal.stopCount).toBe(1);
  1252. expect(app.controller.snapshot().status).not.toBe("error");
  1253. await app.resume();
  1254. expect(terminal.startCount).toBe(2);
  1255. await vi.waitFor(() =>
  1256. expect(runtime.watchEvents).toHaveBeenCalledTimes(2),
  1257. );
  1258. expect(runtime.getActiveRun).toHaveBeenCalled();
  1259. await app.stop();
  1260. });
  1261. it.each(["regular", "fullscreen"] as const)(
  1262. "restores %s Composer input after Ctrl+G returns from the external editor",
  1263. async (tuiMode) => {
  1264. const terminal = new FakeTerminal();
  1265. const stopTerminal = vi.spyOn(terminal, "stop");
  1266. const startTerminal = vi.spyOn(terminal, "start");
  1267. const editDraftInExternalEditor = vi.fn(
  1268. async () => "edited in the external editor",
  1269. );
  1270. const app = createTuiApp({
  1271. runtime: createRuntime(),
  1272. terminal,
  1273. version: "0.1.0",
  1274. workspaceDir: "/workspace",
  1275. tuiMode,
  1276. externalEditorCommand: "code --wait",
  1277. editDraftInExternalEditor,
  1278. });
  1279. app.start();
  1280. await app.ready;
  1281. const longPaste = Array.from(
  1282. { length: 12 },
  1283. (_, index) => `line ${String(index + 1)}`,
  1284. ).join("\n");
  1285. terminal.input?.(`\x1b[200~${longPaste}\x1b[201~`);
  1286. expect(app.editor.getText()).toBe("[paste #1 +12 lines]");
  1287. terminal.input?.("\x07");
  1288. await vi.waitFor(() =>
  1289. expect(editDraftInExternalEditor).toHaveBeenCalledOnce(),
  1290. );
  1291. expect(editDraftInExternalEditor).toHaveBeenCalledWith({
  1292. command: "code --wait",
  1293. draft: longPaste,
  1294. cwd: "/workspace",
  1295. });
  1296. await vi.waitFor(() =>
  1297. expect(app.editor.getText()).toBe("edited in the external editor"),
  1298. );
  1299. expect(stopTerminal).toHaveBeenCalledOnce();
  1300. expect(startTerminal).toHaveBeenCalledTimes(2);
  1301. terminal.input?.("!");
  1302. expect(app.editor.getText()).toBe("edited in the external editor!");
  1303. await app.stop();
  1304. },
  1305. );
  1306. it("loads Runtime-owned Git context into the status rail without blocking startup", async () => {
  1307. const runtime = createRuntime();
  1308. vi.mocked(runtime.getWorkspaceGitMetadata).mockResolvedValue({
  1309. isGitRepo: true,
  1310. branch: "feat/status-context",
  1311. detached: false,
  1312. isWorktree: true,
  1313. });
  1314. const app = createTuiApp({
  1315. runtime,
  1316. terminal: new FakeTerminal(),
  1317. version: "0.1.0",
  1318. workspaceDir: "/Users/dev/github/agent-archon",
  1319. homeDir: "/Users/dev",
  1320. });
  1321. await app.ready;
  1322. await vi.waitFor(() => {
  1323. expect(runtime.getWorkspaceGitMetadata).toHaveBeenCalledWith(
  1324. "/Users/dev/github/agent-archon",
  1325. );
  1326. const rendered = app.tui.render(120).join("\n");
  1327. expect(rendered).toContain("~/github/agent-archon");
  1328. expect(rendered).toContain("⎇ feat/status-context · worktree");
  1329. });
  1330. await app.stop();
  1331. });
  1332. it("keeps Pi clear-on-shrink disabled for the inline product by default", async () => {
  1333. const app = createTuiApp({
  1334. runtime: createRuntime(),
  1335. terminal: new FakeTerminal(),
  1336. version: "0.1.0",
  1337. workspaceDir: "/workspace",
  1338. });
  1339. expect(app.tui.getClearOnShrink()).toBe(false);
  1340. await app.ready;
  1341. await app.stop();
  1342. });
  1343. it("drains Pi terminal input before restoring the terminal on shutdown", async () => {
  1344. const terminal = new FakeTerminal();
  1345. const drainInput = vi.spyOn(terminal, "drainInput");
  1346. const stopTerminal = vi.spyOn(terminal, "stop");
  1347. const app = createTuiApp({
  1348. runtime: createRuntime(),
  1349. terminal,
  1350. version: "0.1.0",
  1351. workspaceDir: "/workspace",
  1352. });
  1353. app.start();
  1354. await app.ready;
  1355. await app.stop();
  1356. expect(drainInput).toHaveBeenCalledWith(1000);
  1357. expect(stopTerminal).toHaveBeenCalledOnce();
  1358. expect(drainInput.mock.invocationCallOrder[0]).toBeLessThan(
  1359. stopTerminal.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
  1360. );
  1361. });
  1362. it("shows the Runtime initialization error text when the Session catalog is unavailable", async () => {
  1363. const runtime = createRuntime();
  1364. vi.mocked(runtime.listSessions).mockRejectedValue(
  1365. new Error("Unable to connect to the Runtime on port 1234"),
  1366. );
  1367. const app = createTuiApp({
  1368. runtime,
  1369. terminal: new FakeTerminal(),
  1370. version: "0.1.0",
  1371. workspaceDir: "/workspace",
  1372. });
  1373. await app.ready;
  1374. expect(app.controller.snapshot()).toMatchObject({
  1375. status: "error",
  1376. error:
  1377. "Couldn't load sessions: Unable to connect to the Runtime on port 1234. Retry.",
  1378. sessions: [],
  1379. });
  1380. expect(app.tui.render(80).join("\n")).toContain(
  1381. "Error · Couldn't load sessions:",
  1382. );
  1383. await app.stop();
  1384. });
  1385. it("shows an available update as a dedicated startup notice", async () => {
  1386. const terminal = new FakeTerminal();
  1387. const checkForUpdate = vi.fn(async () => ({ latestVersion: "1.2.4" }));
  1388. const app = createTuiApp({
  1389. runtime: createRuntime(),
  1390. terminal,
  1391. version: "1.2.3",
  1392. workspaceDir: "/workspace",
  1393. checkForUpdate,
  1394. });
  1395. app.start();
  1396. await app.ready;
  1397. await vi.waitFor(() => {
  1398. expect(terminal.writes.join("")).toContain(
  1399. "A new version of MCode is available",
  1400. );
  1401. });
  1402. const rendered = terminal.writes.join("");
  1403. expect(checkForUpdate).toHaveBeenCalledTimes(1);
  1404. expect(rendered).toContain("Run '/update' to install MCode 1.2.4");
  1405. await app.submit("Start working");
  1406. expect(app.getSurface()).toBe("conversation");
  1407. expect(app.tui.render(80).join("\n")).not.toContain(
  1408. "A new version of MCode is available",
  1409. );
  1410. await app.submit("/new");
  1411. expect(app.getSurface()).toBe("welcome");
  1412. expect(app.tui.render(80).join("\n")).toContain(
  1413. "A new version of MCode is available",
  1414. );
  1415. await app.stop();
  1416. });
  1417. it("keeps the Welcome handoff out of the primary hint and submits it on Ctrl+U", async () => {
  1418. const terminal = new FakeTerminal();
  1419. const runtime = createRuntime();
  1420. vi.mocked(runtime.listSkills).mockResolvedValue({
  1421. skills: [
  1422. {
  1423. name: "resume-codex",
  1424. displayName: "Resume Codex",
  1425. description: "Continue a Codex session",
  1426. enabled: true,
  1427. sourceKind: "builtin",
  1428. },
  1429. ],
  1430. hasMore: false,
  1431. });
  1432. const sessionId = "01a02373-25ae-76a1-880c-9253ba939cdc";
  1433. const findRecentCodexSession = vi.fn(async () => ({
  1434. sessionId,
  1435. updatedAtMs: Date.now() - 60_000,
  1436. source: "cli" as const,
  1437. }));
  1438. const app = createTuiApp({
  1439. runtime,
  1440. terminal,
  1441. version: "0.1.0",
  1442. workspaceDir: "/workspace",
  1443. findRecentCodexSession,
  1444. });
  1445. app.start();
  1446. await app.ready;
  1447. await vi.waitFor(() =>
  1448. expect(findRecentCodexSession).toHaveBeenCalledOnce(),
  1449. );
  1450. const welcome = app.tui.render(100).join("\n");
  1451. expect(welcome).toContain("Start");
  1452. expect(welcome).not.toContain("Coming from Codex?");
  1453. terminal.input?.("\x15");
  1454. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
  1455. expect(runtime.sendMessage).toHaveBeenCalledWith(
  1456. expect.objectContaining({
  1457. id: "session-1",
  1458. content: `/resume-codex ${sessionId}`,
  1459. }),
  1460. expect.any(AbortSignal),
  1461. );
  1462. expect(app.tui.render(100).join("\n")).not.toContain("Coming from Codex?");
  1463. await app.stop();
  1464. });
  1465. it("invalidates an in-flight Codex handoff scan after the user starts typing", async () => {
  1466. const terminal = new FakeTerminal();
  1467. const runtime = createRuntime();
  1468. vi.mocked(runtime.listSkills).mockResolvedValue({
  1469. skills: [
  1470. {
  1471. name: "resume-codex",
  1472. displayName: "Resume Codex",
  1473. description: "Continue a Codex session",
  1474. enabled: true,
  1475. sourceKind: "builtin",
  1476. },
  1477. ],
  1478. hasMore: false,
  1479. });
  1480. let resolveRecent:
  1481. | ((session: {
  1482. sessionId: string;
  1483. updatedAtMs: number;
  1484. source: "cli";
  1485. }) => void)
  1486. | undefined;
  1487. const findRecentCodexSession = vi.fn(
  1488. async () =>
  1489. await new Promise<{
  1490. sessionId: string;
  1491. updatedAtMs: number;
  1492. source: "cli";
  1493. }>((resolve) => {
  1494. resolveRecent = resolve;
  1495. }),
  1496. );
  1497. const app = createTuiApp({
  1498. runtime,
  1499. terminal,
  1500. version: "0.1.0",
  1501. workspaceDir: "/workspace",
  1502. findRecentCodexSession,
  1503. });
  1504. app.start();
  1505. terminal.input?.("x");
  1506. await vi.waitFor(() =>
  1507. expect(findRecentCodexSession).toHaveBeenCalledOnce(),
  1508. );
  1509. resolveRecent?.({
  1510. sessionId: "01a02373-25ae-76a1-880c-9253ba939cdc",
  1511. updatedAtMs: Date.now(),
  1512. source: "cli",
  1513. });
  1514. await Promise.resolve();
  1515. await Promise.resolve();
  1516. expect(app.editor.getText()).toBe("x");
  1517. expect(app.tui.render(100).join("\n")).not.toContain("Coming from Codex?");
  1518. await app.stop();
  1519. });
  1520. it("does not inspect Codex storage when the resume Skill is unavailable", async () => {
  1521. const runtime = createRuntime();
  1522. const findRecentCodexSession = vi.fn(async () => ({
  1523. sessionId: "01a02373-25ae-76a1-880c-9253ba939cdc",
  1524. updatedAtMs: Date.now(),
  1525. source: "cli" as const,
  1526. }));
  1527. const app = createTuiApp({
  1528. runtime,
  1529. terminal: new FakeTerminal(),
  1530. version: "0.1.0",
  1531. workspaceDir: "/workspace",
  1532. findRecentCodexSession,
  1533. });
  1534. app.start();
  1535. await app.ready;
  1536. await vi.waitFor(() => expect(runtime.listSkills).toHaveBeenCalledOnce());
  1537. await Promise.resolve();
  1538. expect(findRecentCodexSession).not.toHaveBeenCalled();
  1539. expect(app.tui.render(100).join("\n")).not.toContain("Coming from Codex?");
  1540. await app.stop();
  1541. });
  1542. it.each(["unsupported result", "blank version", "rejected check"] as const)(
  1543. "keeps a %s startup update result out of the notice and transcript",
  1544. async (scenario) => {
  1545. const terminal = new FakeTerminal();
  1546. const checkForUpdate = vi.fn(async () => {
  1547. if (scenario === "rejected check")
  1548. throw new Error("registry unavailable");
  1549. if (scenario === "unsupported result") return undefined;
  1550. return { latestVersion: " " };
  1551. });
  1552. const app = createTuiApp({
  1553. runtime: createRuntime(),
  1554. terminal,
  1555. version: "1.2.3",
  1556. workspaceDir: "/workspace",
  1557. checkForUpdate,
  1558. });
  1559. app.start();
  1560. await app.ready;
  1561. await vi.waitFor(() => expect(checkForUpdate).toHaveBeenCalledOnce());
  1562. await app.stop();
  1563. expect(terminal.writes.join("")).not.toContain(
  1564. "A new version of MCode is available",
  1565. );
  1566. expect(
  1567. app.transcript.snapshot().filter((cell) => cell.kind === "error"),
  1568. ).toEqual([]);
  1569. },
  1570. );
  1571. it("routes /update through the in-process update confirmation flow", async () => {
  1572. const plan = {
  1573. kind: "available" as const,
  1574. source: "managed-installer" as const,
  1575. currentVersion: "1.2.3",
  1576. latestVersion: "1.2.4",
  1577. channel: "stable" as const,
  1578. };
  1579. const inspectUpdate = vi.fn(async () => plan);
  1580. const applyUpdate = vi.fn(async () => ({
  1581. applied: true,
  1582. message:
  1583. "MCode 1.2.4 is installed. Restart running MCode sessions to use it.",
  1584. }));
  1585. const app = createTuiApp({
  1586. runtime: createRuntime(),
  1587. terminal: new FakeTerminal(),
  1588. version: "1.2.3",
  1589. workspaceDir: "/workspace",
  1590. inspectUpdate,
  1591. applyUpdate,
  1592. });
  1593. await app.ready;
  1594. await app.submit("/update");
  1595. expect(inspectUpdate).toHaveBeenCalledOnce();
  1596. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  1597. "MCode update",
  1598. );
  1599. app.interaction.current()?.handleInput?.("\r");
  1600. await vi.waitFor(() =>
  1601. expect(applyUpdate).toHaveBeenCalledWith(
  1602. plan,
  1603. expect.objectContaining({
  1604. onOutput: expect.any(Function),
  1605. }),
  1606. ),
  1607. );
  1608. await vi.waitFor(() =>
  1609. expect(
  1610. app.transcript
  1611. .snapshot()
  1612. .some((cell) => cell.content.includes("MCode update completed")),
  1613. ).toBe(true),
  1614. );
  1615. await app.stop();
  1616. });
  1617. it("leaves the current TUI after /update stages an npm-prefix replacement", async () => {
  1618. const plan = {
  1619. kind: "package-manager" as const,
  1620. source: "npm-prefix" as const,
  1621. currentVersion: "1.2.3",
  1622. latestVersion: "1.2.4",
  1623. packageTag: "latest" as const,
  1624. command: {
  1625. executable: "npm",
  1626. args: ["install"],
  1627. display: "npm install",
  1628. },
  1629. };
  1630. const requestRestart = vi.fn();
  1631. const app = createTuiApp({
  1632. runtime: createRuntime(),
  1633. terminal: new FakeTerminal(),
  1634. version: "1.2.3",
  1635. workspaceDir: "/workspace",
  1636. inspectUpdate: async () => plan,
  1637. applyUpdate: async () => ({
  1638. applied: true,
  1639. restartRequired: true,
  1640. message: "MCode 1.2.4 is staged safely.",
  1641. }),
  1642. requestRestart,
  1643. });
  1644. app.start();
  1645. await app.ready;
  1646. await app.submit("/update");
  1647. app.interaction.current()?.handleInput?.("\r");
  1648. await vi.waitFor(() => expect(requestRestart).toHaveBeenCalledOnce());
  1649. await app.stopped;
  1650. });
  1651. it("rechecks local and Runtime work before applying an update", async () => {
  1652. const runtime = createRuntime();
  1653. const applyUpdate = vi.fn(async () => ({
  1654. applied: true,
  1655. message: "updated",
  1656. }));
  1657. const app = createTuiApp({
  1658. runtime,
  1659. terminal: new FakeTerminal(),
  1660. version: "1.2.3",
  1661. workspaceDir: "/workspace",
  1662. inspectUpdate: async () => ({
  1663. kind: "available",
  1664. source: "managed-installer",
  1665. currentVersion: "1.2.3",
  1666. latestVersion: "1.2.4",
  1667. channel: "stable",
  1668. }),
  1669. applyUpdate,
  1670. });
  1671. await app.ready;
  1672. await app.openSession("session-1");
  1673. vi.mocked(runtime.getActiveRun).mockResolvedValue({
  1674. schemaVersion: 1,
  1675. sessionId: "session-1",
  1676. state: "running",
  1677. turnId: "turn-active",
  1678. actions: { steer: true },
  1679. });
  1680. await app.submit("/update");
  1681. app.interaction.current()?.handleInput?.("\r");
  1682. await vi.waitFor(() =>
  1683. expect(
  1684. app.transcript
  1685. .snapshot()
  1686. .some((cell) =>
  1687. cell.content.includes(
  1688. "MCode update failed: Finish or stop the active response before updating.",
  1689. ),
  1690. ),
  1691. ).toBe(true),
  1692. );
  1693. expect(applyUpdate).not.toHaveBeenCalled();
  1694. await app.stop();
  1695. });
  1696. it("fails the update gate closed when Runtime state cannot be verified", async () => {
  1697. const runtime = createRuntime();
  1698. const applyUpdate = vi.fn(async () => ({
  1699. applied: true,
  1700. message: "updated",
  1701. }));
  1702. const app = createTuiApp({
  1703. runtime,
  1704. terminal: new FakeTerminal(),
  1705. version: "1.2.3",
  1706. workspaceDir: "/workspace",
  1707. inspectUpdate: async () => ({
  1708. kind: "available",
  1709. source: "managed-installer",
  1710. currentVersion: "1.2.3",
  1711. latestVersion: "1.2.4",
  1712. channel: "stable",
  1713. }),
  1714. applyUpdate,
  1715. });
  1716. await app.ready;
  1717. await app.openSession("session-1");
  1718. vi.mocked(runtime.getActiveRun).mockRejectedValue(
  1719. new Error("Runtime unavailable"),
  1720. );
  1721. await app.submit("/update");
  1722. app.interaction.current()?.handleInput?.("\r");
  1723. await vi.waitFor(() =>
  1724. expect(
  1725. app.transcript
  1726. .snapshot()
  1727. .some((cell) =>
  1728. cell.content.includes("Unable to verify that this Session is idle"),
  1729. ),
  1730. ).toBe(true),
  1731. );
  1732. expect(applyUpdate).not.toHaveBeenCalled();
  1733. await app.stop();
  1734. });
  1735. it("does not expose the TUI before base hydration has settled", async () => {
  1736. const terminal = new FakeTerminal();
  1737. const runtime = createRuntime();
  1738. let releaseSessions: (() => void) | undefined;
  1739. vi.mocked(runtime.listSessions).mockImplementation(
  1740. async () =>
  1741. await new Promise((resolve) => {
  1742. releaseSessions = () => resolve([]);
  1743. }),
  1744. );
  1745. const app = createTuiApp({
  1746. runtime,
  1747. terminal,
  1748. version: "0.1.0",
  1749. workspaceDir: "/workspace",
  1750. });
  1751. let settled = false;
  1752. void app.ready.then(() => {
  1753. settled = true;
  1754. });
  1755. await Promise.resolve();
  1756. expect(settled).toBe(false);
  1757. releaseSessions?.();
  1758. await app.ready;
  1759. app.start();
  1760. const rendered = app.tui.render(80).join("\n");
  1761. expect(rendered).not.toContain("Starting MiniMax Code");
  1762. expect(rendered).not.toContain("Loading session");
  1763. await app.stop();
  1764. });
  1765. it("renders server startup in the welcome composer header until hydration settles", async () => {
  1766. const runtime = createRuntime();
  1767. let releaseSessions: (() => void) | undefined;
  1768. vi.mocked(runtime.listSessions).mockImplementation(
  1769. async () =>
  1770. await new Promise((resolve) => {
  1771. releaseSessions = () => resolve([]);
  1772. }),
  1773. );
  1774. const app = createTuiApp({
  1775. runtime,
  1776. terminal: new FakeTerminal(),
  1777. version: "0.1.0",
  1778. workspaceDir: "/workspace",
  1779. });
  1780. try {
  1781. app.setStartupStatus("⠋ Starting server...");
  1782. app.start();
  1783. const starting = app.tui.render(80).join("\n");
  1784. expect(starting).toContain("⠋ Starting server...");
  1785. expect(starting).not.toContain("Start · @ file · / autocomplete");
  1786. expect(starting).not.toContain("Loading session");
  1787. releaseSessions?.();
  1788. await app.ready;
  1789. app.setStartupStatus(undefined);
  1790. expect(app.tui.render(80).join("\n")).toContain(
  1791. "Start · @ file · / autocomplete",
  1792. );
  1793. } finally {
  1794. releaseSessions?.();
  1795. await app.stop();
  1796. }
  1797. });
  1798. it("waits for account hydration before allowing the first message", async () => {
  1799. const runtime = createRuntime();
  1800. let resolveAccount!: (
  1801. account: Awaited<ReturnType<typeof runtime.getAccountStatus>>,
  1802. ) => void;
  1803. vi.mocked(runtime.getAccountStatus).mockReturnValue(
  1804. new Promise((resolve) => {
  1805. resolveAccount = resolve;
  1806. }),
  1807. );
  1808. const app = createTuiApp({
  1809. runtime,
  1810. terminal: new FakeTerminal(),
  1811. version: "0.1.0",
  1812. workspaceDir: "/workspace",
  1813. });
  1814. try {
  1815. const readiness = await Promise.race([
  1816. app.ready.then(() => "ready" as const),
  1817. new Promise<"blocked">((resolve) =>
  1818. setTimeout(() => resolve("blocked"), 100),
  1819. ),
  1820. ]);
  1821. expect(readiness).toBe("blocked");
  1822. expect(runtime.createSession).not.toHaveBeenCalled();
  1823. resolveAccount({
  1824. status: "ready",
  1825. defaultModel: "minimax/MiniMax-M2.7",
  1826. managedTokenPresent: true,
  1827. warnings: [],
  1828. });
  1829. await app.ready;
  1830. const submission = app.submit("Send after account hydration");
  1831. await submission;
  1832. expect(runtime.createSession).toHaveBeenCalledWith({
  1833. workspaceDir: "/workspace",
  1834. });
  1835. expect(app.transcript.snapshot()).toEqual(
  1836. expect.arrayContaining([
  1837. expect.objectContaining({
  1838. kind: "user",
  1839. content: "Send after account hydration",
  1840. }),
  1841. expect.objectContaining({
  1842. kind: "assistant",
  1843. content: "Hello from the Agent",
  1844. }),
  1845. ]),
  1846. );
  1847. } finally {
  1848. resolveAccount({
  1849. status: "ready",
  1850. defaultModel: "minimax/MiniMax-M2.7",
  1851. managedTokenPresent: true,
  1852. warnings: [],
  1853. });
  1854. await app.ready;
  1855. await app.stop();
  1856. }
  1857. });
  1858. it("does not wait for Token Plan membership hydration before App readiness", async () => {
  1859. const runtime = createRuntime();
  1860. const baseAccount = {
  1861. status: "ready" as const,
  1862. defaultModel: "minimax/MiniMax-M2.7",
  1863. providerId: "minimax",
  1864. modelId: "MiniMax-M2.7",
  1865. authMode: "managed-login",
  1866. managedTokenPresent: true,
  1867. modelSource: "token-plan" as const,
  1868. warnings: [],
  1869. };
  1870. const hydratedAccount = {
  1871. ...baseAccount,
  1872. tokenPlanQuotaState: "available" as const,
  1873. tokenPlanQuota: {
  1874. fiveHour: { remainingPercent: 90, unlimited: false },
  1875. weekly: { remainingPercent: 80, unlimited: false },
  1876. },
  1877. };
  1878. let resolveMembership!: (account: typeof hydratedAccount) => void;
  1879. vi.mocked(runtime.getAccountStatus).mockImplementation(
  1880. async (_sessionId, options) => {
  1881. if (options?.includeMembership === true) {
  1882. return await new Promise((resolve) => {
  1883. resolveMembership = resolve;
  1884. });
  1885. }
  1886. return baseAccount;
  1887. },
  1888. );
  1889. const app = createTuiApp({
  1890. runtime,
  1891. terminal: new FakeTerminal(),
  1892. version: "0.1.0",
  1893. workspaceDir: "/workspace",
  1894. });
  1895. try {
  1896. await app.ready;
  1897. expect(runtime.getAccountStatus).toHaveBeenCalledWith(undefined, {
  1898. includeMembership: false,
  1899. });
  1900. expect(runtime.getAccountStatus).toHaveBeenCalledWith(undefined, {
  1901. includeMembership: true,
  1902. });
  1903. expect(app.controller.snapshot().account).toMatchObject(baseAccount);
  1904. resolveMembership(hydratedAccount);
  1905. await vi.waitFor(() =>
  1906. expect(app.controller.snapshot().account).toMatchObject({
  1907. tokenPlanQuotaState: "available",
  1908. }),
  1909. );
  1910. } finally {
  1911. resolveMembership(hydratedAccount);
  1912. await app.stop();
  1913. }
  1914. });
  1915. it("waits for permission mode hydration before reporting App readiness", async () => {
  1916. const runtime = createRuntime();
  1917. let resolvePermissionMode!: (mode: "auto") => void;
  1918. vi.mocked(runtime.getPermissionMode).mockReturnValue(
  1919. new Promise((resolve) => {
  1920. resolvePermissionMode = resolve;
  1921. }),
  1922. );
  1923. const app = createTuiApp({
  1924. runtime,
  1925. terminal: new FakeTerminal(),
  1926. version: "0.1.0",
  1927. workspaceDir: "/workspace",
  1928. });
  1929. const readiness = Promise.race([
  1930. app.ready.then(() => "ready" as const),
  1931. new Promise<"blocked">((resolve) =>
  1932. setTimeout(() => resolve("blocked"), 100),
  1933. ),
  1934. ]);
  1935. await expect(readiness).resolves.toBe("blocked");
  1936. resolvePermissionMode("auto");
  1937. await app.ready;
  1938. await app.stop();
  1939. });
  1940. it("accepts modeled account and optional permission degradation at the ready boundary", async () => {
  1941. const runtime = createRuntime();
  1942. vi.mocked(runtime.getAccountStatus).mockRejectedValue(
  1943. new Error("account offline"),
  1944. );
  1945. vi.mocked(runtime.getPermissionMode).mockRejectedValue(
  1946. new Error("config unavailable"),
  1947. );
  1948. const app = createTuiApp({
  1949. runtime,
  1950. terminal: new FakeTerminal(),
  1951. version: "0.1.0",
  1952. workspaceDir: "/workspace",
  1953. });
  1954. await expect(app.ready).resolves.toBeUndefined();
  1955. expect(app.controller.snapshot().account).toEqual({
  1956. status: "unknown",
  1957. warnings: [],
  1958. });
  1959. await app.stop();
  1960. });
  1961. it("hydrates the selected model display name into the status rail on startup", async () => {
  1962. const terminal = new FakeTerminal();
  1963. const runtime = createRuntime();
  1964. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  1965. status: "ready",
  1966. defaultModel: "custom_provider:innerTest/MiniMax-M3",
  1967. providerId: "custom_provider:innerTest",
  1968. modelId: "MiniMax-M3",
  1969. authMode: "byok",
  1970. managedTokenPresent: true,
  1971. warnings: [],
  1972. });
  1973. vi.mocked(runtime.listModels).mockResolvedValue([
  1974. {
  1975. providerId: "custom_provider:innerTest",
  1976. modelId: "MiniMax-M3",
  1977. displayName: "m3.05",
  1978. selected: true,
  1979. },
  1980. ]);
  1981. const app = createTuiApp({
  1982. runtime,
  1983. terminal,
  1984. version: "0.1.0",
  1985. workspaceDir: "/workspace",
  1986. });
  1987. app.start();
  1988. await app.ready;
  1989. await vi.waitFor(() =>
  1990. expect(app.tui.render(120).join("\n")).toContain("✦ m3.05"),
  1991. );
  1992. await app.stop();
  1993. });
  1994. it("restores a managed-login failure to the Composer", async () => {
  1995. const terminal = new FakeTerminal();
  1996. const runtime = createRuntime();
  1997. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  1998. status: "ready",
  1999. defaultModel: "minimax/MiniMax-M2.7",
  2000. authMode: "managed-login",
  2001. modelSource: "token-plan",
  2002. managedTokenPresent: false,
  2003. warnings: [],
  2004. });
  2005. const app = createTuiApp({
  2006. runtime,
  2007. terminal,
  2008. version: "0.1.0",
  2009. workspaceDir: "/workspace",
  2010. });
  2011. app.start();
  2012. await app.ready;
  2013. await vi.waitFor(() =>
  2014. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login"),
  2015. );
  2016. terminal.input?.("Keep this until login");
  2017. terminal.input?.("\r");
  2018. await vi.waitFor(() =>
  2019. expect(app.editor.getText()).toBe("Keep this until login"),
  2020. );
  2021. expect(app.tui.render(80).join("\n")).toContain("Keep this until login");
  2022. expect(app.transcript.snapshot()).toEqual(
  2023. expect.arrayContaining([
  2024. expect.objectContaining({
  2025. kind: "warning",
  2026. content:
  2027. "Sign in to MiniMax to use Agent features. Run /login, then retry.",
  2028. }),
  2029. ]),
  2030. );
  2031. expect(runtime.createSession).not.toHaveBeenCalled();
  2032. expect(runtime.sendMessage).not.toHaveBeenCalled();
  2033. await app.stop();
  2034. });
  2035. it("renders an Enter submission before the asynchronous login preflight settles", async () => {
  2036. const terminal = new FakeTerminal();
  2037. const runtime = createRuntime();
  2038. const app = createTuiApp({
  2039. runtime,
  2040. terminal,
  2041. version: "0.1.0",
  2042. workspaceDir: "/workspace",
  2043. });
  2044. app.start();
  2045. await app.ready;
  2046. let resolveAccount:
  2047. | ((
  2048. account: Awaited<ReturnType<typeof runtime.getAccountStatus>>,
  2049. ) => void)
  2050. | undefined;
  2051. vi.mocked(runtime.getAccountStatus).mockImplementationOnce(
  2052. () =>
  2053. new Promise((resolve) => {
  2054. resolveAccount = resolve;
  2055. }),
  2056. );
  2057. const writesBeforeSubmission = terminal.writes.length;
  2058. terminal.input?.("Show this immediately");
  2059. terminal.input?.("\r");
  2060. expect(app.editor.getText()).toBe("");
  2061. expect(
  2062. app.transcript.snapshot().filter((cell) => cell.kind === "user"),
  2063. ).toEqual([
  2064. expect.objectContaining({
  2065. status: "pending",
  2066. content: "Show this immediately",
  2067. }),
  2068. ]);
  2069. await vi.waitFor(() =>
  2070. expect(terminal.writes.length).toBeGreaterThan(writesBeforeSubmission),
  2071. );
  2072. expect(runtime.createSession).not.toHaveBeenCalled();
  2073. expect(runtime.sendMessage).not.toHaveBeenCalled();
  2074. await vi.waitFor(() => expect(resolveAccount).toBeTypeOf("function"));
  2075. resolveAccount?.({
  2076. status: "ready",
  2077. defaultModel: "minimax/MiniMax-M2.7",
  2078. providerId: "minimax",
  2079. modelId: "MiniMax-M2.7",
  2080. authMode: "managed-login",
  2081. managedTokenPresent: true,
  2082. warnings: [],
  2083. });
  2084. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
  2085. await app.stop();
  2086. });
  2087. it("keeps a login-blocked submission editable after current-region sign-in", async () => {
  2088. const terminal = new FakeTerminal();
  2089. const runtime = createRuntime();
  2090. let authenticated = false;
  2091. vi.mocked(runtime.getAccountStatus).mockImplementation(async () =>
  2092. authenticated
  2093. ? {
  2094. status: "ready",
  2095. defaultModel: "minimax/MiniMax-M2.7",
  2096. providerId: "minimax",
  2097. modelId: "MiniMax-M2.7",
  2098. authMode: "managed-login",
  2099. modelSource: "token-plan",
  2100. managedTokenPresent: true,
  2101. warnings: [],
  2102. }
  2103. : {
  2104. status: "needs-login",
  2105. authMode: "managed-login",
  2106. modelSource: "token-plan",
  2107. managedTokenPresent: false,
  2108. warnings: [],
  2109. },
  2110. );
  2111. const auth = {
  2112. login: vi.fn(async () => {
  2113. authenticated = true;
  2114. return {
  2115. state: "authenticated" as const,
  2116. message: "Signed in with MiniMax.",
  2117. };
  2118. }),
  2119. logout: vi.fn(async () => ({
  2120. state: "signed-out" as const,
  2121. message: "Signed out of MiniMax.",
  2122. })),
  2123. };
  2124. const app = createTuiApp({
  2125. runtime,
  2126. auth,
  2127. terminal,
  2128. version: "0.1.0",
  2129. workspaceDir: "/workspace",
  2130. });
  2131. app.start();
  2132. await app.ready;
  2133. terminal.input?.("Send this after login");
  2134. terminal.input?.("\r");
  2135. await vi.waitFor(() =>
  2136. expect(app.editor.getText()).toBe("Send this after login"),
  2137. );
  2138. await app.submit("/login");
  2139. app.interaction.current()?.handleInput("\r");
  2140. expect(runtime.sendMessage).not.toHaveBeenCalled();
  2141. app.editor.handleInput("\r");
  2142. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
  2143. expect(runtime.sendMessage).toHaveBeenCalledWith(
  2144. expect.objectContaining({
  2145. id: "session-1",
  2146. content: "Send this after login",
  2147. turnId: expect.any(String),
  2148. }),
  2149. expect.any(AbortSignal),
  2150. );
  2151. expect(app.transcript.snapshot()).toEqual(
  2152. expect.arrayContaining([
  2153. expect.objectContaining({
  2154. kind: "user",
  2155. content: "Send this after login",
  2156. }),
  2157. ]),
  2158. );
  2159. await app.stop();
  2160. });
  2161. it("runs /checkin immediately for a signed-in MiniMax account", async () => {
  2162. const runtime = createRuntime();
  2163. const app = createTuiApp({
  2164. runtime,
  2165. terminal: new FakeTerminal(),
  2166. version: "0.1.0",
  2167. workspaceDir: "/workspace",
  2168. });
  2169. app.start();
  2170. await app.ready;
  2171. await app.submit("/checkin");
  2172. expect(runtime.runDailyCheckin).toHaveBeenCalledOnce();
  2173. expect(app.transcript.snapshot()).toEqual(
  2174. expect.arrayContaining([
  2175. expect.objectContaining({
  2176. kind: "final-summary",
  2177. content: expect.stringContaining(
  2178. "Checked in: Cycle day 2, +20 Credits",
  2179. ),
  2180. }),
  2181. ]),
  2182. );
  2183. await app.stop();
  2184. });
  2185. it("shows a generic /checkin failure without backend details", async () => {
  2186. const runtime = createRuntime();
  2187. vi.mocked(runtime.runDailyCheckin).mockRejectedValue(
  2188. new Error("internal signin shard rejected request"),
  2189. );
  2190. const app = createTuiApp({
  2191. runtime,
  2192. terminal: new FakeTerminal(),
  2193. version: "0.1.0",
  2194. workspaceDir: "/workspace",
  2195. });
  2196. app.start();
  2197. await app.ready;
  2198. await app.submit("/checkin");
  2199. const transcript = app.transcript
  2200. .snapshot()
  2201. .map((cell) => cell.content)
  2202. .join("\n");
  2203. expect(transcript).toContain("Couldn't complete daily check-in.");
  2204. expect(transcript).not.toContain("internal signin shard");
  2205. await app.stop();
  2206. });
  2207. it("does not open login when /checkin cannot verify account status", async () => {
  2208. const runtime = createRuntime();
  2209. const auth = {
  2210. login: vi.fn(),
  2211. logout: vi.fn(async () => ({
  2212. state: "signed-out" as const,
  2213. message: "Signed out of MiniMax.",
  2214. })),
  2215. };
  2216. const app = createTuiApp({
  2217. runtime,
  2218. auth,
  2219. terminal: new FakeTerminal(),
  2220. version: "0.1.0",
  2221. workspaceDir: "/workspace",
  2222. });
  2223. app.start();
  2224. await app.ready;
  2225. vi.mocked(runtime.getAccountStatus).mockRejectedValue(
  2226. new Error("status unavailable"),
  2227. );
  2228. await app.submit("/checkin");
  2229. expect(app.interaction.current()).toBeUndefined();
  2230. expect(auth.login).not.toHaveBeenCalled();
  2231. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2232. await app.stop();
  2233. });
  2234. it("starts MiniMax login and resumes /checkin once after authentication", async () => {
  2235. const runtime = createRuntime();
  2236. let authenticated = false;
  2237. vi.mocked(runtime.getAccountStatus).mockImplementation(async () => ({
  2238. status: authenticated ? "ready" : "needs-login",
  2239. authMode: "managed-login",
  2240. modelSource: "byok",
  2241. managedTokenPresent: authenticated,
  2242. warnings: [],
  2243. }));
  2244. const auth = {
  2245. login: vi.fn(async () => {
  2246. authenticated = true;
  2247. return {
  2248. state: "authenticated" as const,
  2249. message: "Signed in with MiniMax.",
  2250. };
  2251. }),
  2252. logout: vi.fn(async () => ({
  2253. state: "signed-out" as const,
  2254. message: "Signed out of MiniMax.",
  2255. })),
  2256. };
  2257. const app = createTuiApp({
  2258. runtime,
  2259. auth,
  2260. terminal: new FakeTerminal(),
  2261. version: "0.1.0",
  2262. workspaceDir: "/workspace",
  2263. });
  2264. app.start();
  2265. await app.ready;
  2266. await app.submit("/checkin");
  2267. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2268. app.interaction.current()?.handleInput("\r");
  2269. await vi.waitFor(() =>
  2270. expect(runtime.runDailyCheckin).toHaveBeenCalledOnce(),
  2271. );
  2272. expect(auth.login).toHaveBeenCalledWith(expect.any(Function), "cn");
  2273. await app.stop();
  2274. });
  2275. it("does not resume /checkin when the login picker is cancelled", async () => {
  2276. const runtime = createRuntime();
  2277. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2278. status: "needs-login",
  2279. authMode: "managed-login",
  2280. modelSource: "byok",
  2281. managedTokenPresent: false,
  2282. warnings: [],
  2283. });
  2284. const auth = {
  2285. login: vi.fn(),
  2286. logout: vi.fn(async () => ({
  2287. state: "signed-out" as const,
  2288. message: "Signed out of MiniMax.",
  2289. })),
  2290. };
  2291. const app = createTuiApp({
  2292. runtime,
  2293. auth,
  2294. terminal: new FakeTerminal(),
  2295. version: "0.1.0",
  2296. workspaceDir: "/workspace",
  2297. });
  2298. app.start();
  2299. await app.ready;
  2300. await app.submit("/checkin");
  2301. app.interaction.current()?.handleInput("\u001b");
  2302. expect(auth.login).not.toHaveBeenCalled();
  2303. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2304. await app.stop();
  2305. });
  2306. it("does not resume /checkin when browser login fails", async () => {
  2307. const runtime = createRuntime();
  2308. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2309. status: "needs-login",
  2310. managedTokenPresent: false,
  2311. warnings: [],
  2312. });
  2313. const auth = {
  2314. login: vi.fn(async () => {
  2315. throw new Error("browser login failed");
  2316. }),
  2317. logout: vi.fn(async () => ({
  2318. state: "signed-out" as const,
  2319. message: "Signed out of MiniMax.",
  2320. })),
  2321. };
  2322. const app = createTuiApp({
  2323. runtime,
  2324. auth,
  2325. terminal: new FakeTerminal(),
  2326. version: "0.1.0",
  2327. workspaceDir: "/workspace",
  2328. });
  2329. app.start();
  2330. await app.ready;
  2331. await app.submit("/checkin");
  2332. app.interaction.current()?.handleInput("\r");
  2333. await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
  2334. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2335. await app.stop();
  2336. });
  2337. it("carries /checkin through a cross-region login restart", async () => {
  2338. const runtime = createRuntime();
  2339. const requestRestart = vi.fn();
  2340. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2341. status: "needs-login",
  2342. managedTokenPresent: false,
  2343. warnings: [],
  2344. });
  2345. const auth = {
  2346. login: vi.fn(async () => ({
  2347. state: "authenticated" as const,
  2348. restartRequired: true,
  2349. message: "Signed in with MiniMax Global.",
  2350. })),
  2351. logout: vi.fn(async () => ({
  2352. state: "signed-out" as const,
  2353. message: "Signed out of MiniMax.",
  2354. })),
  2355. };
  2356. const app = createTuiApp({
  2357. runtime,
  2358. auth,
  2359. terminal: new FakeTerminal(),
  2360. version: "0.1.0",
  2361. workspaceDir: "/workspace",
  2362. requestRestart,
  2363. });
  2364. app.start();
  2365. await app.ready;
  2366. await app.submit("/checkin");
  2367. app.interaction.current()?.handleInput("\u001b[B");
  2368. app.interaction.current()?.handleInput("\r");
  2369. await vi.waitFor(() =>
  2370. expect(requestRestart).toHaveBeenCalledWith("en", "/checkin"),
  2371. );
  2372. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2373. await app.stopped;
  2374. });
  2375. it("restarts after cross-region login while keeping the blocked submission", async () => {
  2376. const terminal = new FakeTerminal();
  2377. const runtime = createRuntime();
  2378. const requestRestart = vi.fn();
  2379. const notifyAuthContextChanged = vi.fn(async () => undefined);
  2380. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2381. status: "needs-login",
  2382. authMode: "managed-login",
  2383. modelSource: "token-plan",
  2384. managedTokenPresent: false,
  2385. warnings: [],
  2386. });
  2387. const auth = {
  2388. login: vi.fn(async () => ({
  2389. state: "authenticated" as const,
  2390. restartRequired: true,
  2391. message: "Signed in with MiniMax Global.",
  2392. })),
  2393. logout: vi.fn(async () => ({
  2394. state: "signed-out" as const,
  2395. message: "Signed out of MiniMax.",
  2396. })),
  2397. };
  2398. const app = createTuiApp({
  2399. runtime,
  2400. auth,
  2401. terminal,
  2402. version: "0.1.0",
  2403. workspaceDir: "/workspace",
  2404. requestRestart,
  2405. notifyAuthContextChanged,
  2406. });
  2407. app.start();
  2408. await app.ready;
  2409. terminal.input?.("Keep this through restart");
  2410. terminal.input?.("\r");
  2411. await vi.waitFor(() =>
  2412. expect(app.editor.getText()).toBe("Keep this through restart"),
  2413. );
  2414. await app.submit("/login");
  2415. app.interaction.current()?.handleInput("\u001b[B");
  2416. app.interaction.current()?.handleInput("\r");
  2417. await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
  2418. expect(auth.login).toHaveBeenCalledWith(expect.any(Function), "en");
  2419. expect(runtime.sendMessage).not.toHaveBeenCalled();
  2420. await vi.waitFor(() => expect(requestRestart).toHaveBeenCalledOnce());
  2421. expect(requestRestart).toHaveBeenCalledWith("en");
  2422. expect(notifyAuthContextChanged).not.toHaveBeenCalled();
  2423. await app.stopped;
  2424. expect(app.editor.getText()).toBe("Keep this through restart");
  2425. });
  2426. it("offers MiniMax login without blocking an unauthenticated builtin BYOK Turn", async () => {
  2427. const runtime = createRuntime();
  2428. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2429. status: "ready",
  2430. defaultModel: "minimax/MiniMax-M3",
  2431. providerId: "minimax",
  2432. authMode: "managed-login",
  2433. modelSource: "byok",
  2434. managedTokenPresent: false,
  2435. warnings: [],
  2436. });
  2437. const app = createTuiApp({
  2438. runtime,
  2439. terminal: new FakeTerminal(),
  2440. version: "0.1.0",
  2441. workspaceDir: "/workspace",
  2442. });
  2443. app.start();
  2444. await app.ready;
  2445. await vi.waitFor(() =>
  2446. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login"),
  2447. );
  2448. await app.submit("BYOK still runs");
  2449. expect(runtime.createSession).toHaveBeenCalledWith({
  2450. workspaceDir: "/workspace",
  2451. });
  2452. expect(app.transcript.snapshot()).toEqual(
  2453. expect.arrayContaining([
  2454. expect.objectContaining({ kind: "user", content: "BYOK still runs" }),
  2455. expect.objectContaining({
  2456. kind: "assistant",
  2457. content: "Hello from the Agent",
  2458. }),
  2459. ]),
  2460. );
  2461. await app.stop();
  2462. });
  2463. it("starts a terminal-native workbench and submits messages through the Agent runtime", async () => {
  2464. const terminal = new FakeTerminal();
  2465. const runtime = createRuntime();
  2466. const app = createTuiApp({
  2467. runtime,
  2468. terminal,
  2469. version: "0.1.0",
  2470. workspaceDir: "/workspace",
  2471. homeDir: "/home/dev",
  2472. });
  2473. app.start();
  2474. await app.ready;
  2475. expect(app.getSurface()).toBe("welcome");
  2476. await app.submit("Say hello");
  2477. expect(app.getSurface()).toBe("conversation");
  2478. const conversation = app.tui.render(80).join("\n");
  2479. expect(conversation).toContain("Tips for getting started");
  2480. expect(conversation).toContain("Say hello");
  2481. expect(conversation).toContain("Hello from the Agent");
  2482. expect(terminal.started).toBe(true);
  2483. expect(terminal.title).toBe("Minimax Code");
  2484. expect(runtime.createSession).toHaveBeenCalledWith({
  2485. workspaceDir: "/workspace",
  2486. });
  2487. expect(app.transcript.snapshot()).toEqual([
  2488. expect.objectContaining({ kind: "user", content: "Say hello" }),
  2489. expect.objectContaining({
  2490. kind: "assistant",
  2491. status: "succeeded",
  2492. content: "Hello from the Agent",
  2493. }),
  2494. expect.objectContaining({ kind: "turn-duration", status: "succeeded" }),
  2495. ]);
  2496. await app.stop();
  2497. expect(terminal.stopped).toBe(true);
  2498. });
  2499. it("syncs the generated Session title to the terminal without duplicate writes", async () => {
  2500. const terminal = new FakeTerminal();
  2501. const runtime = createRuntime();
  2502. let sessionTitle = "New session";
  2503. let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  2504. vi.mocked(runtime.listSessions).mockImplementation(async () => [
  2505. {
  2506. sessionId: "session-1",
  2507. title: sessionTitle,
  2508. workspaceDir: "/workspace",
  2509. },
  2510. ]);
  2511. vi.mocked(runtime.watchEvents).mockImplementation(
  2512. async function* watchEvents(signal) {
  2513. const event = await new Promise<TuiRuntimeEvent | undefined>(
  2514. (resolve) => {
  2515. emitEvent = resolve;
  2516. signal.addEventListener("abort", () => resolve(undefined), {
  2517. once: true,
  2518. });
  2519. },
  2520. );
  2521. if (event) yield event;
  2522. await new Promise<void>((resolve) => {
  2523. signal.addEventListener("abort", resolve, { once: true });
  2524. });
  2525. },
  2526. );
  2527. const app = createTuiApp({
  2528. runtime,
  2529. terminal,
  2530. version: "0.1.0",
  2531. workspaceDir: "/workspace",
  2532. });
  2533. app.start();
  2534. await app.ready;
  2535. await app.submit("Review uncommitted work");
  2536. await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
  2537. sessionTitle = "Review uncommitted work";
  2538. emitEvent?.(
  2539. runtimeEvent({
  2540. type: "session.title_updated",
  2541. timestamp: Date.now(),
  2542. source: "runtime",
  2543. payload: {
  2544. sessionId: "session-1",
  2545. title: sessionTitle,
  2546. },
  2547. }),
  2548. );
  2549. await vi.waitFor(() => expect(terminal.title).toBe(sessionTitle));
  2550. await app.submit("/status");
  2551. expect(terminal.titleUpdates).toEqual(["Minimax Code", sessionTitle]);
  2552. await app.stop();
  2553. });
  2554. it("keeps chat state alive while a regular feature overlay owns the viewport", async () => {
  2555. const terminal = new FakeTerminal();
  2556. terminal.rows = 6;
  2557. const runtime = createRuntime();
  2558. const app = createTuiApp({
  2559. runtime,
  2560. terminal,
  2561. version: "0.1.0",
  2562. workspaceDir: "/workspace",
  2563. });
  2564. const featureInput = vi.fn();
  2565. const featureContent = {
  2566. render: () => ["feature-header", "feature-body"],
  2567. invalidate: () => undefined,
  2568. };
  2569. const feature = {
  2570. id: "sessions",
  2571. layoutRoot: new VStack([{ component: featureContent }]),
  2572. render: featureContent.render,
  2573. invalidate: () => undefined,
  2574. handleInput: featureInput,
  2575. };
  2576. app.start();
  2577. await app.ready;
  2578. const screen = new VirtualTerminalScreen(terminal.columns, terminal.rows);
  2579. let writeIndex = 0;
  2580. const flushWrites = (): void => {
  2581. for (; writeIndex < terminal.writes.length; writeIndex += 1) {
  2582. screen.feed(terminal.writes[writeIndex] ?? "");
  2583. }
  2584. };
  2585. flushWrites();
  2586. app.editor.setText("preserved draft");
  2587. const handle = app.surfaceHost.pushFeature({ screen: feature });
  2588. app.tui.renderNow();
  2589. flushWrites();
  2590. expect(app.surfaceHost.getActiveSurface()).toEqual({
  2591. kind: "feature",
  2592. id: "sessions",
  2593. });
  2594. expect(app.surfaceHost.render(80).join("\n")).toContain("preserved draft");
  2595. expect(screen.viewportText()).toContain("feature-header");
  2596. expect(screen.viewportText()).toContain("feature-body");
  2597. expect(app.tui.mode).toBe("regular");
  2598. expect(terminal.startCount).toBe(1);
  2599. expect(terminal.stopCount).toBe(0);
  2600. terminal.input?.("j");
  2601. expect(featureInput).toHaveBeenCalledWith("j");
  2602. expect(handle.close()).toBe(true);
  2603. app.tui.renderNow();
  2604. flushWrites();
  2605. expect(app.surfaceHost.getActiveSurface()).toEqual({
  2606. kind: "chat",
  2607. id: "chat",
  2608. });
  2609. expect(app.editor.getText()).toBe("preserved draft");
  2610. expect(app.surfaceHost.render(80).join("\n")).toContain("preserved draft");
  2611. expect(screen.viewportText()).toContain("preserved draft");
  2612. expect(screen.viewportText()).not.toContain("feature-header");
  2613. await app.stop();
  2614. screen.dispose();
  2615. });
  2616. it("switches /settings through explicit choices and closes after applying", async () => {
  2617. const terminal = new FakeTerminal();
  2618. const persistTuiMode = vi.fn();
  2619. const app = createTuiApp({
  2620. runtime: createRuntime(),
  2621. terminal,
  2622. version: "0.2.0",
  2623. workspaceDir: "/workspace",
  2624. tuiMode: "regular",
  2625. persistTuiMode,
  2626. });
  2627. app.start();
  2628. await app.ready;
  2629. expect(app.surfaceHost.getChatMode()).toBe("regular");
  2630. expect(app.tui.mode).toBe("regular");
  2631. await app.submit("/settings");
  2632. const fullscreenSettings = app.interaction.current();
  2633. expect(app.tui.getFocusedComponent()).toBe(fullscreenSettings);
  2634. expect(app.surfaceHost.render(80).join("\n")).toContain(
  2635. "TUI mode · Regular",
  2636. );
  2637. terminal.input?.("\u001b[B");
  2638. terminal.input?.("\r");
  2639. expect(app.surfaceHost.getChatMode()).toBe("fullscreen");
  2640. expect(app.tui.mode).toBe("fullscreen");
  2641. expect(app.interaction.isActive()).toBe(false);
  2642. expect(app.tui.getFocusedComponent()).toBe(app.editor);
  2643. expect(persistTuiMode).toHaveBeenLastCalledWith("fullscreen");
  2644. expect(app.editor.focused).toBe(true);
  2645. terminal.input?.("/");
  2646. await vi.waitFor(() =>
  2647. expect(app.editor.render(60).join("\n")).toContain(
  2648. "Show available commands",
  2649. ),
  2650. );
  2651. terminal.input?.("\u001b");
  2652. app.editor.setText("");
  2653. await app.submit("/settings");
  2654. const regularSettings = app.interaction.current();
  2655. expect(app.tui.getFocusedComponent()).toBe(regularSettings);
  2656. expect(app.surfaceHost.render(80).join("\n")).toContain(
  2657. "TUI mode · Fullscreen",
  2658. );
  2659. terminal.input?.("\u001b[A");
  2660. terminal.input?.("\r");
  2661. expect(app.surfaceHost.getChatMode()).toBe("regular");
  2662. expect(app.tui.mode).toBe("regular");
  2663. expect(app.interaction.isActive()).toBe(false);
  2664. expect(app.tui.getFocusedComponent()).toBe(app.editor);
  2665. expect(persistTuiMode).toHaveBeenLastCalledWith("regular");
  2666. await app.stop();
  2667. });
  2668. it("keeps the Pi Editor and Slash Command autocomplete active in fullscreen chat", async () => {
  2669. const terminal = new FakeTerminal();
  2670. terminal.rows = 8;
  2671. const app = createTuiApp({
  2672. runtime: createRuntime(),
  2673. terminal,
  2674. version: "0.2.0",
  2675. workspaceDir: "/workspace",
  2676. tuiMode: "fullscreen",
  2677. });
  2678. app.start();
  2679. await app.ready;
  2680. terminal.input?.("/");
  2681. await vi.waitFor(() =>
  2682. expect(app.editor.render(60).join("\n")).toContain(
  2683. "Show available commands",
  2684. ),
  2685. );
  2686. expect(app.editor.getText()).toBe("/");
  2687. terminal.input?.("\u001B[B");
  2688. expect(app.editor.getText()).toBe("/");
  2689. terminal.input?.("\u001B");
  2690. expect(app.editor.getText()).toBe("/");
  2691. expect(app.editor.focused).toBe(true);
  2692. await app.stop();
  2693. });
  2694. it("renders regular-mode Slash Command autocomplete on the first keypress and every update", async () => {
  2695. const terminal = new FakeTerminal();
  2696. const app = createTuiApp({
  2697. runtime: createRuntime(),
  2698. terminal,
  2699. version: "0.2.0",
  2700. workspaceDir: "/workspace",
  2701. tuiMode: "regular",
  2702. });
  2703. app.start();
  2704. await app.ready;
  2705. const screen = new VirtualTerminalScreen(terminal.columns, terminal.rows);
  2706. let writeIndex = 0;
  2707. const flushWrites = (): void => {
  2708. for (; writeIndex < terminal.writes.length; writeIndex += 1) {
  2709. screen.feed(terminal.writes[writeIndex] ?? "");
  2710. }
  2711. };
  2712. flushWrites();
  2713. terminal.input?.("/");
  2714. await vi.waitFor(() => {
  2715. flushWrites();
  2716. expect(screen.viewportText()).toContain("Show available commands");
  2717. });
  2718. expect(screen.viewportText()).toContain("/");
  2719. terminal.input?.("m");
  2720. await vi.waitFor(() => {
  2721. flushWrites();
  2722. expect(screen.viewportText()).toContain("Choose a model");
  2723. });
  2724. expect(screen.viewportText()).toContain("/m");
  2725. screen.dispose();
  2726. await app.stop();
  2727. });
  2728. it("resumes fullscreen tail following when submitting from scrolled history", async () => {
  2729. const terminal = new FakeTerminal();
  2730. terminal.rows = 6;
  2731. const app = createTuiApp({
  2732. runtime: createRuntime(),
  2733. terminal,
  2734. version: "0.2.0",
  2735. workspaceDir: "/workspace",
  2736. tuiMode: "fullscreen",
  2737. });
  2738. app.start();
  2739. await app.ready;
  2740. for (let index = 1; index <= 4; index += 1) {
  2741. await app.submit(`Prompt ${String(index)}`);
  2742. }
  2743. app.tui.renderNow();
  2744. terminal.input?.("\u001B[5~");
  2745. expect((app.tui as TuiAltScreen).isFollowingOutput).toBe(false);
  2746. await app.submit("Latest prompt");
  2747. expect((app.tui as TuiAltScreen).isFollowingOutput).toBe(true);
  2748. await app.stop();
  2749. });
  2750. it("stops the terminal without waiting for a stalled Desktop event stream", async () => {
  2751. const terminal = new FakeTerminal();
  2752. const runtime = createRuntime();
  2753. vi.mocked(runtime.watchEvents).mockImplementation(
  2754. async function* watchEvents() {
  2755. await new Promise<void>(() => undefined);
  2756. yield runtimeEvent({
  2757. type: "unreachable",
  2758. timestamp: 0,
  2759. source: "test",
  2760. payload: {},
  2761. });
  2762. },
  2763. );
  2764. const app = createTuiApp({
  2765. runtime,
  2766. terminal,
  2767. version: "0.1.0",
  2768. workspaceDir: "/workspace",
  2769. });
  2770. app.start();
  2771. await app.ready;
  2772. const stopping = app.stop();
  2773. await vi.waitFor(() => expect(terminal.stopped).toBe(true));
  2774. await stopping;
  2775. });
  2776. it("restores the terminal before a stalled remote turn abort finishes", async () => {
  2777. const terminal = new FakeTerminal();
  2778. const runtime = createRuntime();
  2779. let finishRemoteAbort: ((value: boolean) => void) | undefined;
  2780. vi.mocked(runtime.sendMessage).mockImplementation(
  2781. async function* sendMessage(_req: SendMessageReq, signal?: AbortSignal) {
  2782. await new Promise<void>((resolve) => {
  2783. signal?.addEventListener("abort", () => resolve(), { once: true });
  2784. });
  2785. yield { type: "done" };
  2786. },
  2787. );
  2788. vi.mocked(runtime.abortSession).mockImplementation(
  2789. async () =>
  2790. await new Promise<boolean>((resolve) => {
  2791. finishRemoteAbort = resolve;
  2792. }),
  2793. );
  2794. const app = createTuiApp({
  2795. runtime,
  2796. terminal,
  2797. version: "0.1.0",
  2798. workspaceDir: "/workspace",
  2799. });
  2800. app.start();
  2801. await app.ready;
  2802. const submitting = app.submit("Keep running");
  2803. await vi.waitFor(() =>
  2804. expect(app.controller.snapshot().status).toBe("running"),
  2805. );
  2806. const stopping = app.stop();
  2807. await vi.waitFor(() => expect(terminal.stopped).toBe(true));
  2808. finishRemoteAbort?.(true);
  2809. await Promise.all([submitting, stopping]);
  2810. });
  2811. it("stops the active turn before leaving the UI", async () => {
  2812. const terminal = new FakeTerminal();
  2813. const runtime = createRuntime();
  2814. let finishTurn: (() => void) | undefined;
  2815. vi.mocked(runtime.sendMessage).mockImplementation(
  2816. async function* sendMessage() {
  2817. yield {
  2818. type: "delta",
  2819. turnId: "turn-detached",
  2820. role: "assistant",
  2821. content: "Still running",
  2822. };
  2823. await new Promise<void>((resolve) => {
  2824. finishTurn = resolve;
  2825. });
  2826. yield { type: "done", turnId: "turn-detached" };
  2827. },
  2828. );
  2829. const app = createTuiApp({
  2830. runtime,
  2831. terminal,
  2832. version: "0.1.0",
  2833. workspaceDir: "/workspace",
  2834. });
  2835. app.start();
  2836. await app.ready;
  2837. const submitting = app.submit("Keep running after the UI leaves");
  2838. await vi.waitFor(() =>
  2839. expect(app.controller.snapshot().status).toBe("running"),
  2840. );
  2841. await app.leaveUi();
  2842. expect(terminal.stopped).toBe(true);
  2843. expect(runtime.abortSession).toHaveBeenCalledWith(
  2844. expect.objectContaining({ id: "session-1" }),
  2845. );
  2846. finishTurn?.();
  2847. await submitting;
  2848. });
  2849. it("resumes a launcher-selected Session and exposes its ID for the exit hint", async () => {
  2850. const terminal = new FakeTerminal();
  2851. const runtime = createRuntime();
  2852. const app = createTuiApp({
  2853. runtime,
  2854. terminal,
  2855. version: "0.1.0",
  2856. workspaceDir: "/workspace",
  2857. });
  2858. app.start();
  2859. await app.ready;
  2860. expect(app.controller.snapshot().session?.sessionId).toBeUndefined();
  2861. await app.openSession("session-existing");
  2862. expect(runtime.getSession).toHaveBeenCalledWith("session-existing");
  2863. expect(runtime.getMessages).toHaveBeenCalledWith("session-existing");
  2864. expect(app.controller.snapshot().session?.sessionId).toBe(
  2865. "session-existing",
  2866. );
  2867. await app.leaveUi();
  2868. });
  2869. it("reports a launcher continue hydration failure in the Transcript", async () => {
  2870. const terminal = new FakeTerminal();
  2871. const runtime = createRuntime();
  2872. vi.mocked(runtime.listSessions).mockResolvedValue([
  2873. {
  2874. sessionId: "session-existing",
  2875. title: "Existing session",
  2876. workspaceDir: "/workspace",
  2877. },
  2878. ]);
  2879. vi.mocked(runtime.getSession).mockRejectedValue(
  2880. new Error("Session hydration failed"),
  2881. );
  2882. const app = createTuiApp({
  2883. runtime,
  2884. terminal,
  2885. version: "0.1.0",
  2886. workspaceDir: "/workspace",
  2887. });
  2888. await app.ready;
  2889. await expect(app.continueLatestSession()).rejects.toThrow(
  2890. "Session hydration failed",
  2891. );
  2892. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  2893. kind: "error",
  2894. content:
  2895. "Couldn't continue the latest conversation: Session hydration failed. Retry after the connection recovers.",
  2896. });
  2897. await app.leaveUi();
  2898. });
  2899. it("can disable queue UI and preserve the next draft while a turn is running", async () => {
  2900. const terminal = new FakeTerminal();
  2901. const runtime = createRuntime();
  2902. let finishTool: (() => void) | undefined;
  2903. vi.mocked(runtime.sendMessage).mockImplementation(
  2904. async function* sendMessage() {
  2905. yield {
  2906. type: "delta",
  2907. turnId: "turn-running-tool",
  2908. toolCalls: [
  2909. {
  2910. id: "read-1",
  2911. name: "read",
  2912. status: "running",
  2913. input: { path: "src/cart/price.ts" },
  2914. },
  2915. ],
  2916. };
  2917. await new Promise<void>((resolve) => {
  2918. finishTool = resolve;
  2919. });
  2920. yield { type: "done", turnId: "turn-running-tool" };
  2921. },
  2922. );
  2923. const app = createTuiApp({
  2924. runtime,
  2925. terminal,
  2926. version: "0.1.0",
  2927. workspaceDir: "/workspace",
  2928. productFeatures: { queue: false },
  2929. });
  2930. await app.ready;
  2931. const submission = app.submit("Inspect the pricing logic");
  2932. await vi.waitFor(() => {
  2933. const rendered = app.tui.render(80).join("\n");
  2934. expect(rendered).toContain("Reading (src/cart/price.ts)");
  2935. expect(rendered).toContain("Running");
  2936. expect(rendered).not.toContain("Running · 0s");
  2937. expect(rendered).not.toContain("Running · Read");
  2938. expect(rendered).not.toContain("MCode · Running");
  2939. expect(rendered).toContain("Ctrl+O details");
  2940. expect(rendered).toContain("Esc stop");
  2941. expect(rendered).not.toContain("Enter run next");
  2942. expect(rendered).not.toContain("Message · Enter send");
  2943. expect(rendered).not.toContain("Follow-up");
  2944. expect(rendered).not.toContain("waiting");
  2945. });
  2946. await app.submit("Review the tests next");
  2947. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  2948. expect(app.editor.getText()).toBe("Review the tests next");
  2949. expect(app.tui.render(80).join("\n")).toContain("Esc to interrupt");
  2950. finishTool?.();
  2951. await submission;
  2952. });
  2953. it("refreshes the running queue hint from the same bindings as the hotkeys panel", async () => {
  2954. const keybindings = createTuiHostKeybindings({
  2955. platform: "linux",
  2956. suspendSupported: true,
  2957. });
  2958. const runtime = createRuntime();
  2959. let finishTurn: (() => void) | undefined;
  2960. vi.mocked(runtime.sendMessage).mockImplementation(
  2961. async function* sendMessage() {
  2962. yield {
  2963. type: "delta",
  2964. turnId: "turn-custom-queue",
  2965. thinking: "Inspecting the repository",
  2966. };
  2967. await new Promise<void>((resolve) => {
  2968. finishTurn = resolve;
  2969. });
  2970. yield { type: "done", turnId: "turn-custom-queue" };
  2971. },
  2972. );
  2973. const app = createTuiApp({
  2974. runtime,
  2975. terminal: new FakeTerminal(),
  2976. version: "0.1.0",
  2977. workspaceDir: "/workspace",
  2978. keybindings: keybindings.registry,
  2979. });
  2980. await app.ready;
  2981. keybindings.manager.setUserBindings({ "run.queue-draft": "ctrl+enter" });
  2982. const submission = app.submit("Inspect the repository");
  2983. try {
  2984. await vi.waitFor(() => {
  2985. const rendered = stripAnsi(app.tui.render(100).join("\n"));
  2986. expect(rendered).toContain("Running");
  2987. expect(rendered).toContain("Ctrl+Enter queue");
  2988. expect(rendered).not.toContain("Alt+Enter queue");
  2989. expect(
  2990. keybindings.registry
  2991. .helpRows()
  2992. .find((row) => row.ids.includes("run.queue-draft"))?.keys,
  2993. ).toBe("Ctrl+Enter");
  2994. });
  2995. } finally {
  2996. finishTurn?.();
  2997. await submission;
  2998. await app.stop();
  2999. }
  3000. });
  3001. it("shows running Thinking in chat and opens the full Transcript with /transcript", async () => {
  3002. const terminal = new FakeTerminal();
  3003. const runtime = createRuntime();
  3004. let finishThinking: (() => void) | undefined;
  3005. vi.mocked(runtime.sendMessage).mockImplementation(
  3006. async function* sendMessage() {
  3007. yield {
  3008. type: "delta",
  3009. turnId: "turn-running-thinking",
  3010. thinking: "Inspecting the repository",
  3011. };
  3012. await new Promise<void>((resolve) => {
  3013. finishThinking = resolve;
  3014. });
  3015. yield { type: "done", turnId: "turn-running-thinking" };
  3016. },
  3017. );
  3018. const app = createTuiApp({
  3019. runtime,
  3020. terminal,
  3021. version: "0.1.0",
  3022. workspaceDir: "/workspace",
  3023. });
  3024. app.start();
  3025. await app.ready;
  3026. const submission = app.submit("Inspect the repository");
  3027. const countThinkingBodyRows = (rendered: string): number =>
  3028. rendered
  3029. .split("\n")
  3030. .filter(
  3031. (line) =>
  3032. line.includes("Inspecting the repository") &&
  3033. !line.includes("MCode"),
  3034. ).length;
  3035. let expandedThinkingRows = 0;
  3036. try {
  3037. await vi.waitFor(() => {
  3038. const thinking = app.transcript
  3039. .snapshot()
  3040. .find((cell) => cell.kind === "thinking");
  3041. expect(thinking?.content).toBe("Inspecting the repository");
  3042. expect(thinking?.expanded).toBeUndefined();
  3043. const rendered = app.tui.render(80).join("\n");
  3044. expect(rendered).toContain("Running");
  3045. expect(rendered).not.toContain("Running · 0s");
  3046. expect(rendered).toContain(`${formatTuiShortcut("alt+enter")} queue`);
  3047. expect(rendered).toContain("Enter steer");
  3048. expect(rendered).not.toContain(`${formatTuiShortcut("ctrl+x")} steer`);
  3049. expect(rendered).toContain("Ctrl+O details");
  3050. expect(rendered).toContain("Esc stop");
  3051. expect(rendered).toContain("Thinking…");
  3052. expect(rendered).not.toContain("MCode ·");
  3053. expect(rendered).not.toContain("Thinking · Inspecting the repository");
  3054. expandedThinkingRows = countThinkingBodyRows(rendered);
  3055. expect(expandedThinkingRows).toBeGreaterThan(0);
  3056. });
  3057. await app.submit("/transcript");
  3058. await vi.waitFor(() => {
  3059. const rendered = renderTerminalViewport(app, terminal);
  3060. expect(app.surfaceHost.getActiveSurface()).toEqual({
  3061. kind: "feature",
  3062. id: "transcript",
  3063. });
  3064. expect(rendered).toContain("Transcript");
  3065. expect(rendered).not.toContain("Inspecting the repository");
  3066. expect(countThinkingBodyRows(rendered)).toBeLessThan(
  3067. expandedThinkingRows,
  3068. );
  3069. });
  3070. terminal.input?.("\x14");
  3071. expect(app.surfaceHost.getActiveSurface()).toEqual({
  3072. kind: "feature",
  3073. id: "transcript",
  3074. });
  3075. finishThinking?.();
  3076. finishThinking = undefined;
  3077. await submission;
  3078. expect(app.surfaceHost.getActiveSurface()).toEqual({
  3079. kind: "feature",
  3080. id: "transcript",
  3081. });
  3082. expect(app.controller.snapshot().activeTurnId).toBeUndefined();
  3083. expect(
  3084. app.transcript.snapshot().find((cell) => cell.kind === "thinking"),
  3085. ).toMatchObject({
  3086. status: "succeeded",
  3087. });
  3088. terminal.input?.("\u001B");
  3089. await vi.waitFor(() => {
  3090. const rendered = app.tui.render(80).join("\n");
  3091. expect(app.surfaceHost.getActiveSurface()).toEqual({
  3092. kind: "chat",
  3093. id: "chat",
  3094. });
  3095. expect(rendered).toContain("Message · Enter send");
  3096. expect(rendered).not.toContain("Running");
  3097. });
  3098. } finally {
  3099. finishThinking?.();
  3100. await submission;
  3101. await app.stop();
  3102. }
  3103. });
  3104. it("toggles hidden and full inline Tool output with Ctrl+O", async () => {
  3105. const terminal = new FakeTerminal();
  3106. const app = createTuiApp({
  3107. runtime: createRuntime(),
  3108. terminal,
  3109. version: "0.1.0",
  3110. workspaceDir: "/workspace",
  3111. });
  3112. app.start();
  3113. await app.ready;
  3114. app.transcript.upsert({
  3115. id: "tool-detail-toggle",
  3116. kind: "tool",
  3117. status: "succeeded",
  3118. title: "bash",
  3119. content: '{"command":"pnpm test"}',
  3120. detail: [
  3121. "result line 1",
  3122. "result line 2",
  3123. "result line 3",
  3124. "result line 4",
  3125. ].join("\n"),
  3126. createdAtMs: 1,
  3127. });
  3128. expect(app.tui.render(80).join("\n")).not.toContain("result line 1");
  3129. expect(app.tui.render(80).join("\n")).not.toContain("result line 4");
  3130. terminal.input?.("\x0f");
  3131. const detailed = app.tui.render(80).join("\n");
  3132. expect(detailed).toContain("result line 1");
  3133. expect(detailed).toContain("result line 3");
  3134. expect(detailed).toContain("result line 4");
  3135. expect(detailed).not.toContain("Details expanded");
  3136. terminal.input?.("\x0f");
  3137. const compact = app.tui.render(80).join("\n");
  3138. expect(compact).not.toContain("result line 1");
  3139. expect(compact).not.toContain("result line 3");
  3140. expect(compact).not.toContain("result line 4");
  3141. expect(compact).not.toContain("Details collapsed");
  3142. await app.stop();
  3143. });
  3144. it("uses Ctrl+T for tasks while Ctrl+O remains scoped to transcript details", async () => {
  3145. const terminal = new FakeTerminal();
  3146. const app = createTuiApp({
  3147. runtime: createRuntime(),
  3148. terminal,
  3149. version: "0.1.0",
  3150. workspaceDir: "/workspace",
  3151. });
  3152. app.start();
  3153. await app.ready;
  3154. app.controller.applyRuntimeTurnEvent("turn-todo", {
  3155. type: "generic",
  3156. eventType: "todo_updated",
  3157. turnId: "turn-todo",
  3158. data: {
  3159. todos: [
  3160. { content: "Inspect Desktop behavior", status: "completed" },
  3161. { content: "Polish the task rail", status: "in_progress" },
  3162. { content: "Run focused tests", status: "pending" },
  3163. { content: "Review narrow layouts", status: "pending" },
  3164. { content: "Update user documentation", status: "pending" },
  3165. { content: "Publish the test package", status: "pending" },
  3166. ],
  3167. },
  3168. });
  3169. const compact = app.tui.render(80).join("\n");
  3170. expect(compact).toContain("✓ Inspect Desktop behavior");
  3171. expect(compact).toContain("● Polish the task rail");
  3172. expect(compact).toContain("Ctrl+T expand");
  3173. expect(compact).not.toContain("Publish the test package");
  3174. expect(compact).not.toContain("todo_updated");
  3175. terminal.input?.("\x0f");
  3176. const transcriptDetailed = app.tui.render(80).join("\n");
  3177. expect(transcriptDetailed).toContain("Ctrl+T expand");
  3178. expect(transcriptDetailed).not.toContain("Publish the test package");
  3179. terminal.input?.("\x14");
  3180. const tasksExpanded = app.tui.render(80).join("\n");
  3181. expect(tasksExpanded).toContain(
  3182. "Todo list 1/6 · 5 remaining · Ctrl+T compact",
  3183. );
  3184. expect(tasksExpanded).toContain("Publish the test package");
  3185. terminal.input?.("\x0f");
  3186. expect(app.tui.render(80).join("\n")).toContain("Publish the test package");
  3187. app.controller.applyRuntimeTurnEvent("turn-todo", {
  3188. type: "generic",
  3189. eventType: "todo_updated",
  3190. turnId: "turn-todo",
  3191. data: {
  3192. todos: [
  3193. { content: "Inspect Desktop behavior", status: "completed" },
  3194. { content: "Polish the task rail", status: "completed" },
  3195. { content: "Run focused tests", status: "completed" },
  3196. { content: "Review narrow layouts", status: "completed" },
  3197. { content: "Update user documentation", status: "completed" },
  3198. { content: "Publish the test package", status: "completed" },
  3199. ],
  3200. },
  3201. });
  3202. expect(app.tui.render(80).join("\n")).toContain(
  3203. "✓ Todo list 6/6 completed",
  3204. );
  3205. await app.stop();
  3206. });
  3207. it("keeps settled Thinking hidden until Ctrl+O requests transcript details", async () => {
  3208. const terminal = new FakeTerminal();
  3209. const app = createTuiApp({
  3210. runtime: createRuntime(),
  3211. terminal,
  3212. version: "0.1.0",
  3213. workspaceDir: "/workspace",
  3214. });
  3215. app.start();
  3216. await app.ready;
  3217. app.transcript.upsert({
  3218. id: "thinking-detail-toggle",
  3219. kind: "thinking",
  3220. status: "succeeded",
  3221. content: "Private settled reasoning",
  3222. durationMs: 3_200,
  3223. createdAtMs: 1,
  3224. updatedAtMs: 3_201,
  3225. });
  3226. const compact = app.tui.render(80).join("\n");
  3227. expect(compact).toContain("Thought for 3.2s");
  3228. expect(compact).not.toContain("Private settled reasoning");
  3229. terminal.input?.("\x0f");
  3230. expect(app.tui.render(80).join("\n")).toContain(
  3231. "Private settled reasoning",
  3232. );
  3233. terminal.input?.("\x0f");
  3234. expect(app.tui.render(80).join("\n")).not.toContain(
  3235. "Private settled reasoning",
  3236. );
  3237. await app.stop();
  3238. });
  3239. it("returns from the conversation surface to Welcome after /new", async () => {
  3240. const terminal = new FakeTerminal();
  3241. const runtime = createRuntime();
  3242. const app = createTuiApp({
  3243. runtime,
  3244. terminal,
  3245. version: "0.1.0",
  3246. workspaceDir: "/workspace",
  3247. });
  3248. await app.ready;
  3249. await app.submit("Start a conversation");
  3250. expect(app.getSurface()).toBe("conversation");
  3251. await app.submit("/new");
  3252. expect(app.getSurface()).toBe("welcome");
  3253. expect(app.transcript.snapshot()).toEqual([]);
  3254. });
  3255. it("clears into a fresh conversation while keeping the previous session resumable", async () => {
  3256. const terminal = new FakeTerminal();
  3257. const runtime = createRuntime();
  3258. const app = createTuiApp({
  3259. runtime,
  3260. terminal,
  3261. version: "0.1.0",
  3262. workspaceDir: "/workspace",
  3263. });
  3264. await app.ready;
  3265. await app.submit("Keep this conversation");
  3266. expect(app.controller.snapshot().session?.sessionId).toBe("session-1");
  3267. await app.submit("/clear");
  3268. expect(app.getSurface()).toBe("welcome");
  3269. expect(app.transcript.snapshot()).toEqual([]);
  3270. expect(app.controller.snapshot()).toMatchObject({
  3271. status: "idle",
  3272. session: undefined,
  3273. sessions: [expect.objectContaining({ sessionId: "session-1" })],
  3274. });
  3275. expect(runtime.archiveSession).not.toHaveBeenCalled();
  3276. });
  3277. it("opens read-only Help above the Composer without using a TUI overlay", async () => {
  3278. const terminal = new FakeTerminal();
  3279. const runtime = createRuntime();
  3280. const app = createTuiApp({
  3281. runtime,
  3282. terminal,
  3283. version: "0.1.0",
  3284. workspaceDir: "/workspace",
  3285. });
  3286. const showOverlay = vi.spyOn(app.tui, "showOverlay");
  3287. app.start();
  3288. await app.ready;
  3289. const modelRequestsBeforeHelp = vi.mocked(runtime.listModels).mock.calls
  3290. .length;
  3291. const activeRunRequestsBeforeHelp = vi.mocked(runtime.getActiveRun).mock
  3292. .calls.length;
  3293. await app.submit("/help");
  3294. expect(runtime.sendMessage).not.toHaveBeenCalled();
  3295. expect(app.transcript.snapshot()).toEqual([]);
  3296. expect(app.tui.hasOverlay()).toBe(false);
  3297. expect(app.interaction.isActive()).toBe(true);
  3298. expect(terminal.mouseTracking).toBe(false);
  3299. terminal.input?.("m");
  3300. terminal.input?.("\r");
  3301. expect(app.tui.hasOverlay()).toBe(false);
  3302. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  3303. expect(app.editor.getText()).toBe("");
  3304. expect(runtime.listModels).toHaveBeenCalledTimes(modelRequestsBeforeHelp);
  3305. expect(runtime.getActiveRun).toHaveBeenCalledTimes(
  3306. activeRunRequestsBeforeHelp,
  3307. );
  3308. expect(showOverlay).not.toHaveBeenCalled();
  3309. await app.stop();
  3310. });
  3311. it("lets Help use the available terminal height instead of capping it at twelve rows", async () => {
  3312. const terminal = new FakeTerminal();
  3313. terminal.rows = 30;
  3314. const app = createTuiApp({
  3315. runtime: createRuntime(),
  3316. terminal,
  3317. version: "0.1.0",
  3318. workspaceDir: "/workspace",
  3319. });
  3320. app.start();
  3321. await app.submit("/help");
  3322. expect(app.interaction.current()?.render?.(terminal.columns)).toHaveLength(
  3323. 24,
  3324. );
  3325. terminal.rows = 18;
  3326. expect(app.interaction.current()?.render?.(terminal.columns)).toHaveLength(
  3327. 12,
  3328. );
  3329. await app.stop();
  3330. });
  3331. it("keeps steer executable and exposes it in slash-command discovery", async () => {
  3332. const terminal = new FakeTerminal();
  3333. const runtime = createRuntime();
  3334. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
  3335. schemaVersion: 1,
  3336. sessionId,
  3337. state: "running",
  3338. turnId: "turn-active",
  3339. actions: { steer: true },
  3340. }));
  3341. vi.mocked(runtime.steer).mockResolvedValue({
  3342. turnId: "turn-active",
  3343. mode: "steered",
  3344. });
  3345. const app = createTuiApp({
  3346. runtime,
  3347. terminal,
  3348. version: "0.1.0",
  3349. workspaceDir: "/workspace",
  3350. });
  3351. app.start();
  3352. await app.submit("Create session");
  3353. await app.submit("/help");
  3354. const helpPanel = app.interaction.current();
  3355. expect(helpPanel).toBeDefined();
  3356. expect(app.tui.hasOverlay()).toBe(false);
  3357. const helpPages: string[] = [];
  3358. for (let page = 0; page < 20; page += 1) {
  3359. const current = helpPanel?.render?.(100).join("\n") ?? "";
  3360. if (current === helpPages.at(-1)) break;
  3361. helpPages.push(current);
  3362. helpPanel?.handleInput?.("\x1b[6~");
  3363. }
  3364. const help = helpPages.join("\n");
  3365. expect(help).toContain("/steer <message>");
  3366. expect(help).not.toContain("/send-now");
  3367. expect(help).not.toContain("/retry");
  3368. helpPanel?.handleInput?.("\x1b");
  3369. await app.submit("/steer focus on the failing test");
  3370. expect(runtime.steer).toHaveBeenCalledWith(
  3371. expect.objectContaining({
  3372. sessionId: "session-1",
  3373. source: "api",
  3374. message: { content: "focus on the failing test" },
  3375. producerId: "mcode",
  3376. idempotencyKey: expect.stringMatching(/^run_action_/u),
  3377. }),
  3378. );
  3379. await app.stop();
  3380. });
  3381. it("refreshes Runtime steer capability before Enter submits the active Draft", async () => {
  3382. const terminal = new FakeTerminal();
  3383. const runtime = createRuntime();
  3384. let finishTurn: (() => void) | undefined;
  3385. let consumeSteer: (() => void) | undefined;
  3386. const steerConsumptionReady = new Promise<void>((resolve) => {
  3387. consumeSteer = resolve;
  3388. });
  3389. let steerAvailable = false;
  3390. vi.mocked(runtime.sendMessage).mockImplementation(
  3391. async function* sendMessage() {
  3392. yield {
  3393. type: "delta",
  3394. turnId: "turn-active",
  3395. content: "Working on it",
  3396. };
  3397. await steerConsumptionReady;
  3398. yield {
  3399. type: "message",
  3400. message: {
  3401. id: "message-steer",
  3402. turnId: "turn-active",
  3403. role: "user",
  3404. content: "focus on the failing test",
  3405. },
  3406. };
  3407. await new Promise<void>((resolve) => {
  3408. finishTurn = resolve;
  3409. });
  3410. yield { type: "done", turnId: "turn-active" };
  3411. },
  3412. );
  3413. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) =>
  3414. steerAvailable
  3415. ? {
  3416. schemaVersion: 1,
  3417. sessionId,
  3418. state: "running",
  3419. turnId: "turn-active",
  3420. actions: { steer: true },
  3421. }
  3422. : {
  3423. schemaVersion: 1,
  3424. sessionId,
  3425. state: "idle",
  3426. actions: { steer: false },
  3427. },
  3428. );
  3429. vi.mocked(runtime.steer).mockResolvedValue({
  3430. turnId: "turn-active",
  3431. mode: "steered",
  3432. });
  3433. const app = createTuiApp({
  3434. runtime,
  3435. terminal,
  3436. version: "0.1.0",
  3437. workspaceDir: "/workspace",
  3438. });
  3439. app.start();
  3440. await app.ready;
  3441. const submission = app.submit("Inspect the failure");
  3442. try {
  3443. await vi.waitFor(() =>
  3444. expect(app.tui.render(80).join("\n")).toContain("Running"),
  3445. );
  3446. steerAvailable = true;
  3447. terminal.input?.("focus on the failing test");
  3448. terminal.input?.("\r");
  3449. expect(app.editor.getText()).toBe("");
  3450. await vi.waitFor(() =>
  3451. expect(runtime.steer).toHaveBeenCalledWith(
  3452. expect.objectContaining({
  3453. sessionId: "session-1",
  3454. source: "api",
  3455. message: { content: "focus on the failing test" },
  3456. producerId: "mcode",
  3457. idempotencyKey: expect.stringMatching(/^run_action_/u),
  3458. requestedTurnId: "turn-active",
  3459. }),
  3460. ),
  3461. );
  3462. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  3463. kind: "user",
  3464. status: "pending",
  3465. content: "focus on the failing test",
  3466. userPresentation: "pending-steer",
  3467. });
  3468. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  3469. "↳ Next · focus on the failing test",
  3470. );
  3471. consumeSteer?.();
  3472. await vi.waitFor(() =>
  3473. expect(
  3474. app.transcript.snapshot().filter((cell) => cell.kind === "user"),
  3475. ).toEqual([
  3476. expect.objectContaining({ content: "Inspect the failure" }),
  3477. expect.objectContaining({
  3478. status: "succeeded",
  3479. content: "focus on the failing test",
  3480. sourceMessageId: "message-steer",
  3481. userPresentation: undefined,
  3482. }),
  3483. ]),
  3484. );
  3485. const rendered = app.tui.render(80).join("\n");
  3486. expect(rendered).toContain("Inspect the failure");
  3487. expect(rendered).toContain("focus on the failing test");
  3488. expect(stripAnsi(rendered)).not.toContain("↳ Next ·");
  3489. expect(app.editor.getText()).toBe("");
  3490. } finally {
  3491. consumeSteer?.();
  3492. await vi.waitFor(() => expect(finishTurn).toEqual(expect.any(Function)));
  3493. finishTurn?.();
  3494. await submission;
  3495. await app.stop();
  3496. }
  3497. });
  3498. it("queues with Alt+Enter, restores with Option+Up, then steers with Enter", async () => {
  3499. const terminal = new FakeTerminal();
  3500. const runtime = createRuntime();
  3501. const queuedItems: TuiQueuedMessage[] = [];
  3502. let finishTurn: (() => void) | undefined;
  3503. vi.mocked(runtime.sendMessage).mockImplementation(
  3504. async function* sendMessage() {
  3505. yield {
  3506. type: "delta",
  3507. turnId: "turn-active",
  3508. content: "Working on it",
  3509. };
  3510. await new Promise<void>((resolve) => {
  3511. finishTurn = resolve;
  3512. });
  3513. yield { type: "done", turnId: "turn-active" };
  3514. },
  3515. );
  3516. vi.mocked(runtime.enqueueMessage).mockImplementation(
  3517. async (sessionId, content) => {
  3518. const item: TuiQueuedMessage = {
  3519. itemId: "queue-guidance",
  3520. sessionId,
  3521. status: "queued",
  3522. source: "api",
  3523. content,
  3524. };
  3525. queuedItems.push(item);
  3526. return {
  3527. itemId: item.itemId,
  3528. status: item.status,
  3529. position: queuedItems.length,
  3530. };
  3531. },
  3532. );
  3533. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  3534. ...queuedItems,
  3535. ]);
  3536. vi.mocked(runtime.deleteQueuedMessage).mockImplementation(
  3537. async (_sessionId, itemId) => {
  3538. const index = queuedItems.findIndex((item) => item.itemId === itemId);
  3539. return index >= 0 ? queuedItems.splice(index, 1)[0] : undefined;
  3540. },
  3541. );
  3542. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
  3543. schemaVersion: 1,
  3544. sessionId,
  3545. state: "running",
  3546. turnId: "turn-active",
  3547. actions: { steer: true },
  3548. }));
  3549. const app = createTuiApp({
  3550. runtime,
  3551. terminal,
  3552. version: "0.1.0",
  3553. workspaceDir: "/workspace",
  3554. });
  3555. app.start();
  3556. await app.ready;
  3557. const submission = app.submit("Inspect the failure");
  3558. try {
  3559. await vi.waitFor(() =>
  3560. expect(app.tui.render(80).join("\n")).toContain("Running"),
  3561. );
  3562. terminal.input?.("Use the preview branch directly");
  3563. terminal.input?.("\x1b\r");
  3564. await vi.waitFor(() =>
  3565. expect(app.tui.render(80).join("\n")).toContain(
  3566. "Use the preview branch directly",
  3567. ),
  3568. );
  3569. await vi.waitFor(() =>
  3570. expect(runtime.listQueuedMessages).toHaveBeenCalledWith("session-1"),
  3571. );
  3572. expect(app.editor.getText()).toBe("");
  3573. terminal.input?.("\x1b[1;3A");
  3574. await vi.waitFor(() =>
  3575. expect(app.editor.getText()).toBe("Use the preview branch directly"),
  3576. );
  3577. expect(runtime.deleteQueuedMessage).toHaveBeenCalledWith(
  3578. "session-1",
  3579. "queue-guidance",
  3580. );
  3581. expect(runtime.steerQueuedMessage).not.toHaveBeenCalled();
  3582. await vi.waitFor(() =>
  3583. expect(app.tui.render(80).join("\n")).not.toContain("Queued ·"),
  3584. );
  3585. terminal.input?.("\r");
  3586. await vi.waitFor(() =>
  3587. expect(runtime.steer).toHaveBeenCalledWith(
  3588. expect.objectContaining({
  3589. sessionId: "session-1",
  3590. message: { content: "Use the preview branch directly" },
  3591. requestedTurnId: "turn-active",
  3592. }),
  3593. ),
  3594. );
  3595. expect(app.editor.getText()).toBe("");
  3596. } finally {
  3597. finishTurn?.();
  3598. await submission;
  3599. await app.stop();
  3600. }
  3601. });
  3602. it("renders /context from the Runtime-owned persisted context usage", async () => {
  3603. const runtime = createRuntime();
  3604. vi.mocked(runtime.getContextSnapshot).mockResolvedValue({
  3605. status: "live",
  3606. model: { provider: "minimax", id: "MiniMax-M3", contextWindow: 10_000 },
  3607. contextUsage: {
  3608. contextWindowTokens: 10_000,
  3609. usedTokens: 3_000,
  3610. totalCountSource: "PROVIDER_USAGE_ANCHORED",
  3611. components: [
  3612. { kind: "SYSTEM_PROMPT", tokens: 1_000 },
  3613. { kind: "MEMORY", tokens: 0 },
  3614. { kind: "TOOLS", tokens: 0 },
  3615. { kind: "SKILLS", tokens: 0 },
  3616. { kind: "MESSAGES", tokens: 2_000 },
  3617. { kind: "OTHER", tokens: 0 },
  3618. ],
  3619. },
  3620. });
  3621. const app = createTuiApp({
  3622. runtime,
  3623. terminal: new FakeTerminal(),
  3624. version: "0.1.0",
  3625. workspaceDir: "/workspace",
  3626. });
  3627. await app.submit("Create session");
  3628. const transcriptBeforeContext = app.transcript.snapshot();
  3629. await app.submit("/context");
  3630. expect(app.transcript.snapshot()).toEqual(transcriptBeforeContext);
  3631. expect(app.interaction.current()).toBeDefined();
  3632. const rendered = app.tui.render(80).join("\n");
  3633. expect(rendered).toContain("Context");
  3634. expect(rendered).toContain("3k/10k tokens (30% used)");
  3635. expect(rendered).toContain("Usage by category");
  3636. expect(rendered).toContain("Messages");
  3637. expect(rendered).toMatch(/[⛁⛀⛶]/u);
  3638. app.interaction.current()?.handleInput?.("\x1b");
  3639. expect(app.interaction.current()).toBeUndefined();
  3640. expect(app.transcript.snapshot()).toEqual(transcriptBeforeContext);
  3641. });
  3642. it("routes /init through the Runtime-owned init Skill and the normal Agent turn", async () => {
  3643. const terminal = new FakeTerminal();
  3644. const runtime = createRuntime();
  3645. vi.mocked(runtime.listSkills).mockResolvedValue({
  3646. skills: [
  3647. {
  3648. name: "init",
  3649. displayName: "Init",
  3650. description: "Analyze the codebase and generate AGENTS.md",
  3651. enabled: true,
  3652. sourceKind: "builtin",
  3653. },
  3654. ],
  3655. hasMore: false,
  3656. });
  3657. const app = createTuiApp({
  3658. runtime,
  3659. terminal,
  3660. version: "0.1.0",
  3661. workspaceDir: "/workspace",
  3662. });
  3663. app.start();
  3664. await app.ready;
  3665. await vi.waitFor(() => expect(runtime.listSkills).toHaveBeenCalled());
  3666. await app.submit("/init");
  3667. expect(runtime.sendMessage).toHaveBeenCalledWith(
  3668. expect.objectContaining({ id: "session-1", content: "/init" }),
  3669. expect.any(AbortSignal),
  3670. );
  3671. });
  3672. it("forwards literal slash-prefixed prompts without invoking local commands", async () => {
  3673. const runtime = createRuntime();
  3674. const app = createTuiApp({
  3675. runtime,
  3676. terminal: new FakeTerminal(),
  3677. version: "0.1.0",
  3678. workspaceDir: "/workspace",
  3679. });
  3680. const prompts = [
  3681. "/commands",
  3682. "/diff",
  3683. "/tool",
  3684. "/tools",
  3685. "/resumex",
  3686. "/renamex Renamed by a typo",
  3687. "/clearx",
  3688. "/tmp/sample-photo.JPG 用 read 工具直接读这个图片,告诉我是什么",
  3689. "/not-a-command explain what this text means",
  3690. "/context 这样还是会显示上下文信息",
  3691. ];
  3692. try {
  3693. app.start();
  3694. await app.ready;
  3695. for (const prompt of prompts) {
  3696. await app.submit(prompt);
  3697. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  3698. expect.objectContaining({ id: "session-1", content: prompt }),
  3699. expect.any(AbortSignal),
  3700. );
  3701. expect(app.interaction.current()).toBeUndefined();
  3702. expect(app.tui.hasOverlay()).toBe(false);
  3703. }
  3704. expect(runtime.sendMessage).toHaveBeenCalledTimes(prompts.length);
  3705. expect(runtime.renameSession).not.toHaveBeenCalled();
  3706. // Context metrics refresh independently; the overlay assertions above verify no local command ran.
  3707. expect(app.transcript.snapshot()).not.toContainEqual(
  3708. expect.objectContaining({ content: "Unknown command. Use /help." }),
  3709. );
  3710. } finally {
  3711. await app.stop();
  3712. }
  3713. });
  3714. it("keeps contextual commands local and submits other legacy names as prompts", async () => {
  3715. const terminal = new FakeTerminal();
  3716. const runtime = createRuntime();
  3717. const app = createTuiApp({
  3718. runtime,
  3719. terminal,
  3720. version: "0.1.0",
  3721. workspaceDir: "/workspace",
  3722. });
  3723. await app.submit("/queue");
  3724. expect(runtime.listQueuedMessages).not.toHaveBeenCalled();
  3725. expect(app.transcript.snapshot()).toEqual([]);
  3726. expect(app.tui.render(80).join("\n")).toContain(
  3727. "No messages are waiting and no response is currently running.",
  3728. );
  3729. await app.submit("/queue-clear");
  3730. expect(runtime.deleteQueuedMessage).not.toHaveBeenCalled();
  3731. await app.submit("/send-now do this first");
  3732. await app.submit("/retry");
  3733. expect(
  3734. vi
  3735. .mocked(runtime.sendMessage)
  3736. .mock.calls.map(([request]) => request.content),
  3737. ).toEqual(["/queue-clear", "/send-now do this first"]);
  3738. expect(app.tui.render(80).join("\n")).toContain(
  3739. "There is no failed response to retry in this Session.",
  3740. );
  3741. });
  3742. it("resends the failed user submission through /retry instead of sending the command as text", async () => {
  3743. const terminal = new FakeTerminal();
  3744. const runtime = createRuntime();
  3745. let attempt = 0;
  3746. vi.mocked(runtime.sendMessage).mockImplementation(
  3747. async function* sendMessage() {
  3748. attempt += 1;
  3749. if (attempt === 1) {
  3750. yield { type: "error", message: "terminated" };
  3751. return;
  3752. }
  3753. yield { type: "delta", content: "Recovered response" };
  3754. yield { type: "done" };
  3755. },
  3756. );
  3757. const app = createTuiApp({
  3758. runtime,
  3759. terminal,
  3760. version: "0.1.0",
  3761. workspaceDir: "/workspace",
  3762. });
  3763. await app.submit("Explain this failure");
  3764. expect(app.tui.render(100).join("\n")).toContain(
  3765. "The model connection ended before the response was completed.",
  3766. );
  3767. expect(app.tui.render(100).join("\n")).toContain(
  3768. "Run /retry to resend your last message.",
  3769. );
  3770. await app.submit("/retry");
  3771. expect(
  3772. vi
  3773. .mocked(runtime.sendMessage)
  3774. .mock.calls.map(([request]) => request.content),
  3775. ).toEqual(["Explain this failure", "Explain this failure"]);
  3776. expect(
  3777. vi
  3778. .mocked(runtime.sendMessage)
  3779. .mock.calls.some(([request]) => request.content === "/retry"),
  3780. ).toBe(false);
  3781. expect(app.transcript.snapshot()).toContainEqual(
  3782. expect.objectContaining({
  3783. kind: "assistant",
  3784. content: "Recovered response",
  3785. }),
  3786. );
  3787. await app.stop();
  3788. });
  3789. it("uses Runtime retry-continuation when a terminal failure has no local submission snapshot", async () => {
  3790. const terminal = new FakeTerminal();
  3791. const runtime = createRuntime();
  3792. const restoredSession = {
  3793. sessionId: "session-1",
  3794. title: "Restored session",
  3795. workspaceDir: "/workspace",
  3796. status: "error",
  3797. errorMessage: "terminated",
  3798. };
  3799. vi.mocked(runtime.listSessions).mockResolvedValue([restoredSession]);
  3800. vi.mocked(runtime.getSession).mockResolvedValue(restoredSession);
  3801. const app = createTuiApp({
  3802. runtime,
  3803. terminal,
  3804. version: "0.1.0",
  3805. workspaceDir: "/workspace",
  3806. });
  3807. app.start();
  3808. await app.ready;
  3809. await app.submit("/resume session-1");
  3810. expect(app.tui.render(100).join("\n")).toContain(
  3811. "The model connection ended before the response was completed.",
  3812. );
  3813. await app.submit("/retry");
  3814. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  3815. expect.objectContaining({
  3816. id: "session-1",
  3817. content: "",
  3818. clientIntent: "retry-continuation",
  3819. }),
  3820. expect.any(AbortSignal),
  3821. );
  3822. await app.stop();
  3823. });
  3824. it("reports service authentication failures without assuming the user needs to sign in", async () => {
  3825. const runtime = createRuntime();
  3826. vi.mocked(runtime.sendMessage).mockImplementation(
  3827. async function* sendMessage() {
  3828. yield { type: "error", message: "authentication failed" };
  3829. },
  3830. );
  3831. const app = createTuiApp({
  3832. runtime,
  3833. terminal: new FakeTerminal(),
  3834. version: "0.1.0",
  3835. workspaceDir: "/workspace",
  3836. });
  3837. await app.submit("Use the protected model");
  3838. expect(app.tui.render(100).join("\n")).toContain(
  3839. "The service rejected request authentication.",
  3840. );
  3841. expect(app.tui.render(100).join("\n")).not.toContain("Run /login");
  3842. expect(app.tui.render(100).join("\n")).not.toContain("Run /retry");
  3843. await app.submit("/retry");
  3844. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  3845. await app.stop();
  3846. });
  3847. it("cycles the shared permission mode with Alt+M without repeating the shortcut", async () => {
  3848. const terminal = new FakeTerminal();
  3849. const runtime = createRuntime();
  3850. const app = createTuiApp({
  3851. runtime,
  3852. terminal,
  3853. version: "0.1.0",
  3854. workspaceDir: "/workspace",
  3855. });
  3856. app.start();
  3857. await app.ready;
  3858. expect(app.tui.render(80).join("\n")).toContain("Auto");
  3859. expect(app.tui.render(80).join("\n")).not.toContain("Shift+Tab");
  3860. expect(app.tui.render(80).join("\n")).not.toContain(
  3861. "Shift+Tab switch mode",
  3862. );
  3863. terminal.input?.("\x1bm");
  3864. await vi.waitFor(() => {
  3865. expect(runtime.setPermissionMode).toHaveBeenCalledWith(
  3866. "bypassPermissions",
  3867. );
  3868. const rendered = app.tui.render(80).join("\n");
  3869. expect(rendered).toContain("Full access");
  3870. expect(rendered).not.toContain("Shift+Tab");
  3871. expect(rendered.match(/Full access/g)).toHaveLength(1);
  3872. expect(rendered).not.toContain("Desktop permissions:");
  3873. });
  3874. await app.stop();
  3875. });
  3876. it("projects Token Plan warnings into the status rail", async () => {
  3877. const terminal = new FakeTerminal();
  3878. const runtime = createRuntime();
  3879. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  3880. status: "ready",
  3881. defaultModel: "minimax/MiniMax-M2.7",
  3882. providerId: "minimax",
  3883. modelId: "MiniMax-M2.7",
  3884. authMode: "managed-login",
  3885. managedTokenPresent: true,
  3886. modelSource: "token-plan",
  3887. tokenPlanQuotaState: "available",
  3888. tokenPlanQuota: {
  3889. fiveHour: { remainingPercent: 30, unlimited: false },
  3890. weekly: { remainingPercent: 64, unlimited: false },
  3891. },
  3892. warnings: [],
  3893. });
  3894. const app = createTuiApp({
  3895. runtime,
  3896. terminal,
  3897. version: "0.1.0",
  3898. workspaceDir: "/workspace",
  3899. });
  3900. app.start();
  3901. await app.ready;
  3902. await app.submit("Measure this turn");
  3903. await vi.waitFor(() => {
  3904. const rendered = app.tui.render(120).join("\n");
  3905. expect(rendered).toContain("5h 30%");
  3906. expect(rendered).not.toContain("Week 64%");
  3907. });
  3908. await app.stop();
  3909. });
  3910. it("keeps Token Plan subscription state out of the status rail when no quota exists", async () => {
  3911. const terminal = new FakeTerminal();
  3912. const runtime = createRuntime();
  3913. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  3914. status: "ready",
  3915. defaultModel: "minimax/MiniMax-M3",
  3916. providerId: "minimax",
  3917. modelId: "MiniMax-M3",
  3918. authMode: "managed-login",
  3919. managedTokenPresent: true,
  3920. modelSource: "token-plan",
  3921. tokenPlanQuotaState: "not-subscribed",
  3922. warnings: [],
  3923. });
  3924. const app = createTuiApp({
  3925. runtime,
  3926. terminal,
  3927. version: "0.1.0",
  3928. workspaceDir: "/workspace",
  3929. });
  3930. app.start();
  3931. await app.ready;
  3932. await app.submit("Measure this turn");
  3933. await vi.waitFor(() => {
  3934. const rendered = app.tui.render(120).join("\n");
  3935. expect(rendered).toContain("✦ MiniMax M2.7");
  3936. expect(rendered).not.toMatch(/Context 5%|Quota|Plan|5h|Week/u);
  3937. });
  3938. await app.stop();
  3939. });
  3940. it("keeps the current permission mode when an Alt+M update fails", async () => {
  3941. const terminal = new FakeTerminal();
  3942. const runtime = createRuntime();
  3943. vi.mocked(runtime.setPermissionMode).mockRejectedValueOnce(
  3944. new Error("config is read-only"),
  3945. );
  3946. const app = createTuiApp({
  3947. runtime,
  3948. terminal,
  3949. version: "0.1.0",
  3950. workspaceDir: "/workspace",
  3951. });
  3952. app.start();
  3953. await app.ready;
  3954. terminal.input?.("\x1bm");
  3955. await vi.waitFor(() => {
  3956. expect(app.tui.render(80).join("\n")).toContain("Auto");
  3957. expect(app.tui.render(80).join("\n")).not.toContain("FULL");
  3958. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  3959. kind: "warning",
  3960. content:
  3961. "Permission mode was not changed: config is read-only. Retry /permission or Alt+M.",
  3962. });
  3963. });
  3964. await app.stop();
  3965. });
  3966. it("arms Plan with Shift+Tab and sends the one-shot Runtime intent", async () => {
  3967. const terminal = new FakeTerminal();
  3968. const runtime = createRuntime();
  3969. const app = createTuiApp({
  3970. runtime,
  3971. terminal,
  3972. version: "0.1.0",
  3973. workspaceDir: "/workspace",
  3974. });
  3975. app.start();
  3976. await app.ready;
  3977. terminal.input?.("\x1b[Z");
  3978. expect(app.tui.render(100).join("\n")).toContain("PLAN next");
  3979. expect(app.tui.render(100).join("\n")).toContain(
  3980. "Plan Mode · next message enters Plan",
  3981. );
  3982. terminal.input?.("计");
  3983. expect(app.tui.render(100).join("\n")).toContain(
  3984. "Plan Mode · next message enters Plan",
  3985. );
  3986. expect(app.tui.render(32).join("\n")).toContain("Plan Mode");
  3987. terminal.input?.("\x7f");
  3988. expect(app.editor.getText()).toBe("");
  3989. expect(app.tui.render(100).join("\n")).toContain(
  3990. "Plan Mode · next message enters Plan",
  3991. );
  3992. terminal.input?.("计");
  3993. terminal.input?.("划");
  3994. expect(app.editor.getText()).toBe("计划");
  3995. expect(app.tui.render(100).join("\n")).toContain("PLAN next");
  3996. expect(app.tui.render(100).join("\n")).toContain(
  3997. "Plan Mode · next message enters Plan",
  3998. );
  3999. terminal.input?.("\r");
  4000. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
  4001. await app.controller.whenIdle();
  4002. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4003. expect.objectContaining({
  4004. content: "计划",
  4005. clientIntent: "plan-entry",
  4006. }),
  4007. expect.any(AbortSignal),
  4008. );
  4009. expect(app.tui.render(100).join("\n")).toContain("PLAN");
  4010. expect(app.tui.render(100).join("\n")).toContain("Auto");
  4011. await app.stop();
  4012. });
  4013. it("keeps ordinary messages in Plan and exits only with an explicit one-shot intent", async () => {
  4014. const runtime = createRuntime();
  4015. const app = createTuiApp({
  4016. runtime,
  4017. terminal: new FakeTerminal(),
  4018. version: "0.1.0",
  4019. workspaceDir: "/workspace",
  4020. });
  4021. app.start();
  4022. await app.ready;
  4023. await app.submit("/plan on");
  4024. await app.submit("Draft the implementation plan");
  4025. await app.submit("Refine the verification section");
  4026. expect(runtime.sendMessage).toHaveBeenNthCalledWith(
  4027. 2,
  4028. expect.not.objectContaining({ clientIntent: expect.anything() }),
  4029. expect.any(AbortSignal),
  4030. );
  4031. expect(app.tui.render(100).join("\n")).toContain(
  4032. "/workspace │ PLAN │ Auto",
  4033. );
  4034. await app.submit("/plan off");
  4035. await app.submit("Implement the approved direction");
  4036. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  4037. expect.objectContaining({ clientIntent: "plan-exit" }),
  4038. expect.any(AbortSignal),
  4039. );
  4040. expect(app.tui.render(100).join("\n")).not.toContain("PLAN");
  4041. await app.stop();
  4042. });
  4043. it("keeps the one-shot Plan intent armed when direct admission rejects it", async () => {
  4044. const runtime = createRuntime();
  4045. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  4046. async function* rejectedAdmission() {
  4047. yield* [] as TuiStreamEvent[];
  4048. throw Object.assign(new Error("Plan entry is disabled"), {
  4049. code: "local_plan_entry_disabled",
  4050. });
  4051. },
  4052. );
  4053. const app = createTuiApp({
  4054. runtime,
  4055. terminal: new FakeTerminal(),
  4056. version: "0.1.0",
  4057. workspaceDir: "/workspace",
  4058. });
  4059. app.start();
  4060. await app.ready;
  4061. await app.submit("/plan on");
  4062. await app.submit("Plan this after the feature is enabled");
  4063. expect(app.tui.render(100).join("\n")).toContain("PLAN next");
  4064. await app.submit("Retry the same Plan intent");
  4065. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  4066. expect.objectContaining({ clientIntent: "plan-entry" }),
  4067. expect.any(AbortSignal),
  4068. );
  4069. await app.stop();
  4070. });
  4071. it("settles a Plan transition from authoritative Session metadata when the stream is empty", async () => {
  4072. const runtime = createRuntime();
  4073. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  4074. async function* emptyAcceptedStream() {
  4075. yield* [] as TuiStreamEvent[];
  4076. },
  4077. );
  4078. vi.mocked(runtime.getSession).mockResolvedValue({
  4079. sessionId: "session-1",
  4080. workspace: "/workspace",
  4081. interactionMode: "plan",
  4082. });
  4083. const app = createTuiApp({
  4084. runtime,
  4085. terminal: new FakeTerminal(),
  4086. version: "0.1.0",
  4087. workspaceDir: "/workspace",
  4088. });
  4089. app.start();
  4090. await app.ready;
  4091. await app.submit("/plan on");
  4092. await app.submit("Plan without emitting a stream event");
  4093. expect(runtime.getSession).toHaveBeenCalledWith("session-1");
  4094. expect(app.tui.render(100).join("\n")).toContain(
  4095. "/workspace │ PLAN │ Auto",
  4096. );
  4097. expect(app.tui.render(100).join("\n")).not.toContain("PLAN next");
  4098. await app.stop();
  4099. });
  4100. it("clears accepted Plan entry while authoritative metadata refresh is unavailable", async () => {
  4101. const runtime = createRuntime();
  4102. vi.mocked(runtime.getSession).mockRejectedValue(
  4103. new Error("metadata temporarily unavailable"),
  4104. );
  4105. const app = createTuiApp({
  4106. runtime,
  4107. terminal: new FakeTerminal(),
  4108. version: "0.1.0",
  4109. workspaceDir: "/workspace",
  4110. });
  4111. app.start();
  4112. await app.ready;
  4113. await app.submit("/plan on");
  4114. await app.submit("OK");
  4115. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4116. expect.objectContaining({ content: "OK", clientIntent: "plan-entry" }),
  4117. expect.any(AbortSignal),
  4118. );
  4119. expect(app.tui.render(100).join("\n")).not.toContain("/workspace │ PLAN");
  4120. expect(app.tui.render(100).join("\n")).not.toContain("DEFAULT next");
  4121. await app.stop();
  4122. });
  4123. it("preserves Plan intent through direct busy fallback into the Runtime Queue", async () => {
  4124. const runtime = createRuntime();
  4125. vi.mocked(runtime.listModels).mockResolvedValue([
  4126. {
  4127. providerId: "minimax",
  4128. modelId: "MiniMax-M2.7",
  4129. selected: true,
  4130. variant: "",
  4131. },
  4132. ]);
  4133. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  4134. async function* busyAdmission() {
  4135. yield* [] as TuiStreamEvent[];
  4136. throw Object.assign(new Error("Session is busy"), {
  4137. code: "local_session_busy",
  4138. });
  4139. },
  4140. );
  4141. const app = createTuiApp({
  4142. runtime,
  4143. terminal: new FakeTerminal(),
  4144. version: "0.1.0",
  4145. workspaceDir: "/workspace",
  4146. });
  4147. app.start();
  4148. await app.ready;
  4149. await app.submit("/plan on");
  4150. await app.submit("Queue this Plan request");
  4151. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  4152. "session-1",
  4153. "Queue this Plan request",
  4154. {
  4155. attachments: [],
  4156. clientIntent: "plan-entry",
  4157. model: { providerId: "minimax", modelId: "MiniMax-M2.7", variant: "" },
  4158. },
  4159. );
  4160. expect(app.tui.render(100).join("\n")).not.toContain("PLAN queued");
  4161. await app.stop();
  4162. });
  4163. it("binds a one-shot Plan intent to only the first concurrent submission", async () => {
  4164. let releaseFirstEvent: (() => void) | undefined;
  4165. const firstEventGate = new Promise<void>((resolve) => {
  4166. releaseFirstEvent = resolve;
  4167. });
  4168. const runtime = createRuntime();
  4169. vi.mocked(runtime.sendMessage).mockImplementation(
  4170. async function* delayedAdmission() {
  4171. await firstEventGate;
  4172. yield { type: "delta", content: "Planning" };
  4173. yield { type: "done" };
  4174. },
  4175. );
  4176. const app = createTuiApp({
  4177. runtime,
  4178. terminal: new FakeTerminal(),
  4179. version: "0.1.0",
  4180. workspaceDir: "/workspace",
  4181. });
  4182. app.start();
  4183. await app.ready;
  4184. await app.submit("/plan on");
  4185. const first = app.submit("Plan the implementation");
  4186. await vi.waitFor(() =>
  4187. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  4188. );
  4189. await app.submit("Queue a follow-up while admission is quiet");
  4190. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4191. expect.objectContaining({ clientIntent: "plan-entry" }),
  4192. expect.any(AbortSignal),
  4193. );
  4194. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  4195. "session-1",
  4196. "Queue a follow-up while admission is quiet",
  4197. {
  4198. attachments: [],
  4199. model: { providerId: "minimax", modelId: "MiniMax-M2.7" },
  4200. },
  4201. );
  4202. releaseFirstEvent?.();
  4203. await first;
  4204. await app.stop();
  4205. });
  4206. it("shows the Desktop-aligned confirmation when the Agent calls EnterPlanMode", async () => {
  4207. let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  4208. const runtime = createRuntime();
  4209. vi.mocked(runtime.watchEvents).mockImplementation(
  4210. async function* watchEvents(signal) {
  4211. const event = await new Promise<TuiRuntimeEvent | undefined>(
  4212. (resolve) => {
  4213. emitEvent = resolve;
  4214. signal.addEventListener("abort", () => resolve(undefined), {
  4215. once: true,
  4216. });
  4217. },
  4218. );
  4219. if (event) yield event;
  4220. await new Promise<void>((resolve) => {
  4221. signal.addEventListener("abort", resolve, { once: true });
  4222. });
  4223. },
  4224. );
  4225. const app = createTuiApp({
  4226. runtime,
  4227. terminal: new FakeTerminal(),
  4228. version: "0.1.0",
  4229. workspaceDir: "/workspace",
  4230. });
  4231. app.start();
  4232. await app.ready;
  4233. await app.submit("Plan a complex change");
  4234. await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
  4235. const askEvent = runtimeEvent({
  4236. type: "questionnaire.ask",
  4237. timestamp: Date.now(),
  4238. source: "runtime",
  4239. payload: {
  4240. sessionId: "session-1",
  4241. agentName: "mavis",
  4242. request: planEntryEventRequest("plan-entry-agent-tool"),
  4243. },
  4244. });
  4245. expect(askEvent).toMatchObject({
  4246. type: "questionnaire.ask",
  4247. sessionId: "session-1",
  4248. request: { id: "plan-entry-agent-tool", mode: "plan" },
  4249. });
  4250. emitEvent?.(askEvent);
  4251. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  4252. const panel = app.interaction.current();
  4253. const rendered = panel?.render?.(100).join("\n") ?? "";
  4254. expect(rendered).toContain("Use Plan mode?");
  4255. expect(rendered).toContain(
  4256. "Plan mode structures complex tasks before execution.",
  4257. );
  4258. expect(rendered).toContain("Continue with plan");
  4259. expect(rendered).toContain("Deny");
  4260. panel?.handleInput?.("\r");
  4261. await vi.waitFor(() =>
  4262. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  4263. "mavis",
  4264. "plan-entry-agent-tool",
  4265. [
  4266. {
  4267. stepId: "plan-enter",
  4268. selectedOptionIds: ["confirm"],
  4269. selectedOther: false,
  4270. },
  4271. ],
  4272. ),
  4273. );
  4274. await app.stop();
  4275. });
  4276. it("keeps a pending Plan exit armed when steer guides the current Plan Turn", async () => {
  4277. let finishTurn: (() => void) | undefined;
  4278. let interactionMode: "plan" | undefined;
  4279. const runtime = createRuntime();
  4280. vi.mocked(runtime.getSession).mockImplementation(async () => ({
  4281. sessionId: "session-1",
  4282. workspace: "/workspace",
  4283. ...(interactionMode ? { interactionMode } : {}),
  4284. }));
  4285. vi.mocked(runtime.sendMessage).mockImplementation(
  4286. async function* activePlanTurn() {
  4287. interactionMode = "plan";
  4288. yield { type: "delta", content: "Drafting the plan" };
  4289. await new Promise<void>((resolve) => {
  4290. finishTurn = resolve;
  4291. });
  4292. yield { type: "done" };
  4293. },
  4294. );
  4295. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
  4296. schemaVersion: 1,
  4297. sessionId,
  4298. state: "running",
  4299. turnId: "turn-plan",
  4300. actions: { steer: true },
  4301. }));
  4302. vi.mocked(runtime.steer).mockResolvedValue({
  4303. turnId: "turn-plan",
  4304. mode: "steered",
  4305. });
  4306. const app = createTuiApp({
  4307. runtime,
  4308. terminal: new FakeTerminal(),
  4309. version: "0.1.0",
  4310. workspaceDir: "/workspace",
  4311. });
  4312. app.start();
  4313. await app.ready;
  4314. await app.submit("/plan on");
  4315. const planTurn = app.submit("Draft a plan");
  4316. await vi.waitFor(() =>
  4317. expect(app.tui.render(100).join("\n")).toContain(
  4318. "/workspace │ PLAN │ Auto",
  4319. ),
  4320. );
  4321. await app.submit("/plan off");
  4322. await app.submit("/steer include rollback checks");
  4323. expect(runtime.steer).toHaveBeenCalledWith(
  4324. expect.objectContaining({
  4325. sessionId: "session-1",
  4326. message: { content: "include rollback checks" },
  4327. }),
  4328. );
  4329. expect(app.tui.render(100).join("\n")).toContain("DEFAULT next");
  4330. finishTurn?.();
  4331. await planTurn;
  4332. await app.stop();
  4333. });
  4334. it("does not arm a mode transition while a Plan Review is pending", async () => {
  4335. let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  4336. const runtime = createRuntime();
  4337. vi.mocked(runtime.watchEvents).mockImplementation(
  4338. async function* watchEvents(signal) {
  4339. const event = await new Promise<TuiRuntimeEvent | undefined>(
  4340. (resolve) => {
  4341. emitEvent = resolve;
  4342. signal.addEventListener("abort", () => resolve(undefined), {
  4343. once: true,
  4344. });
  4345. },
  4346. );
  4347. if (event) yield event;
  4348. await new Promise<void>((resolve) => {
  4349. signal.addEventListener("abort", resolve, { once: true });
  4350. });
  4351. },
  4352. );
  4353. const terminal = new FakeTerminal();
  4354. const app = createTuiApp({
  4355. runtime,
  4356. terminal,
  4357. version: "0.1.0",
  4358. workspaceDir: "/workspace",
  4359. });
  4360. app.start();
  4361. await app.ready;
  4362. await app.submit("/plan on");
  4363. await app.submit("Draft a plan");
  4364. await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
  4365. emitEvent?.(
  4366. runtimeEvent({
  4367. type: "questionnaire.ask",
  4368. timestamp: Date.now(),
  4369. source: "runtime",
  4370. payload: {
  4371. sessionId: "session-1",
  4372. agentName: "mavis",
  4373. request: planReviewEventRequest("plan-review-mode-guard"),
  4374. },
  4375. }),
  4376. );
  4377. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  4378. // The compact panel owns the decision; the frozen plan is projected to the Transcript.
  4379. expect(app.interaction.current()?.render?.(100).join("\n")).toContain(
  4380. "Plan complete. What would you like to do?",
  4381. );
  4382. expect(app.tui.render(100).join("\n")).toContain("Frozen plan");
  4383. terminal.input?.("\x1b[Z");
  4384. expect(app.interaction.isActive()).toBe(true);
  4385. expect(app.tui.render(100).join("\n")).toContain(
  4386. "/workspace │ PLAN │ Auto",
  4387. );
  4388. expect(app.tui.render(100).join("\n")).not.toContain("DEFAULT next");
  4389. await app.submit("/plan off");
  4390. expect(app.interaction.isActive()).toBe(true);
  4391. expect(app.tui.render(100).join("\n")).toContain(
  4392. "/workspace │ PLAN │ Auto",
  4393. );
  4394. expect(app.tui.render(100).join("\n")).not.toContain("DEFAULT next");
  4395. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  4396. await app.submit("/steer bypass the review");
  4397. expect(app.interaction.isActive()).toBe(true);
  4398. expect(runtime.steer).not.toHaveBeenCalled();
  4399. app.interaction.current()?.handleInput?.("\u001b");
  4400. await vi.waitFor(() =>
  4401. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  4402. "mavis",
  4403. "plan-review-mode-guard",
  4404. [expect.objectContaining({ skipped: true })],
  4405. ),
  4406. );
  4407. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  4408. expect(app.tui.render(100).join("\n")).toContain(
  4409. "/workspace │ PLAN │ Auto",
  4410. );
  4411. await app.stop();
  4412. });
  4413. it("streams Plan feedback and replaces it with the revised Plan Review", async () => {
  4414. let emitReview: ((event: TuiRuntimeEvent) => void) | undefined;
  4415. let releaseContinuation: (() => void) | undefined;
  4416. let finishReply: ((value: boolean) => void) | undefined;
  4417. const runtime = createRuntime();
  4418. vi.mocked(runtime.replyQuestionnaire).mockImplementation(
  4419. async () =>
  4420. await new Promise<boolean>((resolve) => {
  4421. finishReply = resolve;
  4422. }),
  4423. );
  4424. vi.mocked(runtime.watchEvents).mockImplementation(
  4425. async function* watchEvents(signal) {
  4426. const review = await new Promise<TuiRuntimeEvent | undefined>(
  4427. (resolve) => {
  4428. emitReview = resolve;
  4429. signal.addEventListener("abort", () => resolve(undefined), {
  4430. once: true,
  4431. });
  4432. },
  4433. );
  4434. if (!review || signal.aborted) return;
  4435. yield review;
  4436. await new Promise<void>((resolve) => {
  4437. releaseContinuation = resolve;
  4438. signal.addEventListener("abort", resolve, { once: true });
  4439. });
  4440. if (signal.aborted) return;
  4441. const turnId = "turn-runtime-plan-feedback";
  4442. yield runtimeEvent({
  4443. type: "session.start",
  4444. timestamp: Date.now(),
  4445. source: "runtime",
  4446. payload: { sessionId: "session-1", turnId },
  4447. });
  4448. vi.mocked(runtime.getMessages).mockResolvedValue([
  4449. {
  4450. id: "assistant-revised-plan",
  4451. role: "assistant",
  4452. content: "I revised the plan with rollback coverage.",
  4453. },
  4454. ]);
  4455. yield runtimeEvent({
  4456. type: "questionnaire.ask",
  4457. timestamp: Date.now(),
  4458. source: "runtime",
  4459. payload: {
  4460. sessionId: "session-1",
  4461. agentName: "mavis",
  4462. request: {
  4463. ...planReviewEventRequest("plan-review-feedback-revised"),
  4464. modePayload: {
  4465. planReview: {
  4466. markdown:
  4467. "# Revised frozen plan\n\nIncludes rollback coverage.",
  4468. path: "/history/session-1/artifacts/plan.md",
  4469. },
  4470. },
  4471. },
  4472. },
  4473. });
  4474. yield runtimeEvent({
  4475. type: "session.finish",
  4476. timestamp: Date.now(),
  4477. source: "runtime",
  4478. payload: { sessionId: "session-1", turnId },
  4479. });
  4480. finishReply?.(true);
  4481. await new Promise<void>((resolve) => {
  4482. signal.addEventListener("abort", resolve, { once: true });
  4483. });
  4484. },
  4485. );
  4486. const terminal = new FakeTerminal();
  4487. const app = createTuiApp({
  4488. runtime,
  4489. terminal,
  4490. version: "0.1.0",
  4491. workspaceDir: "/workspace",
  4492. });
  4493. app.start();
  4494. await app.ready;
  4495. await app.submit("/plan on");
  4496. await app.submit("Draft a plan");
  4497. await vi.waitFor(() => expect(emitReview).toBeTypeOf("function"));
  4498. emitReview?.(
  4499. runtimeEvent({
  4500. type: "questionnaire.ask",
  4501. timestamp: Date.now(),
  4502. source: "runtime",
  4503. payload: {
  4504. sessionId: "session-1",
  4505. agentName: "mavis",
  4506. request: planReviewEventRequest("plan-review-feedback-live"),
  4507. },
  4508. }),
  4509. );
  4510. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  4511. terminal.input?.("\u001b[B");
  4512. terminal.input?.("\u001b[B");
  4513. terminal.input?.("\r");
  4514. for (const character of "Add rollback coverage")
  4515. terminal.input?.(character);
  4516. terminal.input?.("\r");
  4517. await vi.waitFor(() => expect(finishReply).toBeTypeOf("function"));
  4518. releaseContinuation?.();
  4519. await vi.waitFor(() =>
  4520. expect(
  4521. app.transcript
  4522. .snapshot()
  4523. .map((cell) => cell.content)
  4524. .join("\n"),
  4525. ).toContain("I revised the plan with rollback coverage."),
  4526. );
  4527. expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
  4528. "session-1",
  4529. "turn-runtime-plan-feedback",
  4530. expect.any(AbortSignal),
  4531. );
  4532. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  4533. // The revised plan is projected to the Transcript; the panel stays the compact decision.
  4534. expect(app.interaction.current()?.render?.(100).join("\n")).toContain(
  4535. "Plan complete. What would you like to do?",
  4536. );
  4537. expect(app.tui.render(100).join("\n")).toContain("Revised frozen plan");
  4538. expect(app.tui.render(100).join("\n")).not.toContain(
  4539. "Message · Enter send",
  4540. );
  4541. await app.stop();
  4542. });
  4543. it("supports explicit /plan and /permission mode commands", async () => {
  4544. const runtime = createRuntime();
  4545. const app = createTuiApp({
  4546. runtime,
  4547. terminal: new FakeTerminal(),
  4548. version: "0.1.0",
  4549. workspaceDir: "/workspace",
  4550. });
  4551. app.start();
  4552. await app.ready;
  4553. await app.submit("/plan on");
  4554. expect(app.tui.render(100).join("\n")).toContain("PLAN next");
  4555. await app.submit("/permission full");
  4556. expect(runtime.setPermissionMode).toHaveBeenCalledWith("bypassPermissions");
  4557. expect(app.tui.render(100).join("\n")).toContain("Full access");
  4558. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4559. await app.submit("Plan with Full access");
  4560. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4561. expect.objectContaining({ clientIntent: "plan-entry" }),
  4562. expect.any(AbortSignal),
  4563. );
  4564. expect(app.tui.render(100).join("\n")).toContain("PLAN");
  4565. expect(app.tui.render(100).join("\n")).toContain("Full access");
  4566. await app.stop();
  4567. });
  4568. it("opens a permission mode selector for bare /permission", async () => {
  4569. const runtime = createRuntime();
  4570. const terminal = new FakeTerminal();
  4571. const app = createTuiApp({
  4572. runtime,
  4573. terminal,
  4574. version: "0.1.0",
  4575. workspaceDir: "/workspace",
  4576. });
  4577. app.start();
  4578. await app.ready;
  4579. await app.submit("/permission");
  4580. expect(app.interaction.isActive()).toBe(true);
  4581. const rendered = app.interaction.current()?.render?.(100).join("\n") ?? "";
  4582. expect(rendered).toContain("╭─ Permission");
  4583. expect(rendered).toContain("Current · Auto");
  4584. expect(rendered).toContain("ASK");
  4585. expect(rendered).toContain("› AUTO");
  4586. expect(rendered).toContain("FULL");
  4587. expect(runtime.setPermissionMode).not.toHaveBeenCalled();
  4588. terminal.input?.("\u001b[B");
  4589. terminal.input?.("\r");
  4590. await vi.waitFor(() =>
  4591. expect(runtime.setPermissionMode).toHaveBeenCalledWith(
  4592. "bypassPermissions",
  4593. ),
  4594. );
  4595. expect(app.interaction.isActive()).toBe(false);
  4596. expect(app.tui.render(100).join("\n")).toContain("Full access");
  4597. await app.submit("/permission status");
  4598. expect(app.interaction.isActive()).toBe(false);
  4599. expect(
  4600. app.transcript
  4601. .snapshot()
  4602. .map((cell) => cell.content)
  4603. .join("\n"),
  4604. ).toContain("Permission mode: Full access.");
  4605. await app.stop();
  4606. });
  4607. it("opens the latest settled Plan as a read-only full snapshot", async () => {
  4608. const runtime = createRuntime();
  4609. vi.mocked(runtime.getLatestPlanReview).mockResolvedValue(
  4610. planReviewEventRequest("plan-review-settled"),
  4611. );
  4612. const app = createTuiApp({
  4613. runtime,
  4614. terminal: new FakeTerminal(),
  4615. version: "0.1.0",
  4616. workspaceDir: "/workspace",
  4617. });
  4618. app.start();
  4619. await app.ready;
  4620. await app.openSession("session-1");
  4621. await app.submit("/plan view");
  4622. expect(runtime.getLatestPlanReview).toHaveBeenCalledWith(
  4623. "mavis",
  4624. "session-1",
  4625. );
  4626. const rendered = app.interaction.current()?.render?.(100).join("\n") ?? "";
  4627. expect(rendered).toContain("Frozen plan");
  4628. expect(rendered).toContain("/history/session-1/artifacts/plan.md");
  4629. expect(rendered).not.toContain("Agree and start implementation");
  4630. app.interaction.current()?.handleInput?.("\u001b");
  4631. expect(app.interaction.isActive()).toBe(false);
  4632. await app.stop();
  4633. });
  4634. it("does not open a settled Plan after the active Session changes", async () => {
  4635. let resolveReview:
  4636. | ((request: TuiQuestionnaireRequest | undefined) => void)
  4637. | undefined;
  4638. const runtime = createRuntime();
  4639. vi.mocked(runtime.getLatestPlanReview).mockImplementation(
  4640. async () =>
  4641. await new Promise<TuiQuestionnaireRequest | undefined>((resolve) => {
  4642. resolveReview = resolve;
  4643. }),
  4644. );
  4645. const app = createTuiApp({
  4646. runtime,
  4647. terminal: new FakeTerminal(),
  4648. version: "0.1.0",
  4649. workspaceDir: "/workspace",
  4650. });
  4651. app.start();
  4652. await app.ready;
  4653. await app.openSession("session-1");
  4654. const viewing = app.submit("/plan view");
  4655. await vi.waitFor(() => expect(resolveReview).toBeTypeOf("function"));
  4656. await app.openSession("session-2");
  4657. resolveReview?.(planReviewEventRequest("stale-plan-review"));
  4658. await viewing;
  4659. expect(app.interaction.isActive()).toBe(false);
  4660. expect(app.tui.render(100).join("\n")).not.toContain("Frozen plan");
  4661. await app.stop();
  4662. });
  4663. it("blocks Plan entry but still allows Plan exit when the Runtime capability is disabled", async () => {
  4664. const runtime = createRuntime();
  4665. vi.mocked(runtime.getPlanModeCapabilities).mockResolvedValue({
  4666. entryEnabled: false,
  4667. });
  4668. const terminal = new FakeTerminal();
  4669. const app = createTuiApp({
  4670. runtime,
  4671. terminal,
  4672. version: "0.1.0",
  4673. workspaceDir: "/workspace",
  4674. });
  4675. app.start();
  4676. await app.ready;
  4677. await app.openSession("session-1");
  4678. terminal.input?.("\x1b[Z");
  4679. await app.submit("/plan on");
  4680. expect(app.tui.render(100).join("\n")).not.toContain("PLAN next");
  4681. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4682. vi.mocked(runtime.getSession).mockResolvedValue({
  4683. sessionId: "session-1",
  4684. workspace: "/workspace",
  4685. interactionMode: "plan",
  4686. });
  4687. await app.controller.refreshSessionMetadata("session-1");
  4688. terminal.input?.("\x1b[Z");
  4689. expect(app.tui.render(100).join("\n")).toContain("DEFAULT next");
  4690. await app.stop();
  4691. });
  4692. it("fails closed when the Runtime Plan capability cannot be loaded", async () => {
  4693. const runtime = createRuntime();
  4694. vi.mocked(runtime.getPlanModeCapabilities).mockRejectedValue(
  4695. new Error("Runtime unavailable"),
  4696. );
  4697. const terminal = new FakeTerminal();
  4698. const app = createTuiApp({
  4699. runtime,
  4700. terminal,
  4701. version: "0.1.0",
  4702. workspaceDir: "/workspace",
  4703. });
  4704. app.start();
  4705. await app.ready;
  4706. terminal.input?.("\x1b[Z");
  4707. await app.submit("/plan on");
  4708. expect(app.tui.render(100).join("\n")).not.toContain("PLAN next");
  4709. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4710. await app.stop();
  4711. });
  4712. it("submits the hidden Runtime engineering log command name as an ordinary prompt", async () => {
  4713. const terminal = new FakeTerminal();
  4714. const runtime = createRuntime();
  4715. const app = createTuiApp({
  4716. runtime,
  4717. terminal,
  4718. version: "0.1.0",
  4719. workspaceDir: "/workspace",
  4720. runtimeLogDirectory: "/home/dev/.minimax/v2/observability/logs",
  4721. });
  4722. await app.submit("/logs");
  4723. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4724. expect.objectContaining({ id: "session-1", content: "/logs" }),
  4725. expect.any(AbortSignal),
  4726. );
  4727. });
  4728. it("exposes sanitized checks and submits the hidden /config name as ordinary text", async () => {
  4729. const terminal = new FakeTerminal();
  4730. const runtime = createRuntime();
  4731. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  4732. {
  4733. requestId: "permission-1",
  4734. sessionId: "session-1",
  4735. toolName: "bash",
  4736. toolDescription: "Run tests",
  4737. },
  4738. ]);
  4739. const app = createTuiApp({
  4740. runtime,
  4741. terminal,
  4742. version: "0.1.0",
  4743. workspaceDir: "/workspace",
  4744. });
  4745. await app.submit("/doctor");
  4746. const doctorOutput = app.transcript.snapshot().at(-1)?.content ?? "";
  4747. expect(app.interaction.current()).toBeUndefined();
  4748. await app.submit("/config");
  4749. expect(app.interaction.current()).toBeUndefined();
  4750. await app.submit("/skills docs");
  4751. const skillsPanel = app.interaction.current();
  4752. const skillsOutput = skillsPanel?.render(80).join("\n") ?? "";
  4753. expect(app.tui.render(80).join("\n")).not.toContain("Message · Enter");
  4754. skillsPanel?.handleInput?.("\x1b");
  4755. await app.submit("/mcp browser");
  4756. const mcpPanel = app.interaction.current();
  4757. const mcpOutput = mcpPanel?.render(80).join("\n") ?? "";
  4758. expect(app.tui.render(80).join("\n")).not.toContain("Message · Enter");
  4759. mcpPanel?.handleInput?.("\x1b");
  4760. await app.submit("/permissions");
  4761. const output = app.transcript
  4762. .snapshot()
  4763. .map((cell) => cell.content)
  4764. .join("\n");
  4765. expect(runtime.getRuntimeDiagnostics).toHaveBeenCalledTimes(1);
  4766. expect(runtime.listSkills).toHaveBeenCalledWith("mavis", "docs");
  4767. expect(runtime.listMcpServers).toHaveBeenCalledWith("browser", "session-1");
  4768. expect(runtime.listPendingPermissions).toHaveBeenCalled();
  4769. expect(doctorOutput).toContain("Configuration check");
  4770. expect(doctorOutput).toContain("Status: Valid");
  4771. expect(doctorOutput).not.toContain("/doctor");
  4772. expect(output).toContain("Configuration check");
  4773. expect(output).not.toContain("Effective configuration");
  4774. expect(skillsOutput).toContain("Skills");
  4775. expect(skillsOutput).toContain("Built-in · 1");
  4776. expect(skillsOutput).toContain("Docs");
  4777. expect(skillsOutput).toContain("● available · builtin");
  4778. expect(mcpOutput).toContain("MCP servers");
  4779. expect(mcpOutput).toContain("browser");
  4780. expect(mcpOutput).toContain("◆ configured · stdio");
  4781. expect(output).toContain("bash · Run tests");
  4782. expect(output).not.toContain("TOKEN");
  4783. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  4784. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4785. expect.objectContaining({ id: "session-1", content: "/config" }),
  4786. expect.any(AbortSignal),
  4787. );
  4788. });
  4789. it("previews /feedback without uploading until Enter confirms the Runtime draft", async () => {
  4790. const terminal = new FakeTerminal();
  4791. terminal.rows = 30;
  4792. const runtime = createRuntime();
  4793. const app = createTuiApp({
  4794. runtime,
  4795. terminal,
  4796. version: "0.1.0",
  4797. workspaceDir: "/workspace",
  4798. });
  4799. app.start();
  4800. await app.ready;
  4801. await app.submit("/feedback Upload failed token=****");
  4802. expect(runtime.prepareFeedback).toHaveBeenCalledWith({
  4803. description: "Upload failed token=****",
  4804. });
  4805. expect(runtime.submitFeedback).not.toHaveBeenCalled();
  4806. expect(app.tui.hasOverlay()).toBe(false);
  4807. expect(app.interaction.isActive()).toBe(true);
  4808. const panel = app.interaction.current();
  4809. expect(panel?.render(80).join("\n")).toContain("Review feedback");
  4810. panel?.handleInput?.("d");
  4811. expect(panel?.render(80).join("\n")).toContain("Client mcode 0.1.0");
  4812. terminal.input?.("\r");
  4813. await vi.waitFor(() =>
  4814. expect(runtime.submitFeedback).toHaveBeenCalledWith(
  4815. "feedback-draft-1",
  4816. expect.objectContaining({ onPhase: expect.any(Function) }),
  4817. ),
  4818. );
  4819. expect(panel?.render(80).join("\n")).toContain("ticket-1");
  4820. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4821. terminal.input?.("\x1b");
  4822. expect(app.interaction.isActive()).toBe(false);
  4823. await app.stop();
  4824. });
  4825. it("cancels /feedback without uploading and keeps missing descriptions out of the Agent", async () => {
  4826. const terminal = new FakeTerminal();
  4827. const runtime = createRuntime();
  4828. const app = createTuiApp({
  4829. runtime,
  4830. terminal,
  4831. version: "0.1.0",
  4832. workspaceDir: "/workspace",
  4833. });
  4834. app.start();
  4835. await app.ready;
  4836. await app.submit("/feedback");
  4837. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  4838. kind: "final-summary",
  4839. content: "Usage: /feedback <message>",
  4840. });
  4841. expect(runtime.prepareFeedback).not.toHaveBeenCalled();
  4842. await app.submit("/feedback Cancel this report");
  4843. terminal.input?.("\x1b");
  4844. await vi.waitFor(() =>
  4845. expect(runtime.cancelFeedback).toHaveBeenCalledWith("feedback-draft-1"),
  4846. );
  4847. expect(runtime.submitFeedback).not.toHaveBeenCalled();
  4848. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4849. await app.stop();
  4850. });
  4851. it("keeps the status report local and submits the hidden /config name as text", async () => {
  4852. const terminal = new FakeTerminal();
  4853. terminal.rows = 24;
  4854. const runtime = createRuntime();
  4855. const app = createTuiApp({
  4856. runtime,
  4857. terminal,
  4858. version: "0.1.0",
  4859. workspaceDir: "/workspace",
  4860. });
  4861. app.start();
  4862. await app.ready;
  4863. const transcriptBeforeStatus = app.transcript.snapshot();
  4864. await app.submit("/status");
  4865. expect(app.tui.hasOverlay()).toBe(false);
  4866. expect(app.interaction.isActive()).toBe(true);
  4867. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  4868. const statusOutput = app.tui.render(80).join("\n");
  4869. expect(statusOutput).toContain("MCode status");
  4870. expect(statusOutput).toContain("Model");
  4871. expect(statusOutput).not.toContain("/status");
  4872. expect(statusOutput).toContain("/workspace");
  4873. expect(statusOutput).toMatch(/Branch:\s+Not a Git repository/u);
  4874. expect(statusOutput).toContain("Not applicable");
  4875. expect(statusOutput).toContain("Session");
  4876. expect(statusOutput).toContain("Permissions");
  4877. expect(statusOutput).toContain("Auto");
  4878. app.interaction.current()?.handleInput?.("\x1b");
  4879. expect(app.interaction.isActive()).toBe(false);
  4880. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  4881. await app.submit("/config");
  4882. expect(app.tui.hasOverlay()).toBe(false);
  4883. expect(app.interaction.isActive()).toBe(false);
  4884. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4885. expect.objectContaining({ id: "session-1", content: "/config" }),
  4886. expect.any(AbortSignal),
  4887. );
  4888. expect(runtime.getRuntimeDiagnostics).not.toHaveBeenCalled();
  4889. await app.stop();
  4890. });
  4891. it("commits the first frame immediately when the Pi renderer starts", async () => {
  4892. const terminal = new FakeTerminal();
  4893. const app = createTuiApp({
  4894. runtime: createRuntime(),
  4895. terminal,
  4896. version: "0.1.0",
  4897. workspaceDir: "/workspace",
  4898. });
  4899. let firstFrameCommitted = false;
  4900. void app.firstFrame.then(() => {
  4901. firstFrameCommitted = true;
  4902. });
  4903. app.start();
  4904. await app.firstFrame;
  4905. expect(terminal.started).toBe(true);
  4906. expect(firstFrameCommitted).toBe(true);
  4907. expect(terminal.writes.join("")).toContain("Tips for getting started");
  4908. await app.stop();
  4909. });
  4910. it("chooses the account region before routing login through the auth application", async () => {
  4911. const runtime = createRuntime();
  4912. const openedTargets: string[] = [];
  4913. const logoutUrl =
  4914. "https://agent.minimax.io/auth/logout?logout_redirect_uri=https%3A%2F%2Fagent.minimax.io";
  4915. let authenticated = false;
  4916. vi.mocked(runtime.getAccountStatus).mockImplementation(async () =>
  4917. authenticated
  4918. ? {
  4919. status: "ready",
  4920. defaultModel: "minimax/MiniMax-M2.7",
  4921. providerId: "minimax",
  4922. modelId: "MiniMax-M2.7",
  4923. authMode: "managed-login",
  4924. managedTokenPresent: true,
  4925. warnings: [],
  4926. }
  4927. : {
  4928. status: "needs-login",
  4929. authMode: "managed-login",
  4930. managedTokenPresent: false,
  4931. warnings: [],
  4932. },
  4933. );
  4934. const auth = {
  4935. login: vi.fn(
  4936. async (
  4937. onProgress?: (progress: McodeAuthProgress) => void,
  4938. _region?: "cn" | "en",
  4939. ) => {
  4940. authenticated = true;
  4941. onProgress?.({
  4942. state: "device-authorization",
  4943. userCode: "ABCD-EFGH",
  4944. verificationUri: "https://account.example.test/device",
  4945. expiresInSec: 300,
  4946. });
  4947. return {
  4948. state: "authenticated" as const,
  4949. message:
  4950. _region === "en"
  4951. ? "Signed in with MiniMax Global. Restart MCode to use this account region."
  4952. : "Signed in with MiniMax.",
  4953. };
  4954. },
  4955. ),
  4956. logout: vi.fn(async () => {
  4957. authenticated = false;
  4958. return {
  4959. state: "signed-out" as const,
  4960. message: "Signed out of MiniMax.",
  4961. logoutUrl,
  4962. };
  4963. }),
  4964. };
  4965. const notifyAuthContextChanged = vi.fn(async () => {
  4966. throw new Error("Hook lifecycle cleanup failed");
  4967. });
  4968. const app = createTuiApp({
  4969. runtime,
  4970. auth,
  4971. terminal: new FakeTerminal(),
  4972. version: "0.1.0",
  4973. workspaceDir: "/workspace",
  4974. openExternalTarget: async (target) => {
  4975. openedTargets.push(target);
  4976. throw new Error("no desktop session");
  4977. },
  4978. notifyAuthContextChanged,
  4979. });
  4980. app.start();
  4981. await app.ready;
  4982. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login");
  4983. await app.submit("/login");
  4984. expect(auth.login).not.toHaveBeenCalled();
  4985. expect(app.interaction.render(80).join("\n")).toContain("China (CN)");
  4986. expect(app.interaction.render(80).join("\n")).toContain("Global");
  4987. app.interaction.current()?.handleInput("\u001b[B");
  4988. app.interaction.current()?.handleInput("\r");
  4989. await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
  4990. await vi.waitFor(() =>
  4991. expect(app.controller.snapshot().account?.managedTokenPresent).toBe(true),
  4992. );
  4993. expect(app.getSurface()).toBe("conversation");
  4994. expect(app.tui.render(80).join("\n")).not.toContain("Sign in with /login");
  4995. expect(app.tui.render(80).join("\n")).not.toContain("Login required");
  4996. await app.submit("/logout");
  4997. await vi.waitFor(() =>
  4998. expect(app.controller.snapshot().account?.managedTokenPresent).toBe(
  4999. false,
  5000. ),
  5001. );
  5002. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login");
  5003. expect(auth.login).toHaveBeenCalledWith(expect.any(Function), "en");
  5004. expect(openedTargets).toEqual([
  5005. "https://account.example.test/device?client_surface=tui&download_source=mcode-internal",
  5006. logoutUrl,
  5007. ]);
  5008. await vi.waitFor(() =>
  5009. expect(app.transcript.snapshot()).toEqual(
  5010. expect.arrayContaining([
  5011. expect.objectContaining({
  5012. kind: "warning",
  5013. content:
  5014. "Couldn't open the default browser. Open the authorization URL above manually.",
  5015. }),
  5016. expect.objectContaining({
  5017. kind: "warning",
  5018. content:
  5019. "Couldn't open the default browser. Open the sign-out URL above manually.",
  5020. }),
  5021. ]),
  5022. ),
  5023. );
  5024. expect(app.transcript.snapshot().slice(-6)).toMatchObject([
  5025. {
  5026. kind: "final-summary",
  5027. content:
  5028. "Complete MiniMax login in your browser:\nhttps://account.example.test/device?client_surface=tui&download_source=mcode-internal\nCode: ABCD-EFGH",
  5029. },
  5030. {
  5031. kind: "warning",
  5032. content:
  5033. "Couldn't open the default browser. Open the authorization URL above manually.",
  5034. },
  5035. {
  5036. kind: "final-summary",
  5037. content:
  5038. "Signed in with MiniMax Global. Restart MCode to use this account region.",
  5039. },
  5040. {
  5041. kind: "final-summary",
  5042. content: "Signed out of MiniMax.",
  5043. },
  5044. {
  5045. kind: "final-summary",
  5046. content: `Finish signing out in your browser:\n${logoutUrl}`,
  5047. },
  5048. {
  5049. kind: "warning",
  5050. content:
  5051. "Couldn't open the default browser. Open the sign-out URL above manually.",
  5052. },
  5053. ]);
  5054. expect(auth.login).toHaveBeenCalledOnce();
  5055. expect(auth.logout).toHaveBeenCalledOnce();
  5056. expect(notifyAuthContextChanged.mock.calls).toEqual([
  5057. ["authenticated"],
  5058. ["logged_out"],
  5059. ]);
  5060. expect(
  5061. app.transcript
  5062. .snapshot()
  5063. .map((cell) => cell.content)
  5064. .join("\n"),
  5065. ).not.toContain("Sign-in wasn't completed");
  5066. expect(
  5067. app.transcript
  5068. .snapshot()
  5069. .map((cell) => cell.content)
  5070. .join("\n"),
  5071. ).not.toContain("Couldn't sign out");
  5072. expect(runtime.sendMessage).not.toHaveBeenCalled();
  5073. await app.stop();
  5074. });
  5075. it("clears Runtime auth context when the shared account is already signed out", async () => {
  5076. const notifyAuthContextChanged = vi.fn(async () => undefined);
  5077. const logoutUrl =
  5078. "https://agent.minimax.cn/auth/logout?logout_redirect_uri=https%3A%2F%2Fagent.minimax.cn";
  5079. const openExternalTarget = vi.fn(() => new Promise<void>(() => {}));
  5080. const app = createTuiApp({
  5081. runtime: createRuntime(),
  5082. auth: {
  5083. login: vi.fn(),
  5084. logout: vi.fn(async () => ({
  5085. state: "already-signed-out" as const,
  5086. message: "Already signed out of MiniMax.",
  5087. logoutUrl,
  5088. })),
  5089. },
  5090. terminal: new FakeTerminal(),
  5091. version: "0.1.0",
  5092. workspaceDir: "/workspace",
  5093. notifyAuthContextChanged,
  5094. openExternalTarget,
  5095. });
  5096. app.start();
  5097. await app.ready;
  5098. await app.submit("/logout");
  5099. expect(notifyAuthContextChanged).toHaveBeenCalledOnce();
  5100. expect(notifyAuthContextChanged).toHaveBeenCalledWith("logged_out");
  5101. expect(openExternalTarget).toHaveBeenCalledWith(logoutUrl);
  5102. expect(app.transcript.snapshot()).toEqual(
  5103. expect.arrayContaining([
  5104. expect.objectContaining({
  5105. content: `Finish signing out in your browser:\n${logoutUrl}`,
  5106. }),
  5107. ]),
  5108. );
  5109. await app.stop();
  5110. });
  5111. it("refreshes Runtime auth context when login renews an existing account", async () => {
  5112. const runtime = createRuntime();
  5113. let authenticated = false;
  5114. vi.mocked(runtime.getAccountStatus).mockImplementation(async () =>
  5115. authenticated
  5116. ? {
  5117. status: "ready",
  5118. defaultModel: "minimax/MiniMax-M2.7",
  5119. providerId: "minimax",
  5120. modelId: "MiniMax-M2.7",
  5121. authMode: "managed-login",
  5122. managedTokenPresent: true,
  5123. warnings: [],
  5124. }
  5125. : {
  5126. status: "needs-login",
  5127. authMode: "managed-login",
  5128. managedTokenPresent: false,
  5129. warnings: [],
  5130. },
  5131. );
  5132. const notifyAuthContextChanged = vi.fn(async () => undefined);
  5133. const auth = {
  5134. login: vi.fn(async () => {
  5135. authenticated = true;
  5136. return {
  5137. state: "already-authenticated" as const,
  5138. message: "Already signed in with MiniMax.",
  5139. };
  5140. }),
  5141. logout: vi.fn(async () => ({
  5142. state: "signed-out" as const,
  5143. message: "Signed out of MiniMax.",
  5144. })),
  5145. };
  5146. const app = createTuiApp({
  5147. runtime,
  5148. auth,
  5149. notifyAuthContextChanged,
  5150. terminal: new FakeTerminal(),
  5151. version: "0.1.0",
  5152. workspaceDir: "/workspace",
  5153. });
  5154. app.start();
  5155. await app.ready;
  5156. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login");
  5157. await app.submit("/login");
  5158. app.interaction.current()?.handleInput("\u001b[B");
  5159. app.interaction.current()?.handleInput("\r");
  5160. await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
  5161. expect(notifyAuthContextChanged).toHaveBeenCalledOnce();
  5162. expect(notifyAuthContextChanged).toHaveBeenCalledWith("authenticated");
  5163. await vi.waitFor(() =>
  5164. expect(app.controller.snapshot().account?.managedTokenPresent).toBe(true),
  5165. );
  5166. expect(app.getSurface()).toBe("conversation");
  5167. expect(app.tui.render(80).join("\n")).not.toContain("Sign in with /login");
  5168. expect(app.tui.render(80).join("\n")).not.toContain("Login required");
  5169. await app.stop();
  5170. });
  5171. it("exits immediately through /quit without aborting the shared Runtime turn", async () => {
  5172. const terminal = new FakeTerminal();
  5173. const runtime = createRuntime();
  5174. const abortSession = vi.spyOn(runtime, "abortSession");
  5175. const app = createTuiApp({
  5176. runtime,
  5177. terminal,
  5178. version: "0.1.0",
  5179. workspaceDir: "/workspace",
  5180. });
  5181. app.start();
  5182. await app.ready;
  5183. await app.submit("/quit");
  5184. await app.stopped;
  5185. expect(terminal.stopped).toBe(true);
  5186. expect(abortSession).not.toHaveBeenCalled();
  5187. });
  5188. it("does not restore /quit after reopening the exited Session", async () => {
  5189. const dataDir = await mkdtemp(join(tmpdir(), "mcode-quit-draft-"));
  5190. try {
  5191. const first = createTuiApp({
  5192. runtime: createRuntime(),
  5193. terminal: new FakeTerminal(),
  5194. version: "0.1.0",
  5195. dataDir,
  5196. workspaceDir: "/workspace",
  5197. });
  5198. await first.ready;
  5199. await first.openSession("session-1");
  5200. first.editor.setText("/quit");
  5201. first.editor.handleInput("\r");
  5202. await first.stopped;
  5203. const restored = createTuiApp({
  5204. runtime: createRuntime(),
  5205. terminal: new FakeTerminal(),
  5206. version: "0.1.0",
  5207. dataDir,
  5208. workspaceDir: "/workspace",
  5209. });
  5210. await restored.ready;
  5211. await restored.openSession("session-1");
  5212. expect(restored.editor.getText()).toBe("");
  5213. await restored.stop();
  5214. } finally {
  5215. await rm(dataDir, { recursive: true, force: true });
  5216. }
  5217. });
  5218. it("keeps warning status details visible until the local panel closes", async () => {
  5219. const terminal = new FakeTerminal();
  5220. terminal.rows = 40;
  5221. const runtime = createRuntime();
  5222. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  5223. status: "warning",
  5224. defaultModel: "minimax/MiniMax-M2.7",
  5225. providerId: "minimax",
  5226. modelId: "MiniMax-M2.7",
  5227. authMode: "managed-login",
  5228. managedTokenPresent: true,
  5229. warnings: ["Desktop login should be refreshed soon."],
  5230. });
  5231. const app = createTuiApp({
  5232. runtime,
  5233. terminal,
  5234. version: "0.1.0",
  5235. workspaceDir: "/workspace",
  5236. });
  5237. app.start();
  5238. await app.ready;
  5239. const transcriptBeforeStatus = app.transcript.snapshot();
  5240. await app.submit("/status");
  5241. const rendered = app.tui.render(80).join("\n");
  5242. expect(app.interaction.current()).toBeDefined();
  5243. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  5244. expect(rendered).toContain("Needs attention");
  5245. expect(rendered).toContain("Connected with warnings");
  5246. expect(rendered).toContain("Model");
  5247. expect(rendered).toContain("Desktop login should be refreshed");
  5248. expect(rendered).toContain("soon.");
  5249. app.interaction.current()?.handleInput?.("\x1b");
  5250. expect(app.interaction.current()).toBeUndefined();
  5251. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  5252. expect(app.tui.render(80).join("\n")).not.toContain(
  5253. "Desktop login should be refreshed",
  5254. );
  5255. await app.stop();
  5256. });
  5257. it("reports doctor failures and submits the hidden /config name as text", async () => {
  5258. const runtime = createRuntime();
  5259. vi.mocked(runtime.getRuntimeDiagnostics).mockRejectedValue(
  5260. new Error("Diagnostics unavailable"),
  5261. );
  5262. const app = createTuiApp({
  5263. runtime,
  5264. terminal: new FakeTerminal(),
  5265. version: "0.1.0",
  5266. workspaceDir: "/workspace",
  5267. });
  5268. await app.submit("/doctor");
  5269. expect(app.tui.hasOverlay()).toBe(false);
  5270. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  5271. kind: "error",
  5272. content:
  5273. "Couldn't load configuration check: Diagnostics unavailable. Retry.",
  5274. });
  5275. await app.submit("/config");
  5276. expect(app.tui.hasOverlay()).toBe(false);
  5277. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5278. expect.objectContaining({ id: "session-1", content: "/config" }),
  5279. expect.any(AbortSignal),
  5280. );
  5281. expect(runtime.getRuntimeDiagnostics).toHaveBeenCalledTimes(1);
  5282. });
  5283. it("lets an async Session card replace a local status panel", async () => {
  5284. const terminal = new FakeTerminal();
  5285. const runtime = createRuntime();
  5286. let resolveSessionPage:
  5287. | ((page: {
  5288. sessions: Array<{
  5289. sessionId: string;
  5290. title: string;
  5291. workspaceDir: string;
  5292. updatedAt: number;
  5293. }>;
  5294. hasMore: boolean;
  5295. }) => void)
  5296. | undefined;
  5297. vi.mocked(runtime.listSessionPage).mockImplementationOnce(
  5298. async () =>
  5299. await new Promise((resolve) => {
  5300. resolveSessionPage = resolve;
  5301. }),
  5302. );
  5303. const app = createTuiApp({
  5304. runtime,
  5305. terminal,
  5306. version: "0.1.0",
  5307. workspaceDir: "/workspace",
  5308. });
  5309. await app.ready;
  5310. const transcriptBeforeStatus = app.transcript.snapshot();
  5311. const sessionCard = app.submit("/sessions");
  5312. await vi.waitFor(() =>
  5313. expect(runtime.listSessionPage).toHaveBeenCalledOnce(),
  5314. );
  5315. await app.submit("/status");
  5316. expect(app.tui.hasOverlay()).toBe(false);
  5317. expect(app.interaction.isActive()).toBe(true);
  5318. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  5319. expect(app.tui.render(80).join("\n")).toContain("MCode status");
  5320. resolveSessionPage?.({
  5321. sessions: [
  5322. {
  5323. sessionId: "session-race",
  5324. title: "Session opened after status",
  5325. workspaceDir: "/workspace",
  5326. updatedAt: Date.now(),
  5327. },
  5328. ],
  5329. hasMore: false,
  5330. });
  5331. await sessionCard;
  5332. expect(app.tui.hasOverlay()).toBe(false);
  5333. expect(app.interaction.isActive()).toBe(true);
  5334. app.interaction.current()?.handleInput?.("\x03");
  5335. expect(runtime.getSession).not.toHaveBeenCalled();
  5336. expect(app.interaction.isActive()).toBe(false);
  5337. expect(app.tui.hasOverlay()).toBe(false);
  5338. await app.stop();
  5339. });
  5340. it("keeps unsupported standalone MCP inspection concise and recoverable", async () => {
  5341. const runtime = createRuntime();
  5342. vi.mocked(runtime.listMcpServers).mockRejectedValue(
  5343. Object.assign(new Error("DesktopService implementation detail"), {
  5344. status: 501,
  5345. code: "NOT_IMPLEMENTED",
  5346. }),
  5347. );
  5348. const app = createTuiApp({
  5349. runtime,
  5350. terminal: new FakeTerminal(),
  5351. version: "0.1.0",
  5352. workspaceDir: "/workspace",
  5353. });
  5354. await app.submit("/mcp");
  5355. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  5356. kind: "warning",
  5357. content:
  5358. "MCP status is not available in this build. Configured MCP tools remain available.",
  5359. });
  5360. });
  5361. it("registers enabled Skills as discoverable slash commands without shadowing built-ins", async () => {
  5362. const terminal = new FakeTerminal();
  5363. const runtime = createRuntime();
  5364. vi.mocked(runtime.listSkills).mockResolvedValue({
  5365. skills: [
  5366. {
  5367. name: "docs",
  5368. displayName: "Docs",
  5369. description: "Read project docs",
  5370. enabled: true,
  5371. sourceKind: "builtin",
  5372. },
  5373. {
  5374. name: "disabled-skill",
  5375. enabled: false,
  5376. },
  5377. {
  5378. name: "help",
  5379. enabled: true,
  5380. },
  5381. ...Array.from({ length: 14 }, (_, index) => ({
  5382. name: `skill-${index}`,
  5383. description: `Generated skill ${index}`,
  5384. enabled: true,
  5385. })),
  5386. ],
  5387. hasMore: false,
  5388. });
  5389. const app = createTuiApp({
  5390. runtime,
  5391. terminal,
  5392. version: "0.1.0",
  5393. workspaceDir: "/workspace",
  5394. });
  5395. app.start();
  5396. await app.ready;
  5397. app.editor.setText("/docs summarize this repository");
  5398. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5399. "Skill · instructions · Enter invoke",
  5400. );
  5401. app.editor.setText("/context");
  5402. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5403. "Command · Enter run",
  5404. );
  5405. app.editor.setText("/context explain this repository");
  5406. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5407. "Prompt · Enter send",
  5408. );
  5409. app.editor.setText("/stop");
  5410. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5411. "Command · Enter run",
  5412. );
  5413. app.editor.setText("/config");
  5414. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5415. "Prompt · Enter send",
  5416. );
  5417. app.editor.setText("");
  5418. await app.submit("/help");
  5419. expect(app.transcript.snapshot()).toEqual([]);
  5420. expect(app.tui.hasOverlay()).toBe(false);
  5421. expect(app.interaction.isActive()).toBe(true);
  5422. for (const character of "docs") terminal.input?.(character);
  5423. terminal.input?.("\r");
  5424. expect(app.tui.hasOverlay()).toBe(false);
  5425. expect(app.interaction.isActive()).toBe(false);
  5426. expect(app.editor.getText()).toBe("");
  5427. await app.submit("/docs summarize this repository");
  5428. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5429. expect.objectContaining({
  5430. id: "session-1",
  5431. content: "/docs summarize this repository",
  5432. }),
  5433. expect.any(AbortSignal),
  5434. );
  5435. vi.mocked(runtime.sendMessage).mockClear();
  5436. await app.submit("/disabled-skill");
  5437. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5438. expect.objectContaining({ id: "session-1", content: "/disabled-skill" }),
  5439. expect.any(AbortSignal),
  5440. );
  5441. await app.stop();
  5442. });
  5443. it("deduplicates configured Skills case-insensitively and reserves built-in names", async () => {
  5444. const terminal = new FakeTerminal();
  5445. const runtime = createRuntime();
  5446. vi.mocked(runtime.listSkills).mockResolvedValue({
  5447. skills: [
  5448. {
  5449. name: "HELP",
  5450. description: "A Skill that must not shadow /help",
  5451. enabled: true,
  5452. },
  5453. {
  5454. name: "Docs",
  5455. description: "Read project docs",
  5456. enabled: true,
  5457. },
  5458. {
  5459. name: "docs",
  5460. description: "Duplicate project docs command",
  5461. enabled: true,
  5462. },
  5463. ],
  5464. hasMore: false,
  5465. });
  5466. const app = createTuiApp({
  5467. runtime,
  5468. terminal,
  5469. version: "0.1.0",
  5470. workspaceDir: "/workspace",
  5471. });
  5472. app.start();
  5473. await app.ready;
  5474. await app.submit("/help");
  5475. const helpPanel = app.interaction.current();
  5476. expect(helpPanel).toBeDefined();
  5477. helpPanel?.handleInput?.("\x1b");
  5478. await app.submit("/help [arguments]");
  5479. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5480. expect.objectContaining({
  5481. id: "session-1",
  5482. content: "/help [arguments]",
  5483. }),
  5484. expect.any(AbortSignal),
  5485. );
  5486. vi.mocked(runtime.sendMessage).mockClear();
  5487. await app.submit("/docs explain this repository");
  5488. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5489. expect.objectContaining({
  5490. id: "session-1",
  5491. content: "/docs explain this repository",
  5492. }),
  5493. expect.any(AbortSignal),
  5494. );
  5495. await app.stop();
  5496. });
  5497. it("uses public Runtime owners for Session inspection commands", async () => {
  5498. const terminal = new FakeTerminal();
  5499. terminal.rows = 40;
  5500. const runtime = createRuntime();
  5501. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  5502. status: "ready",
  5503. defaultModel: "minimax/MiniMax-M3",
  5504. providerId: "minimax-cn-coding-plan",
  5505. authMode: "managed-login",
  5506. managedTokenPresent: true,
  5507. modelSource: "token-plan",
  5508. tokenPlanQuotaState: "available",
  5509. tokenPlanSummary: { tier: "Ultra Plan", creditBalance: "0" },
  5510. tokenPlanQuota: {
  5511. fiveHour: { remainingPercent: 100, unlimited: false },
  5512. weekly: { remainingPercent: 99, unlimited: false },
  5513. video: { remainingCount: 5, totalCount: 5, unlimited: false },
  5514. },
  5515. warnings: [],
  5516. });
  5517. const app = createTuiApp({
  5518. runtime,
  5519. terminal,
  5520. version: "0.1.0",
  5521. workspaceDir: "/workspace",
  5522. });
  5523. await app.submit("Create a session");
  5524. vi.mocked(runtime.sendMessage).mockClear();
  5525. vi.mocked(runtime.getSessionUsage).mockClear();
  5526. vi.mocked(runtime.getContextSnapshot).mockResolvedValueOnce({
  5527. status: "live",
  5528. contextUsage: {
  5529. contextWindowTokens: 10_000,
  5530. usedTokens: 3_000,
  5531. totalCountSource: "PROVIDER_USAGE_ANCHORED",
  5532. components: [],
  5533. },
  5534. });
  5535. const transcriptBeforeUsage = app.transcript.snapshot();
  5536. await app.submit("/usage");
  5537. const usageOutput = app.tui.render(80).join("\n");
  5538. expect(app.interaction.current()).toBeDefined();
  5539. expect(app.transcript.snapshot()).toEqual(transcriptBeforeUsage);
  5540. expect(usageOutput).toContain("Usage");
  5541. expect(usageOutput).toContain("120 total");
  5542. expect(usageOutput).toContain("30% used · 70% free");
  5543. expect(usageOutput).toContain("Ultra Plan");
  5544. expect(usageOutput).toContain("100% left");
  5545. app.interaction.current()?.handleInput?.("\x1b");
  5546. expect(app.interaction.current()).toBeUndefined();
  5547. expect(app.transcript.snapshot()).toEqual(transcriptBeforeUsage);
  5548. await app.submit("/compact keep test evidence");
  5549. expect(runtime.getSessionUsage).toHaveBeenCalledWith("session-1");
  5550. expect(runtime.getContextSnapshot).toHaveBeenCalledWith("session-1");
  5551. expect(runtime.getAccountStatus).toHaveBeenCalledWith("session-1", {
  5552. includeMembership: true,
  5553. forceRefresh: true,
  5554. });
  5555. expect(runtime.requestCompaction).toHaveBeenCalledWith(
  5556. "session-1",
  5557. "mavis",
  5558. "keep test evidence",
  5559. );
  5560. expect(runtime.sendMessage).not.toHaveBeenCalled();
  5561. const output = app.transcript
  5562. .snapshot()
  5563. .map((cell) => cell.content)
  5564. .join("\n");
  5565. expect(output).not.toContain("Session usage");
  5566. expect(output).not.toMatch(
  5567. /Turns|Total tokens|Cost|Reasoning|Cache|Runtime|source|compaction|snapshot/i,
  5568. );
  5569. expect(output).not.toContain("Compaction completed");
  5570. expect(output).not.toContain("4,000 → 1,200 tokens");
  5571. expect(output).not.toContain("compact-1");
  5572. });
  5573. it("shows compaction as live activity until the Runtime request settles", async () => {
  5574. const runtime = createRuntime();
  5575. let resolveCompaction:
  5576. | ((result: {
  5577. success: true;
  5578. sessionId: string;
  5579. compactionId: string;
  5580. }) => void)
  5581. | undefined;
  5582. vi.mocked(runtime.requestCompaction).mockImplementationOnce(
  5583. async () =>
  5584. await new Promise((resolve) => {
  5585. resolveCompaction = resolve;
  5586. }),
  5587. );
  5588. const app = createTuiApp({
  5589. runtime,
  5590. terminal: new FakeTerminal(),
  5591. version: "0.1.0",
  5592. workspaceDir: "/workspace",
  5593. });
  5594. await app.submit("Create a session");
  5595. const pending = app.submit("/compact keep decisions");
  5596. await vi.waitFor(() =>
  5597. expect(app.tui.render(80).join("\n")).toContain("Compacting context"),
  5598. );
  5599. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
  5600. resolveCompaction?.({
  5601. success: true,
  5602. sessionId: "session-1",
  5603. compactionId: "compact-1",
  5604. });
  5605. await pending;
  5606. expect(app.tui.render(80).join("\n")).not.toContain("Compacting context");
  5607. });
  5608. it("treats Runtime NOTHING_TO_COMPACT as a recoverable Session state", async () => {
  5609. const runtime = createRuntime();
  5610. vi.mocked(runtime.requestCompaction).mockRejectedValue(
  5611. Object.assign(new Error("HTTP 400 implementation detail"), {
  5612. status: 400,
  5613. code: "NOTHING_TO_COMPACT",
  5614. }),
  5615. );
  5616. const app = createTuiApp({
  5617. runtime,
  5618. terminal: new FakeTerminal(),
  5619. version: "0.1.0",
  5620. workspaceDir: "/workspace",
  5621. });
  5622. await app.submit("Create a session");
  5623. await app.submit("/compact");
  5624. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  5625. kind: "final-summary",
  5626. content: "No compaction is needed for this conversation yet.",
  5627. });
  5628. });
  5629. it("shows account usage before a Session exists and keeps Session-only inspection recoverable", async () => {
  5630. const runtime = createRuntime();
  5631. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  5632. status: "ready",
  5633. authMode: "byok",
  5634. managedTokenPresent: false,
  5635. modelSource: "byok",
  5636. tokenPlanQuotaState: "available",
  5637. tokenPlanSummary: { tier: "Pro Plan" },
  5638. tokenPlanQuota: {
  5639. fiveHour: { remainingPercent: 75, unlimited: false },
  5640. weekly: { remainingPercent: 50, unlimited: false },
  5641. },
  5642. warnings: [],
  5643. });
  5644. const terminal = new FakeTerminal();
  5645. terminal.rows = 40;
  5646. const app = createTuiApp({
  5647. runtime,
  5648. terminal,
  5649. version: "0.1.0",
  5650. workspaceDir: "/workspace",
  5651. });
  5652. await app.submit("/usage");
  5653. const usageOutput = app.tui.render(80).join("\n");
  5654. expect(app.interaction.current()).toBeDefined();
  5655. expect(app.transcript.snapshot()).toEqual([]);
  5656. expect(usageOutput).toContain("Usage");
  5657. expect(usageOutput).toContain("Account only");
  5658. expect(usageOutput).toContain("Pro Plan");
  5659. expect(usageOutput).toContain("75% left");
  5660. app.interaction.current()?.handleInput?.("\x1b");
  5661. expect(app.interaction.current()).toBeUndefined();
  5662. expect(app.transcript.snapshot()).toEqual([]);
  5663. await app.submit("/compact");
  5664. expect(runtime.getSessionUsage).not.toHaveBeenCalled();
  5665. expect(runtime.getContextSnapshot).not.toHaveBeenCalled();
  5666. expect(runtime.getAccountStatus).toHaveBeenCalledWith(undefined, {
  5667. includeMembership: true,
  5668. forceRefresh: true,
  5669. });
  5670. expect(app.transcript.snapshot()).toEqual([]);
  5671. expect(app.tui.render(80).join("\n")).toContain(
  5672. "Start or resume a Session before compacting it.",
  5673. );
  5674. });
  5675. it("keeps prompt history and long bracketed paste intact in the Composer", async () => {
  5676. const terminal = new FakeTerminal();
  5677. const runtime = createRuntime();
  5678. const app = createTuiApp({
  5679. runtime,
  5680. terminal,
  5681. version: "0.1.0",
  5682. workspaceDir: "/workspace",
  5683. });
  5684. app.start();
  5685. await app.ready;
  5686. terminal.input?.("first prompt");
  5687. terminal.input?.("\r");
  5688. await vi.waitFor(() =>
  5689. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  5690. );
  5691. terminal.input?.("second prompt");
  5692. terminal.input?.("\r");
  5693. await vi.waitFor(() =>
  5694. expect(runtime.sendMessage).toHaveBeenCalledTimes(2),
  5695. );
  5696. terminal.input?.("\x1b[A");
  5697. expect(app.editor.getText()).toBe("second prompt");
  5698. terminal.input?.("\x1b[A");
  5699. expect(app.editor.getText()).toBe("first prompt");
  5700. terminal.input?.("\x1b[B");
  5701. expect(app.editor.getText()).toBe("second prompt");
  5702. app.editor.setText("");
  5703. const pasted = `Explain this payload:\n${"x".repeat(1_200)}`;
  5704. terminal.input?.(`\x1b[200~${pasted}\x1b[201~`);
  5705. expect(app.editor.getText()).toContain("[paste #");
  5706. expect(app.editor.getExpandedText()).toBe(pasted);
  5707. terminal.input?.("\r");
  5708. await vi.waitFor(() =>
  5709. expect(runtime.sendMessage).toHaveBeenCalledTimes(3),
  5710. );
  5711. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  5712. expect.objectContaining({ id: "session-1", content: pasted }),
  5713. expect.any(AbortSignal),
  5714. );
  5715. await app.stop();
  5716. });
  5717. it("trusts bracketed paste and submits dense typed input without a false newline", async () => {
  5718. const terminal = new FakeTerminal();
  5719. Object.defineProperty(terminal, "capabilities", {
  5720. value: {
  5721. terminalId: "unknown",
  5722. platform: "linux",
  5723. isTTY: true,
  5724. transport: "local",
  5725. multiplexer: "none",
  5726. color: true,
  5727. colorLevel: 3,
  5728. } satisfies TerminalCapabilities,
  5729. });
  5730. const runtime = createRuntime();
  5731. const app = createTuiApp({
  5732. runtime,
  5733. terminal,
  5734. version: "0.1.0",
  5735. workspaceDir: "/workspace",
  5736. });
  5737. app.start();
  5738. await app.ready;
  5739. for (const character of "abcdefgh") terminal.input?.(character);
  5740. terminal.input?.("\r");
  5741. await vi.waitFor(() =>
  5742. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  5743. );
  5744. expect(app.editor.getText()).toBe("");
  5745. await app.stop();
  5746. });
  5747. it("projects an otty image paste as an inline editor placeholder", async () => {
  5748. const terminal = new FakeTerminal();
  5749. const resolveAttachment = vi.fn(async () => ({
  5750. type: "image" as const,
  5751. filePath: "/tmp/otty-paste/image-123.png",
  5752. fileName: "image-123.png",
  5753. mimeType: "image/png",
  5754. sizeBytes: 1_024,
  5755. }));
  5756. const app = createTuiApp({
  5757. runtime: createRuntime(),
  5758. terminal,
  5759. version: "0.1.0",
  5760. workspaceDir: "/workspace",
  5761. resolveAttachment,
  5762. });
  5763. app.start();
  5764. await app.ready;
  5765. terminal.input?.("\x1b[200~/tmp/otty-paste/image-123.png\x1b[201~");
  5766. await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledTimes(1));
  5767. const rendered = app.tui.render(80).join("\n");
  5768. expect(app.editor.getText()).toBe("[Image #1] ");
  5769. expect(rendered).toContain("[Image #1]");
  5770. expect(rendered).not.toContain("/tmp/otty-paste/");
  5771. await app.stop();
  5772. });
  5773. it.each(["regular", "fullscreen"] as const)(
  5774. "keeps image preview controls separate from Enter submission in %s mode",
  5775. async (tuiMode) => {
  5776. const terminal = new FakeTerminal();
  5777. terminal.rows = 40;
  5778. const runtime = createRuntime();
  5779. const app = createTuiApp({
  5780. runtime,
  5781. terminal,
  5782. tuiMode,
  5783. version: "0.1.0",
  5784. workspaceDir: "/workspace",
  5785. resolveAttachment: async () => ({
  5786. type: "image",
  5787. filePath: "/tmp/image-preview-missing.png",
  5788. fileName: "preview.png",
  5789. mimeType: "image/png",
  5790. sizeBytes: 32768,
  5791. }),
  5792. });
  5793. app.start();
  5794. await app.ready;
  5795. terminal.input?.("\x1b[200~/tmp/image-preview-missing.png\x1b[201~");
  5796. await vi.waitFor(() =>
  5797. expect(app.editor.getAttachmentPreview()?.id).toBe(
  5798. "/tmp/image-preview-missing.png",
  5799. ),
  5800. );
  5801. expect(app.editor.getText()).toBe("[Image #1] ");
  5802. expect(app.tui.render(80).join("\n")).toContain("preview.png");
  5803. expect(app.tui.render(80).join("\n")).toContain("32 KB");
  5804. expect(app.tui.render(80).join("\n")).not.toMatch(/Option\+I|Alt\+I/);
  5805. expect(runtime.sendMessage).not.toHaveBeenCalled();
  5806. terminal.input?.("\x1b");
  5807. expect(app.editor.getAttachmentPreview()).toBeUndefined();
  5808. terminal.input?.("\x1b[D");
  5809. expect(app.editor.getAttachmentPreview()?.id).toBe(
  5810. "/tmp/image-preview-missing.png",
  5811. );
  5812. terminal.input?.("\r");
  5813. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalled());
  5814. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5815. expect.objectContaining({
  5816. content: "",
  5817. attachments: [
  5818. expect.objectContaining({
  5819. local: { filePath: "/tmp/image-preview-missing.png" },
  5820. }),
  5821. ],
  5822. }),
  5823. expect.any(AbortSignal),
  5824. );
  5825. expect(app.editor.getAttachmentPreview()).toBeUndefined();
  5826. await app.stop();
  5827. },
  5828. );
  5829. it("projects a pasted absolute WeChat image path as a short inline placeholder", async () => {
  5830. const terminal = new FakeTerminal();
  5831. const runtime = createRuntime();
  5832. const wechatImagePath =
  5833. "D:\\Yingyong\\social\\wechat\\xwechat_files\\wxid_demo\\temp\\RWTemp\\2026-08\\3336519cd4d5351f4bc5a5a68c7fea75.png";
  5834. const resolveAttachment = vi.fn(async () => ({
  5835. type: "image" as const,
  5836. filePath: wechatImagePath,
  5837. fileName: "3336519cd4d5351f4bc5a5a68c7fea75.png",
  5838. mimeType: "image/png",
  5839. sizeBytes: 1_024,
  5840. }));
  5841. const app = createTuiApp({
  5842. runtime,
  5843. terminal,
  5844. version: "0.1.0",
  5845. workspaceDir: "D:\\workspace",
  5846. resolveAttachment,
  5847. });
  5848. app.start();
  5849. await app.ready;
  5850. terminal.input?.(`\x1b[200~'${wechatImagePath}'\x1b[201~`);
  5851. await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledOnce());
  5852. expect(resolveAttachment).toHaveBeenCalledWith(`'${wechatImagePath}'`, {
  5853. source: "terminal-paste",
  5854. workspaceDir: "D:\\workspace",
  5855. });
  5856. expect(app.editor.getText()).toBe("[Image #1] ");
  5857. expect(app.tui.render(80).join("\n")).not.toContain("xwechat_files");
  5858. await app.submit("Inspect this image");
  5859. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5860. expect.objectContaining({
  5861. content: "Inspect this image",
  5862. attachments: [
  5863. expect.objectContaining({
  5864. local: { filePath: wechatImagePath },
  5865. }),
  5866. ],
  5867. }),
  5868. expect.any(AbortSignal),
  5869. );
  5870. await app.stop();
  5871. });
  5872. it("keeps an image placeholder visible before a long CJK prompt", async () => {
  5873. const terminal = new FakeTerminal();
  5874. const resolveAttachment = vi.fn(async () => ({
  5875. type: "image" as const,
  5876. filePath: "/tmp/otty-paste/logo.png",
  5877. fileName: "logo.png",
  5878. mimeType: "image/png",
  5879. sizeBytes: 1_024,
  5880. }));
  5881. const app = createTuiApp({
  5882. runtime: createRuntime(),
  5883. terminal,
  5884. version: "0.1.0",
  5885. workspaceDir: "/workspace",
  5886. resolveAttachment,
  5887. });
  5888. app.start();
  5889. await app.ready;
  5890. terminal.input?.("\x1b[200~/tmp/otty-paste/logo.png\x1b[201~");
  5891. await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledTimes(1));
  5892. app.editor.insertTextAtCursor(
  5893. "logo 不太对还是,还出现了奇怪的--; logo你自己截取把:",
  5894. );
  5895. const rendered = app.tui.render(80).join("\n");
  5896. expect(rendered).toContain("[Image #1]");
  5897. await app.stop();
  5898. });
  5899. it("removes an inline image placeholder and its attachment with Backspace", async () => {
  5900. const terminal = new FakeTerminal();
  5901. const resolveAttachment = vi.fn(async () => ({
  5902. type: "image" as const,
  5903. filePath: "/tmp/otty-paste/image-123.png",
  5904. fileName: "image-123.png",
  5905. mimeType: "image/png",
  5906. sizeBytes: 1_024,
  5907. }));
  5908. const app = createTuiApp({
  5909. runtime: createRuntime(),
  5910. terminal,
  5911. version: "0.1.0",
  5912. workspaceDir: "/workspace",
  5913. resolveAttachment,
  5914. });
  5915. app.start();
  5916. await app.ready;
  5917. app.editor.setText("first line\nsecond line");
  5918. terminal.input?.("\x1b[200~/tmp/otty-paste/image-123.png\x1b[201~");
  5919. await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledTimes(1));
  5920. expect(app.editor.getText()).toBe("first line\nsecond line [Image #1] ");
  5921. expect(app.tui.render(80).join("\n")).toContain("[Image #1]");
  5922. terminal.input?.("\x7f");
  5923. await vi.waitFor(() =>
  5924. expect(app.editor.getText().trimEnd()).toBe("first line\nsecond line"),
  5925. );
  5926. expect(app.tui.render(80).join("\n")).not.toContain("[Image #1]");
  5927. await app.stop();
  5928. });
  5929. it("resumes Desktop history, supports rename, and executes the files-unchanged fork flow", async () => {
  5930. const terminal = new FakeTerminal();
  5931. const runtime = createRuntime();
  5932. vi.mocked(runtime.listSessions).mockResolvedValue([
  5933. {
  5934. sessionId: "session-existing",
  5935. title: "Existing session",
  5936. workspaceDir: "/workspace",
  5937. updatedAt: 200,
  5938. },
  5939. ]);
  5940. const history = [
  5941. {
  5942. id: "msg-user-v1-fork-source",
  5943. turnId: "turn-history",
  5944. role: "user" as const,
  5945. content: "Try the original approach",
  5946. timestamp: 90,
  5947. },
  5948. {
  5949. id: "assistant-fork-source",
  5950. turnId: "turn-history",
  5951. role: "assistant" as const,
  5952. content: "Recovered answer",
  5953. timestamp: 100,
  5954. actions: { fork: true },
  5955. },
  5956. ];
  5957. const forkRuntime = runtime as TuiRuntime & TuiSessionForkPort;
  5958. vi.mocked(runtime.getMessages).mockResolvedValue(history);
  5959. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  5960. messages: history,
  5961. hasMore: false,
  5962. });
  5963. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  5964. sessionId === "session-fork"
  5965. ? {
  5966. sessionId,
  5967. parentSessionId: "session-existing",
  5968. title: "Existing session (fork 1)",
  5969. workspaceDir: "/workspace",
  5970. }
  5971. : {
  5972. sessionId,
  5973. title: "Existing session",
  5974. workspaceDir: "/workspace",
  5975. },
  5976. );
  5977. vi.mocked(forkRuntime.getSessionForkOptions).mockResolvedValue({
  5978. canFork: true,
  5979. suggestedTitle: "Existing session (fork 1)",
  5980. worktreeVisible: false,
  5981. worktreeEligible: false,
  5982. });
  5983. vi.mocked(forkRuntime.forkSession).mockResolvedValue({
  5984. session: {
  5985. sessionId: "session-fork",
  5986. parentSessionId: "session-existing",
  5987. title: "Existing session (fork 1)",
  5988. workspaceDir: "/workspace",
  5989. },
  5990. });
  5991. const app = createTuiApp({
  5992. runtime,
  5993. terminal,
  5994. version: "0.1.0",
  5995. workspaceDir: "/workspace",
  5996. });
  5997. app.start();
  5998. await app.ready;
  5999. await app.submit("/sessions");
  6000. expect(app.tui.hasOverlay()).toBe(false);
  6001. expect(app.interaction.isActive()).toBe(true);
  6002. app.interaction.current()?.handleInput?.("\x1b");
  6003. expect(app.interaction.isActive()).toBe(false);
  6004. await app.submit("/resume 1");
  6005. expect(app.getSurface()).toBe("conversation");
  6006. vi.mocked(runtime.renameSession).mockClear();
  6007. await app.submit("/rename");
  6008. expect(runtime.renameSession).not.toHaveBeenCalled();
  6009. expect(app.interaction.isActive()).toBe(true);
  6010. expect(app.tui.render(100).join("\n")).toContain(
  6011. "Sessions / Rename session",
  6012. );
  6013. app.interaction.current()?.handleInput?.("\x1b");
  6014. expect(app.tui.render(100).join("\n")).toContain("Sessions");
  6015. app.interaction.current()?.handleInput?.("\x1b");
  6016. expect(app.interaction.isActive()).toBe(false);
  6017. await app.submit("/rename Renamed session");
  6018. vi.mocked(runtime.createSession).mockClear();
  6019. await app.submit("/fork");
  6020. await vi.waitFor(() =>
  6021. expect(runtime.listSessionInputSummaries).toHaveBeenCalledWith(
  6022. "session-existing",
  6023. {
  6024. limit: 100,
  6025. },
  6026. ),
  6027. );
  6028. // The new fork flow owns the surface with the history picker, not the
  6029. // generic transcript panel.
  6030. expect(renderTerminalViewport(app, terminal)).toContain(
  6031. "Fork from a previous message",
  6032. );
  6033. expect(renderTerminalViewport(app, terminal)).not.toContain("Transcript");
  6034. // Esc cancels without calling the fork Runtime API.
  6035. const beforeForkCalls = vi.mocked(runtime.forkSession).mock.calls.length;
  6036. app.surfaceHost.popFeature();
  6037. expect(vi.mocked(runtime.forkSession).mock.calls.length).toBe(
  6038. beforeForkCalls,
  6039. );
  6040. const transcriptBeforeStatus = app.transcript.snapshot();
  6041. await app.submit("/status");
  6042. expect(runtime.getSession).toHaveBeenCalledWith("session-existing");
  6043. expect(app.interaction.current()).toBeDefined();
  6044. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  6045. expect(app.tui.render(100).join("\n")).toContain("MCode status");
  6046. expect(runtime.renameSession).toHaveBeenCalledWith(
  6047. "session-existing",
  6048. "Renamed session",
  6049. );
  6050. expect(runtime.createSession).not.toHaveBeenCalled();
  6051. expect(app.transcript.snapshot()).not.toEqual(
  6052. expect.arrayContaining([
  6053. expect.objectContaining({ content: "Unknown command. Use /help." }),
  6054. ]),
  6055. );
  6056. app.interaction.current()?.handleInput?.("\x1b");
  6057. await app.stop();
  6058. });
  6059. it.each(["regular", "fullscreen"] as const)(
  6060. "presents /history in %s mode and returns to chat on cancel",
  6061. async (tuiMode) => {
  6062. const terminal = new FakeTerminal();
  6063. const runtime = createRuntime();
  6064. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6065. {
  6066. userMessageId: "msg-user-history",
  6067. assistantMessageId: "msg-assistant-history",
  6068. contentHead: "Inspect the Session UI",
  6069. timestamp: 1_700_000_000_000,
  6070. fileChangeCount: 1,
  6071. },
  6072. ]);
  6073. const app = createTuiApp({
  6074. runtime,
  6075. terminal,
  6076. version: "0.1.0",
  6077. workspaceDir: "/workspace",
  6078. tuiMode,
  6079. });
  6080. app.start();
  6081. await app.ready;
  6082. await app.submit("Seed the session");
  6083. await app.submit("/history");
  6084. await vi.waitFor(() =>
  6085. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6086. kind: "feature",
  6087. id: "session-history:explorer",
  6088. }),
  6089. );
  6090. expect(renderTerminalViewport(app, terminal)).toContain(
  6091. "Inspect the Session UI",
  6092. );
  6093. expect(renderTerminalViewport(app, terminal)).toContain("Search:");
  6094. expect(renderTerminalViewport(app, terminal)).toContain("Enter actions");
  6095. terminal.input?.("\u001b");
  6096. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6097. kind: "chat",
  6098. id: "chat",
  6099. });
  6100. await app.stop();
  6101. },
  6102. );
  6103. it("forks with the assistant boundary and starts a new operation after a terminal failure", async () => {
  6104. const terminal = new FakeTerminal();
  6105. const runtime = createRuntime();
  6106. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6107. {
  6108. userMessageId: "msg-user-1",
  6109. assistantMessageId: "msg-assistant-1",
  6110. contentHead: "Investigate flaky login tests",
  6111. timestamp: 1_700_000_000_000,
  6112. fileChangeCount: 2,
  6113. },
  6114. {
  6115. userMessageId: "msg-user-2",
  6116. assistantMessageId: "msg-assistant-2",
  6117. contentHead: "Draft a new CLI handler",
  6118. timestamp: 1_699_999_000_000,
  6119. fileChangeCount: 0,
  6120. },
  6121. ]);
  6122. vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
  6123. canFork: true,
  6124. worktreeVisible: false,
  6125. worktreeEligible: false,
  6126. });
  6127. vi.mocked(runtime.forkSession).mockRejectedValueOnce(
  6128. Object.assign(new Error("persisted fork recovery failed"), {
  6129. key: "FORK_RECOVERY_FAILED",
  6130. }),
  6131. );
  6132. const app = createTuiApp({
  6133. runtime,
  6134. terminal,
  6135. version: "0.1.0",
  6136. workspaceDir: "/workspace",
  6137. });
  6138. app.start();
  6139. await app.ready;
  6140. // Submit a message so the controller has an active session id.
  6141. await app.submit("Seed the session");
  6142. await vi.waitFor(() =>
  6143. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6144. );
  6145. const sourceSessionId = app.controller.snapshot().session?.sessionId;
  6146. expect(sourceSessionId).toBe("session-1");
  6147. const transcriptBefore = app.transcript.snapshot();
  6148. vi.mocked(runtime.createSession).mockClear();
  6149. vi.mocked(runtime.forkSession).mockClear();
  6150. vi.mocked(runtime.getSessionForkOptions).mockClear();
  6151. vi.mocked(runtime.listSessionInputSummaries).mockClear();
  6152. await app.submit("/fork");
  6153. // 1. /fork loads input summaries, not the generic transcript.
  6154. await vi.waitFor(() =>
  6155. expect(runtime.listSessionInputSummaries).toHaveBeenCalledWith(
  6156. sourceSessionId,
  6157. {
  6158. limit: 100,
  6159. },
  6160. ),
  6161. );
  6162. expect(renderTerminalViewport(app, terminal)).toContain(
  6163. "Fork from a previous message",
  6164. );
  6165. expect(renderTerminalViewport(app, terminal)).not.toContain("Transcript");
  6166. // 2. The newest summary (last entry) is selected by default; confirm with Enter.
  6167. await vi.waitFor(() =>
  6168. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6169. kind: "feature",
  6170. id: "session-mutation:history",
  6171. }),
  6172. );
  6173. terminal.input?.("\r");
  6174. // The history selection only fetches options; it must not mutate yet.
  6175. await vi.waitFor(() =>
  6176. expect(runtime.getSessionForkOptions).toHaveBeenCalledWith(
  6177. sourceSessionId,
  6178. "msg-assistant-2",
  6179. ),
  6180. );
  6181. await vi.waitFor(() =>
  6182. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6183. kind: "feature",
  6184. id: "session-mutation:fork-confirm",
  6185. }),
  6186. );
  6187. expect(runtime.forkSession).not.toHaveBeenCalled();
  6188. expect(renderTerminalViewport(app, terminal)).toContain("Confirm fork");
  6189. // 3. Explicit confirmation performs the mutation.
  6190. terminal.input?.("\r");
  6191. await vi.waitFor(() =>
  6192. expect(runtime.forkSession).toHaveBeenCalledWith(
  6193. expect.objectContaining({
  6194. sessionId: sourceSessionId,
  6195. assistantMessageId: "msg-assistant-2",
  6196. useSuggestedTitle: true,
  6197. createIsolatedWorktree: false,
  6198. }),
  6199. ),
  6200. );
  6201. await vi.waitFor(() =>
  6202. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6203. kind: "feature",
  6204. id: "session-mutation:fork-confirm",
  6205. }),
  6206. );
  6207. terminal.input?.("\r");
  6208. await vi.waitFor(() =>
  6209. expect(runtime.forkSession).toHaveBeenCalledTimes(2),
  6210. );
  6211. const forkCalls = vi.mocked(runtime.forkSession).mock.calls;
  6212. const operationIds = forkCalls.map(([input]) => input.clientRequestId);
  6213. expect(operationIds[0]).toBeTruthy();
  6214. expect(operationIds[1]).toBeTruthy();
  6215. expect(operationIds[0]).not.toBe(operationIds[1]);
  6216. // 5. Activation moves the controller to the child session id.
  6217. await vi.waitFor(() =>
  6218. expect(app.controller.snapshot().session?.sessionId).toBe("session-fork"),
  6219. );
  6220. expect(runtime.createSession).not.toHaveBeenCalled();
  6221. // The user message that seeded the source session was already projected
  6222. // into the transcript before the fork ran; the fork flow must not write
  6223. // any new user-typed cell while the picker is open or the mutation runs.
  6224. expect(
  6225. transcriptBefore.filter((cell) => cell.kind === "user").length,
  6226. ).toBeGreaterThan(0);
  6227. });
  6228. it("does not call forkSession when /fork is cancelled, unavailable, or fails", async () => {
  6229. const scenarios: ReadonlyArray<{
  6230. readonly label: string;
  6231. readonly setup: (runtime: ReturnType<typeof createRuntime>) => void;
  6232. readonly interact: (terminal: FakeTerminal) => void | Promise<void>;
  6233. /** When true, expect forkSession to have been called exactly once. */
  6234. readonly expectForkCall: boolean;
  6235. readonly confirmAfterSelection?: boolean;
  6236. }> = [
  6237. {
  6238. label: "esc cancels the picker without invoking fork",
  6239. setup: (runtime) => {
  6240. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6241. {
  6242. userMessageId: "msg-user-1",
  6243. assistantMessageId: "msg-assistant-1",
  6244. contentHead: "Investigate flaky login tests",
  6245. timestamp: 1_700_000_000_000,
  6246. fileChangeCount: 0,
  6247. },
  6248. ]);
  6249. },
  6250. interact: (terminal) => {
  6251. terminal.input?.("\u001b");
  6252. },
  6253. expectForkCall: false,
  6254. },
  6255. {
  6256. label: "unavailable fork surfaces a warning without invoking fork",
  6257. setup: (runtime) => {
  6258. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6259. {
  6260. userMessageId: "msg-user-1",
  6261. assistantMessageId: "msg-assistant-1",
  6262. contentHead: "Investigate flaky login tests",
  6263. timestamp: 1_700_000_000_000,
  6264. fileChangeCount: 0,
  6265. },
  6266. ]);
  6267. vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
  6268. canFork: false,
  6269. unavailableReason: "No persisted user prompts yet.",
  6270. worktreeVisible: false,
  6271. worktreeEligible: false,
  6272. });
  6273. },
  6274. interact: (terminal) => {
  6275. terminal.input?.("\r");
  6276. },
  6277. expectForkCall: false,
  6278. },
  6279. {
  6280. label:
  6281. "forkSession failure preserves the source session and transcript",
  6282. setup: (runtime) => {
  6283. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6284. {
  6285. userMessageId: "msg-user-1",
  6286. assistantMessageId: "msg-assistant-1",
  6287. contentHead: "Investigate flaky login tests",
  6288. timestamp: 1_700_000_000_000,
  6289. fileChangeCount: 0,
  6290. },
  6291. ]);
  6292. vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
  6293. canFork: true,
  6294. worktreeVisible: false,
  6295. worktreeEligible: false,
  6296. });
  6297. vi.mocked(runtime.forkSession).mockRejectedValue(
  6298. new Error("Runtime offline."),
  6299. );
  6300. },
  6301. interact: (terminal) => {
  6302. terminal.input?.("\r");
  6303. },
  6304. expectForkCall: true,
  6305. confirmAfterSelection: true,
  6306. },
  6307. ];
  6308. for (const scenario of scenarios) {
  6309. const terminal = new FakeTerminal();
  6310. const runtime = createRuntime();
  6311. scenario.setup(runtime);
  6312. const app = createTuiApp({
  6313. runtime,
  6314. terminal,
  6315. version: "0.1.0",
  6316. workspaceDir: "/workspace",
  6317. });
  6318. app.start();
  6319. await app.ready;
  6320. await app.submit("Seed the session");
  6321. await vi.waitFor(() =>
  6322. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6323. );
  6324. const sourceSessionId = app.controller.snapshot().session?.sessionId;
  6325. const transcriptBefore = app.transcript.snapshot();
  6326. await app.submit("/fork");
  6327. await vi.waitFor(() =>
  6328. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6329. kind: "feature",
  6330. id: "session-mutation:history",
  6331. }),
  6332. );
  6333. await scenario.interact(terminal);
  6334. if (scenario.expectForkCall || scenario.label.includes("unavailable")) {
  6335. await vi.waitFor(() =>
  6336. expect(runtime.getSessionForkOptions).toHaveBeenCalled(),
  6337. );
  6338. }
  6339. expect(runtime.forkSession).not.toHaveBeenCalled();
  6340. if (scenario.confirmAfterSelection) {
  6341. terminal.input?.("\r");
  6342. }
  6343. // Give the async fork pipeline a chance to settle.
  6344. await new Promise((resolve) => setTimeout(resolve, 40));
  6345. if (scenario.expectForkCall) {
  6346. expect(
  6347. vi.mocked(runtime.forkSession).mock.calls.length,
  6348. `${scenario.label} should call forkSession once`,
  6349. ).toBe(1);
  6350. } else {
  6351. expect(
  6352. vi.mocked(runtime.forkSession).mock.calls.length,
  6353. `${scenario.label} should not call forkSession`,
  6354. ).toBe(0);
  6355. }
  6356. expect(
  6357. app.controller.snapshot().session?.sessionId,
  6358. `${scenario.label} must not switch sessions`,
  6359. ).toBe(sourceSessionId);
  6360. expect(
  6361. app.transcript.snapshot().filter((cell) => cell.kind === "user").length,
  6362. `${scenario.label} must preserve the source transcript`,
  6363. ).toBe(transcriptBefore.filter((cell) => cell.kind === "user").length);
  6364. await app.stop();
  6365. }
  6366. });
  6367. it("does not call forkSession when the source session changes between summary and selection", async () => {
  6368. const terminal = new FakeTerminal();
  6369. const runtime = createRuntime();
  6370. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6371. {
  6372. userMessageId: "msg-user-1",
  6373. assistantMessageId: "msg-assistant-1",
  6374. contentHead: "Investigate flaky login tests",
  6375. timestamp: 1_700_000_000_000,
  6376. fileChangeCount: 0,
  6377. },
  6378. ]);
  6379. vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
  6380. canFork: true,
  6381. worktreeVisible: false,
  6382. worktreeEligible: false,
  6383. });
  6384. const app = createTuiApp({
  6385. runtime,
  6386. terminal,
  6387. version: "0.1.0",
  6388. workspaceDir: "/workspace",
  6389. });
  6390. app.start();
  6391. await app.ready;
  6392. await app.submit("Seed the session");
  6393. await vi.waitFor(() =>
  6394. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6395. );
  6396. await app.submit("/fork");
  6397. await vi.waitFor(() =>
  6398. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6399. kind: "feature",
  6400. id: "session-mutation:history",
  6401. }),
  6402. );
  6403. // Simulate the source session changing while the picker is open.
  6404. const otherSession = {
  6405. sessionId: "session-other",
  6406. title: "Other session",
  6407. workspaceDir: "/workspace",
  6408. };
  6409. vi.mocked(runtime.listSessions).mockResolvedValue([otherSession]);
  6410. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  6411. sessionId === otherSession.sessionId
  6412. ? otherSession
  6413. : { sessionId, workspaceDir: "/workspace" },
  6414. );
  6415. await app.openSession(otherSession.sessionId);
  6416. expect(app.controller.snapshot().session?.sessionId).toBe(
  6417. otherSession.sessionId,
  6418. );
  6419. // Confirming the picker now must not call forkSession.
  6420. terminal.input?.("\r");
  6421. await new Promise((resolve) => setTimeout(resolve, 20));
  6422. expect(vi.mocked(runtime.forkSession)).not.toHaveBeenCalled();
  6423. expect(vi.mocked(runtime.getSessionForkOptions).mock.calls.length).toBe(0);
  6424. });
  6425. it("preserves the /fork command draft and skips mutation when a turn is running", async () => {
  6426. const terminal = new FakeTerminal();
  6427. const runtime = createRuntime();
  6428. let finishTurn: (() => void) | undefined;
  6429. vi.mocked(runtime.sendMessage).mockImplementation(
  6430. async function* sendMessage() {
  6431. await new Promise<void>((resolve) => {
  6432. finishTurn = resolve;
  6433. });
  6434. yield { type: "done" };
  6435. },
  6436. );
  6437. const app = createTuiApp({
  6438. runtime,
  6439. terminal,
  6440. version: "0.1.0",
  6441. workspaceDir: "/workspace",
  6442. });
  6443. app.start();
  6444. await app.ready;
  6445. const submission = app.submit("Seed the session");
  6446. await vi.waitFor(() =>
  6447. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6448. );
  6449. await vi.waitFor(() =>
  6450. expect(vi.mocked(runtime.sendMessage)).toHaveBeenCalled(),
  6451. );
  6452. const summariesBefore = vi.mocked(runtime.listSessionInputSummaries).mock
  6453. .calls.length;
  6454. const forkOptionsBefore = vi.mocked(runtime.getSessionForkOptions).mock
  6455. .calls.length;
  6456. const forkBefore = vi.mocked(runtime.forkSession).mock.calls.length;
  6457. // While the turn is still running, /fork should preserve the draft and
  6458. // skip every runtime mutation method.
  6459. app.editor.setText("/fork");
  6460. await app.submit("/fork");
  6461. expect(app.editor.getText()).toBe("/fork");
  6462. expect(vi.mocked(runtime.listSessionInputSummaries).mock.calls.length).toBe(
  6463. summariesBefore,
  6464. );
  6465. expect(vi.mocked(runtime.getSessionForkOptions).mock.calls.length).toBe(
  6466. forkOptionsBefore,
  6467. );
  6468. expect(vi.mocked(runtime.forkSession).mock.calls.length).toBe(forkBefore);
  6469. // The fork surface should not have been pushed either.
  6470. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6471. kind: "chat",
  6472. id: "chat",
  6473. });
  6474. finishTurn?.();
  6475. await submission;
  6476. await app.stop();
  6477. });
  6478. it.each([
  6479. ["conversation", []],
  6480. ["conversation_and_files", ["\u001b[B"]],
  6481. ] as const)(
  6482. "runs /rewind with explicit %s scope and stable operation id",
  6483. async (scope, navigation) => {
  6484. const terminal = new FakeTerminal();
  6485. const runtime = createRuntime();
  6486. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6487. {
  6488. userMessageId: "msg-user-rewind",
  6489. contentHead: "Undo this point",
  6490. timestamp: 1_700_000_000_000,
  6491. fileChangeCount: 2,
  6492. },
  6493. ]);
  6494. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  6495. turns: [
  6496. {
  6497. turnId: "turn-1",
  6498. files: [
  6499. { filePath: "src/ready.ts", action: "modified", skipped: false },
  6500. { filePath: "src/skipped.ts", action: "deleted", skipped: true },
  6501. ],
  6502. },
  6503. ],
  6504. });
  6505. vi.mocked(runtime.rewindSession).mockResolvedValue(
  6506. scope === "conversation"
  6507. ? { rewound: true }
  6508. : {
  6509. rewound: true,
  6510. turnDiffRewind: {
  6511. status: "rewound",
  6512. revertedTurnIds: ["turn-1"],
  6513. },
  6514. },
  6515. );
  6516. const app = createTuiApp({
  6517. runtime,
  6518. terminal,
  6519. version: "0.1.0",
  6520. workspaceDir: "/workspace",
  6521. });
  6522. app.start();
  6523. await app.ready;
  6524. await app.submit("Seed rewind session");
  6525. await vi.waitFor(() =>
  6526. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6527. );
  6528. expect(
  6529. app.transcript.snapshot().some((cell) => cell.kind === "turn-duration"),
  6530. ).toBe(true);
  6531. vi.mocked(runtime.getMessages).mockResolvedValue([]);
  6532. await app.submit("/rewind");
  6533. await vi.waitFor(() =>
  6534. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6535. kind: "feature",
  6536. id: "session-mutation:history",
  6537. }),
  6538. );
  6539. terminal.input?.("\r");
  6540. await vi.waitFor(() =>
  6541. expect(runtime.getSessionRewindPreview).toHaveBeenCalledWith({
  6542. sessionId: "session-1",
  6543. userMessageId: "msg-user-rewind",
  6544. }),
  6545. );
  6546. await vi.waitFor(() =>
  6547. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6548. kind: "feature",
  6549. id: "session-mutation:rewind-preview",
  6550. }),
  6551. );
  6552. expect(renderTerminalViewport(app, terminal)).toContain("src/ready.ts");
  6553. expect(renderTerminalViewport(app, terminal)).toContain("src/skipped.ts");
  6554. terminal.input?.("\r");
  6555. await vi.waitFor(() =>
  6556. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6557. kind: "feature",
  6558. id: "session-mutation:scope",
  6559. }),
  6560. );
  6561. for (const key of navigation) terminal.input?.(key);
  6562. terminal.input?.("\r");
  6563. await vi.waitFor(() =>
  6564. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6565. kind: "feature",
  6566. id: "session-mutation:rewind-confirm",
  6567. }),
  6568. );
  6569. expect(runtime.rewindSession).not.toHaveBeenCalled();
  6570. terminal.input?.("\r");
  6571. await vi.waitFor(() =>
  6572. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  6573. );
  6574. const input = vi.mocked(runtime.rewindSession).mock.calls[0]?.[0];
  6575. expect(input).toEqual({
  6576. sessionId: "session-1",
  6577. userMessageId: "msg-user-rewind",
  6578. clientRequestId: expect.stringMatching(/^tui-rewind_/),
  6579. ...(scope === "conversation_and_files" ? { rewindTurnDiff: true } : {}),
  6580. });
  6581. expect(input?.clientRequestId).toMatch(/^tui-rewind_/);
  6582. await vi.waitFor(() => expect(runtime.getMessages).toHaveBeenCalled());
  6583. await vi.waitFor(() =>
  6584. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6585. kind: "chat",
  6586. id: "chat",
  6587. }),
  6588. );
  6589. expect(
  6590. app.transcript
  6591. .snapshot()
  6592. .some((cell) => cell.content === "Rewind completed."),
  6593. ).toBe(false);
  6594. expect(app.transcript.snapshot()).toEqual([]);
  6595. await app.stop();
  6596. },
  6597. );
  6598. it("edits only the latest user turn, hides that turn while editing, and adds no completion cell", async () => {
  6599. const terminal = new FakeTerminal();
  6600. const runtime = createRuntime();
  6601. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6602. {
  6603. userMessageId: "msg-user-older",
  6604. assistantMessageId: "msg-assistant-older",
  6605. contentHead: "Older prompt",
  6606. timestamp: 1,
  6607. fileChangeCount: 0,
  6608. },
  6609. {
  6610. userMessageId: "msg-user-latest",
  6611. assistantMessageId: "msg-assistant-latest",
  6612. contentHead: "Latest prompt",
  6613. timestamp: 2,
  6614. fileChangeCount: 0,
  6615. },
  6616. ]);
  6617. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  6618. messages: [
  6619. {
  6620. id: "msg-user-older",
  6621. role: "user",
  6622. content: "Older prompt",
  6623. timestamp: 1,
  6624. },
  6625. {
  6626. id: "msg-user-latest",
  6627. role: "user",
  6628. content: "Latest prompt",
  6629. timestamp: 2,
  6630. },
  6631. ],
  6632. hasMore: false,
  6633. });
  6634. const app = createTuiApp({
  6635. runtime,
  6636. terminal,
  6637. version: "0.1.0",
  6638. workspaceDir: "/workspace",
  6639. });
  6640. app.start();
  6641. await app.ready;
  6642. await app.submit("Seed edit session");
  6643. await vi.waitFor(() =>
  6644. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6645. );
  6646. app.transcript.upsert({
  6647. id: "older-user-cell",
  6648. kind: "user",
  6649. status: "succeeded",
  6650. content: "Older prompt",
  6651. sourceMessageId: "msg-user-older",
  6652. turnId: "turn-older",
  6653. createdAtMs: 1,
  6654. });
  6655. app.transcript.upsert({
  6656. id: "latest-user-cell",
  6657. kind: "user",
  6658. status: "succeeded",
  6659. content: "Latest prompt",
  6660. sourceMessageId: "msg-user-latest",
  6661. turnId: "turn-latest",
  6662. createdAtMs: 2,
  6663. });
  6664. app.transcript.upsert({
  6665. id: "latest-assistant-cell",
  6666. kind: "assistant",
  6667. status: "succeeded",
  6668. content: "Latest response",
  6669. sourceMessageId: "msg-assistant-latest",
  6670. turnId: "turn-latest",
  6671. createdAtMs: 3,
  6672. });
  6673. await app.submit("/edit");
  6674. await vi.waitFor(() =>
  6675. expect(app.editor.getExpandedText()).toBe("Latest prompt"),
  6676. );
  6677. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6678. kind: "chat",
  6679. id: "chat",
  6680. });
  6681. const editingFrame = app.tui.render(100).join("\n");
  6682. expect(editingFrame).toContain("Older prompt");
  6683. expect(editingFrame).not.toContain("Latest response");
  6684. const historyRefreshCount = vi.mocked(runtime.getMessages).mock.calls
  6685. .length;
  6686. app.editor.setText("Edited latest prompt");
  6687. app.editor.handleInput("\r");
  6688. await vi.waitFor(() =>
  6689. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  6690. );
  6691. await vi.waitFor(() =>
  6692. expect(vi.mocked(runtime.getMessages).mock.calls.length).toBeGreaterThan(
  6693. historyRefreshCount,
  6694. ),
  6695. );
  6696. expect(
  6697. app.transcript
  6698. .snapshot()
  6699. .some(
  6700. (cell) =>
  6701. cell.content ===
  6702. "Edited message submitted; regenerating from this point.",
  6703. ),
  6704. ).toBe(false);
  6705. expect(runtime.editSessionMessage).toHaveBeenCalledWith(
  6706. expect.objectContaining({
  6707. userMessageId: "msg-user-latest",
  6708. content: "Edited latest prompt",
  6709. }),
  6710. );
  6711. await app.stop();
  6712. });
  6713. it("restores the hidden latest turn when Edit is cancelled", async () => {
  6714. const terminal = new FakeTerminal();
  6715. const runtime = createRuntime();
  6716. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6717. {
  6718. userMessageId: "msg-user-latest",
  6719. assistantMessageId: "msg-assistant-latest",
  6720. contentHead: "Latest prompt",
  6721. timestamp: 2,
  6722. fileChangeCount: 0,
  6723. },
  6724. ]);
  6725. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  6726. messages: [
  6727. {
  6728. id: "msg-user-latest",
  6729. role: "user",
  6730. content: "Latest prompt",
  6731. timestamp: 2,
  6732. },
  6733. ],
  6734. hasMore: false,
  6735. });
  6736. const app = createTuiApp({
  6737. runtime,
  6738. terminal,
  6739. version: "0.1.0",
  6740. workspaceDir: "/workspace",
  6741. });
  6742. app.start();
  6743. await app.ready;
  6744. await app.submit("Seed edit session");
  6745. app.transcript.upsert({
  6746. id: "latest-user-cell",
  6747. kind: "user",
  6748. status: "succeeded",
  6749. content: "Latest prompt",
  6750. sourceMessageId: "msg-user-latest",
  6751. turnId: "turn-latest",
  6752. createdAtMs: 2,
  6753. });
  6754. app.transcript.upsert({
  6755. id: "latest-assistant-cell",
  6756. kind: "assistant",
  6757. status: "succeeded",
  6758. content: "Latest response restored on cancel",
  6759. sourceMessageId: "msg-assistant-latest",
  6760. turnId: "turn-latest",
  6761. createdAtMs: 3,
  6762. });
  6763. await app.submit("/edit");
  6764. await vi.waitFor(() =>
  6765. expect(app.editor.getExpandedText()).toBe("Latest prompt"),
  6766. );
  6767. expect(app.tui.render(100).join("\n")).not.toContain(
  6768. "Latest response restored on cancel",
  6769. );
  6770. terminal.input?.("\u001b");
  6771. await vi.waitFor(() => expect(app.editor.getExpandedText()).toBe(""));
  6772. expect(app.tui.render(100).join("\n")).toContain(
  6773. "Latest response restored on cancel",
  6774. );
  6775. expect(runtime.editSessionMessage).not.toHaveBeenCalled();
  6776. await app.stop();
  6777. });
  6778. it.each([
  6779. { reference: "filePath", action: "cancel" },
  6780. { reference: "assetId", action: "send" },
  6781. { reference: "assetId", action: "delete" },
  6782. { reference: "filePath", action: "undo" },
  6783. { reference: "assetId", action: "add" },
  6784. { reference: "filePath", action: "clear-restore" },
  6785. { reference: "filePath", action: "cached" },
  6786. ] as const)(
  6787. "restores editable image chips after double Escape and retry ($reference / $action)",
  6788. async ({ reference, action }) => {
  6789. const terminal = new FakeTerminal();
  6790. const runtime = createRuntime();
  6791. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6792. {
  6793. userMessageId: "msg-user-latest",
  6794. assistantMessageId: "msg-assistant-latest",
  6795. contentHead: "Latest prompt from shortcut",
  6796. timestamp: 2,
  6797. fileChangeCount: 0,
  6798. },
  6799. ]);
  6800. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  6801. messages: [
  6802. {
  6803. id: "msg-user-latest",
  6804. role: "user",
  6805. content: "Latest prompt from shortcut",
  6806. attachments: [
  6807. {
  6808. type: "image",
  6809. fileName: "edit-reference.png",
  6810. mimeType: "image/png",
  6811. [reference]:
  6812. reference === "filePath"
  6813. ? "/workspace/edit-reference.png"
  6814. : "asset-edit-image",
  6815. },
  6816. ],
  6817. timestamp: 2,
  6818. },
  6819. ],
  6820. hasMore: false,
  6821. });
  6822. const app = createTuiApp({
  6823. runtime,
  6824. terminal,
  6825. version: "0.1.0",
  6826. workspaceDir: "/workspace",
  6827. resolveAttachment: async (path) => ({
  6828. type: "image",
  6829. filePath: path,
  6830. fileName: path.endsWith("new.png") ? "new.png" : "edit-reference.png",
  6831. mimeType: "image/png",
  6832. sizeBytes: 123,
  6833. }),
  6834. });
  6835. app.start();
  6836. await app.ready;
  6837. let restoredText = "Latest prompt from shortcut [Image #1] ";
  6838. if (action === "cached") {
  6839. terminal.input?.("\x1b[200~/workspace/edit-reference.png\x1b[201~");
  6840. await vi.waitFor(() =>
  6841. expect(app.editor.getText()).toContain("[Image #1]"),
  6842. );
  6843. app.editor.handleInput("Latest prompt from shortcut");
  6844. restoredText = app.editor.getText();
  6845. app.editor.handleInput("\r");
  6846. await vi.waitFor(() =>
  6847. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  6848. );
  6849. await vi.waitFor(() =>
  6850. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  6851. );
  6852. } else {
  6853. await app.submit("Seed edit session");
  6854. }
  6855. terminal.input?.("\u001b");
  6856. terminal.input?.("\u001b");
  6857. await vi.waitFor(() =>
  6858. expect(app.editor.getExpandedText()).toBe(restoredText),
  6859. );
  6860. expect(runtime.listSessionInputSummaries).toHaveBeenCalledWith(
  6861. "session-1",
  6862. { limit: 100 },
  6863. );
  6864. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6865. kind: "chat",
  6866. id: "chat",
  6867. });
  6868. expect(stripAnsi(app.tui.render(100).join("\n"))).toContain("[Image #1]");
  6869. vi.mocked(runtime.editSessionMessage).mockRejectedValueOnce(
  6870. new Error("Temporary failure"),
  6871. );
  6872. app.editor.handleInput("\r");
  6873. await vi.waitFor(() =>
  6874. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  6875. );
  6876. await vi.waitFor(() =>
  6877. expect(app.editor.getExpandedText()).toBe(restoredText),
  6878. );
  6879. expect(stripAnsi(app.tui.render(100).join("\n"))).toContain("[Image #1]");
  6880. expect(runtime.editSessionMessage).toHaveBeenCalledWith(
  6881. expect.objectContaining({
  6882. content: "Latest prompt from shortcut",
  6883. attachments: [
  6884. expect.objectContaining({
  6885. fileName: "edit-reference.png",
  6886. [reference]:
  6887. reference === "filePath"
  6888. ? "/workspace/edit-reference.png"
  6889. : "asset-edit-image",
  6890. }),
  6891. ],
  6892. }),
  6893. );
  6894. if (action === "delete" || action === "undo") {
  6895. app.editor.handleInput("\x05");
  6896. app.editor.handleInput("\x7f");
  6897. await vi.waitFor(() =>
  6898. expect(app.editor.getText()).not.toContain("[Image #1]"),
  6899. );
  6900. if (action === "undo") {
  6901. app.editor.handleInput("\x1f");
  6902. expect(app.editor.getText()).toContain("[Image #1]");
  6903. }
  6904. }
  6905. if (action === "add") {
  6906. terminal.input?.("\x1b[200~/workspace/new.png\x1b[201~");
  6907. await vi.waitFor(() =>
  6908. expect(app.editor.getText()).toContain("[Image #2]"),
  6909. );
  6910. expect(app.editor.captureDraft().attachmentPlaceholders).toHaveLength(
  6911. 2,
  6912. );
  6913. }
  6914. if (action === "clear-restore") {
  6915. terminal.input?.("\x03");
  6916. expect(app.editor.getText()).toBe("");
  6917. terminal.input?.("\x1f");
  6918. expect(app.editor.getText()).toContain("[Image #1]");
  6919. }
  6920. if (action === "cancel") {
  6921. terminal.input?.("\u001b");
  6922. } else {
  6923. app.editor.handleInput("\r");
  6924. await vi.waitFor(() =>
  6925. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(2),
  6926. );
  6927. const sent = vi.mocked(runtime.editSessionMessage).mock.calls[1]?.[0];
  6928. expect(sent?.content).toBe("Latest prompt from shortcut");
  6929. expect(sent?.attachments ?? []).toHaveLength(
  6930. action === "delete" ? 0 : action === "add" ? 2 : 1,
  6931. );
  6932. if (action !== "delete")
  6933. expect(sent?.attachments?.[0]?.fileName).toBe("edit-reference.png");
  6934. }
  6935. await vi.waitFor(() =>
  6936. expect(stripAnsi(app.tui.render(100).join("\n"))).not.toContain(
  6937. "[Image #1]",
  6938. ),
  6939. );
  6940. await app.stop();
  6941. },
  6942. );
  6943. it("edits the latest committed user turn through the desktop-aligned mutation contract", async () => {
  6944. const terminal = new FakeTerminal();
  6945. const runtime = createRuntime();
  6946. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6947. {
  6948. userMessageId: "msg-user-v1-target",
  6949. assistantMessageId: "msg-assistant-v1-target",
  6950. contentHead: "Original prompt head",
  6951. timestamp: 1_700_000_000_000,
  6952. fileChangeCount: 1,
  6953. },
  6954. ]);
  6955. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  6956. messages: [
  6957. {
  6958. id: "msg-user-v1-target",
  6959. role: "user",
  6960. content: "Original complete prompt",
  6961. attachments: [
  6962. {
  6963. type: "file",
  6964. fileName: "spec.md",
  6965. mimeType: "text/markdown",
  6966. sizeBytes: 42,
  6967. filePath: "/workspace/spec.md",
  6968. },
  6969. ],
  6970. timestamp: 1_700_000_000_000,
  6971. },
  6972. ],
  6973. hasMore: false,
  6974. });
  6975. const app = createTuiApp({
  6976. runtime,
  6977. terminal,
  6978. version: "0.1.0",
  6979. workspaceDir: "/workspace",
  6980. });
  6981. app.start();
  6982. await app.ready;
  6983. await app.submit("Seed edit session");
  6984. await vi.waitFor(() =>
  6985. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6986. );
  6987. await app.submit("/edit");
  6988. await vi.waitFor(() =>
  6989. expect(app.editor.getExpandedText()).toBe(
  6990. "Original complete prompt [File #1] ",
  6991. ),
  6992. );
  6993. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6994. kind: "chat",
  6995. id: "chat",
  6996. });
  6997. app.editor.setText("Updated prompt");
  6998. app.editor.handleInput("\r");
  6999. await vi.waitFor(() =>
  7000. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7001. );
  7002. expect(runtime.editSessionMessage).toHaveBeenCalledWith({
  7003. sessionId: "session-1",
  7004. userMessageId: "msg-user-v1-target",
  7005. clientRequestId: expect.stringMatching(/^tui-edit_/u),
  7006. content: "Updated prompt",
  7007. attachments: [
  7008. {
  7009. type: "file",
  7010. fileName: "spec.md",
  7011. mimeType: "text/markdown",
  7012. sizeBytes: 42,
  7013. filePath: "/workspace/spec.md",
  7014. },
  7015. ],
  7016. rewindTurnDiff: true,
  7017. });
  7018. await app.stop();
  7019. });
  7020. it("keeps hidden chat context out of the editor and restores it for Edit transport", async () => {
  7021. const terminal = new FakeTerminal();
  7022. const runtime = createRuntime();
  7023. const transportContent = [
  7024. "<user-provided-context>",
  7025. "Referenced context",
  7026. "</user-provided-context>",
  7027. "",
  7028. "Original visible prompt",
  7029. ].join("\n");
  7030. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7031. {
  7032. userMessageId: "msg-user-v1-context",
  7033. assistantMessageId: "msg-assistant-v1-context",
  7034. contentHead: "Original visible prompt",
  7035. timestamp: 1_700_000_000_000,
  7036. fileChangeCount: 0,
  7037. },
  7038. ]);
  7039. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7040. messages: [
  7041. {
  7042. id: "msg-user-v1-context",
  7043. role: "user",
  7044. content: transportContent,
  7045. timestamp: 1_700_000_000_000,
  7046. },
  7047. ],
  7048. hasMore: false,
  7049. });
  7050. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7051. const app = createTuiApp({
  7052. runtime,
  7053. terminal,
  7054. version: "0.1.0",
  7055. workspaceDir: "/workspace",
  7056. });
  7057. app.start();
  7058. await app.ready;
  7059. await app.submit("Seed edit session");
  7060. await app.submit("/edit");
  7061. await vi.waitFor(() =>
  7062. expect(app.editor.getExpandedText()).toBe("Original visible prompt"),
  7063. );
  7064. expect(app.editor.getExpandedText()).not.toContain("user-provided-context");
  7065. app.editor.setText("Updated visible prompt");
  7066. app.editor.handleInput("\r");
  7067. await vi.waitFor(() =>
  7068. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7069. );
  7070. expect(runtime.editSessionMessage).toHaveBeenCalledWith(
  7071. expect.objectContaining({
  7072. content: [
  7073. "<user-provided-context>",
  7074. "Referenced context",
  7075. "</user-provided-context>",
  7076. "",
  7077. "Updated visible prompt",
  7078. ].join("\n"),
  7079. }),
  7080. );
  7081. await app.stop();
  7082. });
  7083. it("preserves hidden context and attachments when Edit recovery requires a new message", async () => {
  7084. const terminal = new FakeTerminal();
  7085. const runtime = createRuntime();
  7086. const transportContent = [
  7087. "<mavis-chat-context>",
  7088. "Referenced context",
  7089. "</mavis-chat-context>",
  7090. "",
  7091. "Original visible prompt",
  7092. ].join("\n");
  7093. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7094. {
  7095. userMessageId: "msg-user-v1-recovery",
  7096. assistantMessageId: "msg-assistant-v1-recovery",
  7097. contentHead: "Original visible prompt",
  7098. timestamp: 1_700_000_000_000,
  7099. fileChangeCount: 0,
  7100. },
  7101. ]);
  7102. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7103. messages: [
  7104. {
  7105. id: "msg-user-v1-recovery",
  7106. role: "user",
  7107. content: transportContent,
  7108. attachments: [
  7109. {
  7110. type: "file",
  7111. fileName: "context.md",
  7112. mimeType: "text/markdown",
  7113. sizeBytes: 42,
  7114. assetId: "asset-context-md",
  7115. },
  7116. ],
  7117. timestamp: 1_700_000_000_000,
  7118. },
  7119. ],
  7120. hasMore: false,
  7121. });
  7122. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7123. vi.mocked(runtime.editSessionMessage).mockRejectedValueOnce(
  7124. Object.assign(new Error("history already rewound"), {
  7125. key: "EDIT_RESTART_NEEDS_RESUBMIT",
  7126. }),
  7127. );
  7128. const app = createTuiApp({
  7129. runtime,
  7130. terminal,
  7131. version: "0.1.0",
  7132. workspaceDir: "/workspace",
  7133. });
  7134. app.start();
  7135. await app.ready;
  7136. await app.submit("Seed edit session");
  7137. const sendCountBeforeEdit = vi.mocked(runtime.sendMessage).mock.calls
  7138. .length;
  7139. await app.submit("/edit");
  7140. await vi.waitFor(() =>
  7141. expect(app.editor.getExpandedText()).toBe(
  7142. "Original visible prompt [File #1] ",
  7143. ),
  7144. );
  7145. app.editor.setText("/help should remain message text");
  7146. app.editor.handleInput("\r");
  7147. await vi.waitFor(() =>
  7148. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7149. );
  7150. await vi.waitFor(() =>
  7151. expect(app.editor.getExpandedText()).toBe(
  7152. "/help should remain message text [File #1] ",
  7153. ),
  7154. );
  7155. expect(app.editor.getExpandedText()).not.toContain("mavis-chat-context");
  7156. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
  7157. let releaseAdmission!: () => void;
  7158. vi.mocked(runtime.getAccountStatus).mockImplementationOnce(
  7159. async () =>
  7160. await new Promise((resolve) => {
  7161. releaseAdmission = () =>
  7162. resolve({
  7163. status: "ready",
  7164. defaultModel: "minimax/MiniMax-M2.7",
  7165. providerId: "minimax",
  7166. modelId: "MiniMax-M2.7",
  7167. authMode: "managed-login",
  7168. managedTokenPresent: true,
  7169. warnings: [],
  7170. });
  7171. }),
  7172. );
  7173. app.editor.handleInput("\r");
  7174. await vi.waitFor(() =>
  7175. expect(app.controller.snapshot().activeTurnId).toBeDefined(),
  7176. );
  7177. terminal.input?.("\u001b");
  7178. releaseAdmission();
  7179. await vi.waitFor(() =>
  7180. expect(app.editor.getExpandedText()).toBe(
  7181. "/help should remain message text [File #1] ",
  7182. ),
  7183. );
  7184. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
  7185. app.editor.handleInput("\r");
  7186. await vi.waitFor(() =>
  7187. expect(runtime.sendMessage).toHaveBeenCalledTimes(
  7188. sendCountBeforeEdit + 1,
  7189. ),
  7190. );
  7191. expect(vi.mocked(runtime.sendMessage).mock.calls.at(-1)?.[0]).toMatchObject(
  7192. {
  7193. content: [
  7194. "<mavis-chat-context>",
  7195. "Referenced context",
  7196. "</mavis-chat-context>",
  7197. "",
  7198. "/help should remain message text",
  7199. ].join("\n"),
  7200. attachments: [
  7201. {
  7202. meta: {
  7203. attachmentType: "file",
  7204. fileName: "context.md",
  7205. mimeType: "text/markdown",
  7206. sizeBytes: 42,
  7207. },
  7208. local: { assetId: "asset-context-md" },
  7209. },
  7210. ],
  7211. },
  7212. );
  7213. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1);
  7214. expect(
  7215. app.transcript
  7216. .snapshot()
  7217. .filter((cell) => cell.kind === "user")
  7218. .map((cell) => cell.content)
  7219. .join("\n"),
  7220. ).toContain("/help should remain message text");
  7221. expect(
  7222. app.transcript
  7223. .snapshot()
  7224. .filter((cell) => cell.kind === "user")
  7225. .map((cell) => cell.content)
  7226. .join("\n"),
  7227. ).not.toContain("mavis-chat-context");
  7228. await app.stop();
  7229. });
  7230. it("allows an attachment-only committed message to enter Edit and gain a body", async () => {
  7231. const terminal = new FakeTerminal();
  7232. const runtime = createRuntime();
  7233. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7234. {
  7235. userMessageId: "msg-user-v1-attachment-only",
  7236. assistantMessageId: "msg-assistant-v1-attachment-only",
  7237. timestamp: 1_700_000_000_000,
  7238. fileChangeCount: 0,
  7239. },
  7240. ]);
  7241. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7242. messages: [
  7243. {
  7244. id: "msg-user-v1-attachment-only",
  7245. role: "user",
  7246. content: "",
  7247. attachments: [
  7248. {
  7249. type: "image",
  7250. fileName: "reference.png",
  7251. mimeType: "image/png",
  7252. filePath: "/workspace/reference.png",
  7253. },
  7254. ],
  7255. timestamp: 1_700_000_000_000,
  7256. },
  7257. ],
  7258. hasMore: false,
  7259. });
  7260. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7261. const app = createTuiApp({
  7262. runtime,
  7263. terminal,
  7264. version: "0.1.0",
  7265. workspaceDir: "/workspace",
  7266. });
  7267. app.start();
  7268. await app.ready;
  7269. await app.submit("Seed edit session");
  7270. const sendCountBeforeEdit = vi.mocked(runtime.sendMessage).mock.calls
  7271. .length;
  7272. await app.submit("/edit");
  7273. await vi.waitFor(() =>
  7274. expect(app.tui.render(100).join("\n")).toContain(
  7275. "Editing the selected message",
  7276. ),
  7277. );
  7278. expect(app.editor.getExpandedText()).toBe("[Image #1] ");
  7279. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7280. kind: "chat",
  7281. id: "chat",
  7282. });
  7283. app.editor.setText("Describe this reference");
  7284. app.editor.handleInput("\r");
  7285. await vi.waitFor(() =>
  7286. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7287. );
  7288. expect(runtime.editSessionMessage).toHaveBeenCalledWith({
  7289. sessionId: "session-1",
  7290. userMessageId: "msg-user-v1-attachment-only",
  7291. clientRequestId: expect.stringMatching(/^tui-edit_/u),
  7292. content: "Describe this reference",
  7293. attachments: [
  7294. {
  7295. type: "image",
  7296. fileName: "reference.png",
  7297. mimeType: "image/png",
  7298. filePath: "/workspace/reference.png",
  7299. },
  7300. ],
  7301. rewindTurnDiff: true,
  7302. });
  7303. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
  7304. await app.stop();
  7305. });
  7306. it("keeps a second composer submission while an edit request is still in flight", async () => {
  7307. const terminal = new FakeTerminal();
  7308. const runtime = createRuntime();
  7309. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7310. {
  7311. userMessageId: "msg-user-v1-target",
  7312. assistantMessageId: "msg-assistant-v1-target",
  7313. contentHead: "Original prompt",
  7314. timestamp: 1,
  7315. fileChangeCount: 0,
  7316. },
  7317. ]);
  7318. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7319. messages: [
  7320. {
  7321. id: "msg-user-v1-target",
  7322. role: "user",
  7323. content: "Original prompt",
  7324. timestamp: 1,
  7325. },
  7326. ],
  7327. hasMore: false,
  7328. });
  7329. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7330. let resolveEdit!: (value: {
  7331. rewound: boolean;
  7332. turnId: string;
  7333. userMessageId: string;
  7334. }) => void;
  7335. vi.mocked(runtime.editSessionMessage).mockImplementation(
  7336. () =>
  7337. new Promise((resolve) => {
  7338. resolveEdit = resolve;
  7339. }),
  7340. );
  7341. const app = createTuiApp({
  7342. runtime,
  7343. terminal,
  7344. version: "0.1.0",
  7345. workspaceDir: "/workspace",
  7346. });
  7347. app.start();
  7348. await app.ready;
  7349. await app.submit("Seed edit session");
  7350. const sendCountBeforeEdit = vi.mocked(runtime.sendMessage).mock.calls
  7351. .length;
  7352. await app.submit("/edit");
  7353. await vi.waitFor(() =>
  7354. expect(app.editor.getText()).toBe("Original prompt"),
  7355. );
  7356. app.editor.setText("First edited prompt");
  7357. app.editor.handleInput("\r");
  7358. await vi.waitFor(() =>
  7359. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7360. );
  7361. app.editor.setText("Keep this until edit settles");
  7362. app.editor.handleInput("\r");
  7363. await vi.waitFor(() =>
  7364. expect(app.editor.getText()).toBe("Keep this until edit settles"),
  7365. );
  7366. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
  7367. resolveEdit({
  7368. rewound: true,
  7369. turnId: "turn-edit-1",
  7370. userMessageId: "msg-user-v1-edited",
  7371. });
  7372. await app.stop();
  7373. });
  7374. it("preserves the edit and retries the same operation when submission fails after rewind", async () => {
  7375. const terminal = new FakeTerminal();
  7376. const runtime = createRuntime();
  7377. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7378. {
  7379. userMessageId: "msg-user-v1-target",
  7380. assistantMessageId: "msg-assistant-v1-target",
  7381. contentHead: "Original prompt",
  7382. timestamp: 1,
  7383. fileChangeCount: 0,
  7384. },
  7385. ]);
  7386. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7387. messages: [
  7388. {
  7389. id: "msg-user-v1-target",
  7390. role: "user",
  7391. content: "Original prompt",
  7392. timestamp: 1,
  7393. },
  7394. ],
  7395. hasMore: false,
  7396. });
  7397. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7398. vi.mocked(runtime.editSessionMessage)
  7399. .mockRejectedValueOnce(
  7400. Object.assign(new Error("submit failed"), {
  7401. key: "EDIT_SUBMIT_FAILED_AFTER_REWIND",
  7402. }),
  7403. )
  7404. .mockResolvedValueOnce({
  7405. rewound: true,
  7406. turnId: "turn-edit-retry",
  7407. userMessageId: "msg-user-v1-edited",
  7408. });
  7409. const app = createTuiApp({
  7410. runtime,
  7411. terminal,
  7412. version: "0.1.0",
  7413. workspaceDir: "/workspace",
  7414. });
  7415. app.start();
  7416. await app.ready;
  7417. await app.submit("Seed edit session");
  7418. await app.submit("/edit");
  7419. await vi.waitFor(() =>
  7420. expect(app.editor.getText()).toBe("Original prompt"),
  7421. );
  7422. app.editor.setText("Preserve this edited prompt");
  7423. app.editor.handleInput("\r");
  7424. await vi.waitFor(() =>
  7425. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7426. );
  7427. await vi.waitFor(() =>
  7428. expect(app.editor.getText()).toBe("Preserve this edited prompt"),
  7429. );
  7430. expect(
  7431. app.transcript
  7432. .snapshot()
  7433. .some((cell) => cell.content.includes("History was rewound")),
  7434. ).toBe(true);
  7435. const firstOperationId = vi.mocked(runtime.editSessionMessage).mock
  7436. .calls[0]?.[0].clientRequestId;
  7437. const sendCount = vi.mocked(runtime.sendMessage).mock.calls.length;
  7438. app.editor.handleInput("\r");
  7439. await vi.waitFor(() =>
  7440. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(2),
  7441. );
  7442. expect(runtime.editSessionMessage).toHaveBeenLastCalledWith(
  7443. expect.objectContaining({ clientRequestId: firstOperationId }),
  7444. );
  7445. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCount);
  7446. await app.stop();
  7447. });
  7448. it("cancels /rewind preview and ignores duplicate scope submission", async () => {
  7449. const terminal = new FakeTerminal();
  7450. const runtime = createRuntime();
  7451. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7452. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7453. ]);
  7454. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7455. turns: [
  7456. {
  7457. turnId: "turn-1",
  7458. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7459. },
  7460. ],
  7461. });
  7462. let resolveRewind!: (value: { rewound: boolean }) => void;
  7463. vi.mocked(runtime.rewindSession).mockImplementation(
  7464. () =>
  7465. new Promise((resolve) => {
  7466. resolveRewind = resolve;
  7467. }),
  7468. );
  7469. const app = createTuiApp({
  7470. runtime,
  7471. terminal,
  7472. version: "0.1.0",
  7473. workspaceDir: "/workspace",
  7474. });
  7475. app.start();
  7476. await app.ready;
  7477. await app.submit("Seed rewind session");
  7478. await app.submit("/rewind");
  7479. await vi.waitFor(() =>
  7480. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7481. kind: "feature",
  7482. id: "session-mutation:history",
  7483. }),
  7484. );
  7485. terminal.input?.("\r");
  7486. await vi.waitFor(() =>
  7487. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7488. kind: "feature",
  7489. id: "session-mutation:rewind-preview",
  7490. }),
  7491. );
  7492. terminal.input?.("\u001b");
  7493. expect(runtime.rewindSession).not.toHaveBeenCalled();
  7494. await app.submit("/rewind");
  7495. await vi.waitFor(() =>
  7496. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7497. kind: "feature",
  7498. id: "session-mutation:history",
  7499. }),
  7500. );
  7501. terminal.input?.("\r");
  7502. await vi.waitFor(() =>
  7503. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7504. kind: "feature",
  7505. id: "session-mutation:rewind-preview",
  7506. }),
  7507. );
  7508. terminal.input?.("\r");
  7509. await vi.waitFor(() =>
  7510. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7511. kind: "feature",
  7512. id: "session-mutation:scope",
  7513. }),
  7514. );
  7515. terminal.input?.("\r");
  7516. await vi.waitFor(() =>
  7517. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7518. kind: "feature",
  7519. id: "session-mutation:rewind-confirm",
  7520. }),
  7521. );
  7522. terminal.input?.("\r");
  7523. await vi.waitFor(() =>
  7524. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  7525. );
  7526. terminal.input?.("\u001b");
  7527. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7528. kind: "feature",
  7529. id: "session-mutation:rewind-confirm",
  7530. });
  7531. resolveRewind({ rewound: true });
  7532. await app.stop();
  7533. });
  7534. it("invalidates /rewind when the active session switches before mutation", async () => {
  7535. const terminal = new FakeTerminal();
  7536. const runtime = createRuntime();
  7537. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7538. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 0 },
  7539. ]);
  7540. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7541. const app = createTuiApp({
  7542. runtime,
  7543. terminal,
  7544. version: "0.1.0",
  7545. workspaceDir: "/workspace",
  7546. });
  7547. app.start();
  7548. await app.ready;
  7549. await app.submit("Seed rewind session");
  7550. await app.submit("/rewind");
  7551. await vi.waitFor(() =>
  7552. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7553. kind: "feature",
  7554. id: "session-mutation:history",
  7555. }),
  7556. );
  7557. const other = {
  7558. sessionId: "session-other",
  7559. title: "Other",
  7560. workspaceDir: "/workspace",
  7561. };
  7562. vi.mocked(runtime.getSession).mockResolvedValue(other);
  7563. await app.openSession(other.sessionId);
  7564. terminal.input?.("\r");
  7565. await new Promise((resolve) => setTimeout(resolve, 20));
  7566. expect(runtime.getSessionRewindPreview).not.toHaveBeenCalled();
  7567. expect(runtime.rewindSession).not.toHaveBeenCalled();
  7568. expect(app.controller.snapshot().session?.sessionId).toBe(other.sessionId);
  7569. await app.stop();
  7570. });
  7571. it("retries a failed file rewind with the same operation id", async () => {
  7572. const terminal = new FakeTerminal();
  7573. const runtime = createRuntime();
  7574. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7575. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7576. ]);
  7577. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7578. turns: [
  7579. {
  7580. turnId: "turn-1",
  7581. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7582. },
  7583. ],
  7584. });
  7585. vi.mocked(runtime.rewindSession)
  7586. .mockRejectedValueOnce(new Error("temporary conflict"))
  7587. .mockResolvedValueOnce({
  7588. rewound: true,
  7589. turnDiffRewind: { status: "rewound", revertedTurnIds: ["turn-1"] },
  7590. });
  7591. const app = createTuiApp({
  7592. runtime,
  7593. terminal,
  7594. version: "0.1.0",
  7595. workspaceDir: "/workspace",
  7596. });
  7597. app.start();
  7598. await app.ready;
  7599. await app.submit("Seed rewind session");
  7600. await app.submit("/rewind");
  7601. await vi.waitFor(() =>
  7602. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7603. kind: "feature",
  7604. id: "session-mutation:history",
  7605. }),
  7606. );
  7607. terminal.input?.("\r");
  7608. await vi.waitFor(() =>
  7609. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7610. kind: "feature",
  7611. id: "session-mutation:rewind-preview",
  7612. }),
  7613. );
  7614. terminal.input?.("\r");
  7615. await vi.waitFor(() =>
  7616. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7617. kind: "feature",
  7618. id: "session-mutation:scope",
  7619. }),
  7620. );
  7621. terminal.input?.("\u001b[B");
  7622. terminal.input?.("\r");
  7623. await vi.waitFor(() =>
  7624. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7625. kind: "feature",
  7626. id: "session-mutation:rewind-confirm",
  7627. }),
  7628. );
  7629. terminal.input?.("\r");
  7630. await vi.waitFor(() =>
  7631. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  7632. );
  7633. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7634. kind: "feature",
  7635. id: "session-mutation:rewind-confirm",
  7636. });
  7637. terminal.input?.("\r");
  7638. await vi.waitFor(() =>
  7639. expect(runtime.rewindSession).toHaveBeenCalledTimes(2),
  7640. );
  7641. const ids = vi
  7642. .mocked(runtime.rewindSession)
  7643. .mock.calls.map(([input]) => input.clientRequestId);
  7644. expect(ids[0]).toBe(ids[1]);
  7645. await app.stop();
  7646. });
  7647. it.each([
  7648. [
  7649. "terminal busy failure",
  7650. "CONVERSATION_MUTATION_BUSY",
  7651. "Stop the running response and try again.",
  7652. false,
  7653. ],
  7654. [
  7655. "pending display publication",
  7656. "REWIND_DISPLAY_COMMIT_FAILED",
  7657. "retry with the same operation id",
  7658. true,
  7659. ],
  7660. ] as const)(
  7661. "keeps a failed conversation rewind open and retries %s with the correct operation id",
  7662. async (_label, errorCode, expectedCopy, reuseOperationId) => {
  7663. const terminal = new FakeTerminal();
  7664. const runtime = createRuntime();
  7665. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7666. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 0 },
  7667. ]);
  7668. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7669. turns: [],
  7670. });
  7671. vi.mocked(runtime.rewindSession)
  7672. .mockRejectedValueOnce(
  7673. Object.assign(new Error("rewind failed"), { key: errorCode }),
  7674. )
  7675. .mockResolvedValueOnce({ rewound: true });
  7676. const app = createTuiApp({
  7677. runtime,
  7678. terminal,
  7679. version: "0.1.0",
  7680. workspaceDir: "/workspace",
  7681. });
  7682. app.start();
  7683. await app.ready;
  7684. await app.submit("Seed rewind session");
  7685. await app.submit("/rewind");
  7686. await vi.waitFor(() =>
  7687. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7688. kind: "feature",
  7689. id: "session-mutation:history",
  7690. }),
  7691. );
  7692. terminal.input?.("\r");
  7693. await vi.waitFor(() =>
  7694. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7695. kind: "feature",
  7696. id: "session-mutation:rewind-preview",
  7697. }),
  7698. );
  7699. terminal.input?.("\r");
  7700. await vi.waitFor(() =>
  7701. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7702. kind: "feature",
  7703. id: "session-mutation:scope",
  7704. }),
  7705. );
  7706. terminal.input?.("\r");
  7707. await vi.waitFor(() =>
  7708. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7709. kind: "feature",
  7710. id: "session-mutation:rewind-confirm",
  7711. }),
  7712. );
  7713. terminal.input?.("\r");
  7714. await vi.waitFor(() =>
  7715. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  7716. );
  7717. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7718. kind: "feature",
  7719. id: "session-mutation:rewind-confirm",
  7720. });
  7721. expect(renderTerminalViewport(app, terminal)).toContain(expectedCopy);
  7722. terminal.input?.("\r");
  7723. await vi.waitFor(() =>
  7724. expect(runtime.rewindSession).toHaveBeenCalledTimes(2),
  7725. );
  7726. const ids = vi
  7727. .mocked(runtime.rewindSession)
  7728. .mock.calls.map(([input]) => input.clientRequestId);
  7729. if (reuseOperationId) expect(ids[0]).toBe(ids[1]);
  7730. else expect(ids[0]).not.toBe(ids[1]);
  7731. await app.stop();
  7732. },
  7733. );
  7734. it.each([
  7735. [
  7736. "failed-after-rewind",
  7737. {
  7738. status: "failed-after-rewind",
  7739. revertedTurnIds: ["turn-1"],
  7740. errorCode: "conflict",
  7741. },
  7742. ],
  7743. ["empty-reverted-ids", { status: "rewound", revertedTurnIds: [] }],
  7744. [
  7745. "unknown-status",
  7746. { status: "future-runtime-status", revertedTurnIds: ["turn-1"] },
  7747. ],
  7748. ] as const)(
  7749. "does not report %s as a successful file rewind",
  7750. async (_label, turnDiffRewind) => {
  7751. const terminal = new FakeTerminal();
  7752. const runtime = createRuntime();
  7753. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7754. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7755. ]);
  7756. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7757. turns: [
  7758. {
  7759. turnId: "turn-1",
  7760. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7761. },
  7762. ],
  7763. });
  7764. vi.mocked(runtime.rewindSession).mockResolvedValue({
  7765. rewound: true,
  7766. turnDiffRewind,
  7767. });
  7768. const app = createTuiApp({
  7769. runtime,
  7770. terminal,
  7771. version: "0.1.0",
  7772. workspaceDir: "/workspace",
  7773. });
  7774. app.start();
  7775. await app.ready;
  7776. await app.submit("Seed rewind session");
  7777. await app.submit("/rewind");
  7778. await vi.waitFor(() =>
  7779. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7780. kind: "feature",
  7781. id: "session-mutation:history",
  7782. }),
  7783. );
  7784. terminal.input?.("\r");
  7785. await vi.waitFor(() =>
  7786. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7787. kind: "feature",
  7788. id: "session-mutation:rewind-preview",
  7789. }),
  7790. );
  7791. terminal.input?.("\r");
  7792. await vi.waitFor(() =>
  7793. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7794. kind: "feature",
  7795. id: "session-mutation:scope",
  7796. }),
  7797. );
  7798. terminal.input?.("\u001b[B");
  7799. terminal.input?.("\r");
  7800. await vi.waitFor(() =>
  7801. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7802. kind: "feature",
  7803. id: "session-mutation:rewind-confirm",
  7804. }),
  7805. );
  7806. terminal.input?.("\r");
  7807. await vi.waitFor(() =>
  7808. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  7809. );
  7810. await vi.waitFor(() =>
  7811. expect(app.transcript.snapshot().at(-1)?.content).toMatch(
  7812. /did not complete|No file changes/,
  7813. ),
  7814. );
  7815. expect(app.transcript.snapshot().at(-1)?.content).not.toContain(
  7816. "Files rewound; conversation history was kept.",
  7817. );
  7818. await app.stop();
  7819. },
  7820. );
  7821. it.each([
  7822. [
  7823. "MESSAGE_BOUNDARY_INVALID",
  7824. "This conversation point is no longer available.",
  7825. ],
  7826. [
  7827. "CONVERSATION_MUTATION_REQUEST_CONFLICT",
  7828. "This action was already submitted or became stale.",
  7829. ],
  7830. ["CONVERSATION_MUTATION_BUSY", "Stop the running response and try again."],
  7831. ] as const)(
  7832. "maps rewind Runtime error %s to stable copy",
  7833. async (code, expected) => {
  7834. const terminal = new FakeTerminal();
  7835. const runtime = createRuntime();
  7836. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7837. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7838. ]);
  7839. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7840. turns: [
  7841. {
  7842. turnId: "turn-1",
  7843. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7844. },
  7845. ],
  7846. });
  7847. vi.mocked(runtime.rewindSession).mockRejectedValue(
  7848. Object.assign(new Error("raw prompt token=secret"), { key: code }),
  7849. );
  7850. const app = createTuiApp({
  7851. runtime,
  7852. terminal,
  7853. version: "0.1.0",
  7854. workspaceDir: "/workspace",
  7855. });
  7856. app.start();
  7857. await app.ready;
  7858. await app.submit("Seed rewind session");
  7859. await app.submit("/rewind");
  7860. await vi.waitFor(() =>
  7861. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7862. kind: "feature",
  7863. id: "session-mutation:history",
  7864. }),
  7865. );
  7866. terminal.input?.("\r");
  7867. await vi.waitFor(() =>
  7868. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7869. kind: "feature",
  7870. id: "session-mutation:rewind-preview",
  7871. }),
  7872. );
  7873. terminal.input?.("\r");
  7874. await vi.waitFor(() =>
  7875. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7876. kind: "feature",
  7877. id: "session-mutation:scope",
  7878. }),
  7879. );
  7880. terminal.input?.("\u001b[B");
  7881. terminal.input?.("\r");
  7882. await vi.waitFor(() =>
  7883. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7884. kind: "feature",
  7885. id: "session-mutation:rewind-confirm",
  7886. }),
  7887. );
  7888. terminal.input?.("\r");
  7889. await vi.waitFor(() =>
  7890. expect(
  7891. app.transcript.snapshot().some((cell) => cell.content === expected),
  7892. ),
  7893. );
  7894. expect(
  7895. app.transcript
  7896. .snapshot()
  7897. .some((cell) => cell.content.includes("raw prompt token")),
  7898. ).toBe(false);
  7899. await app.stop();
  7900. },
  7901. );
  7902. it("reports refresh failure without unhandled rejection after conversation-and-files rewind", async () => {
  7903. const terminal = new FakeTerminal();
  7904. const runtime = createRuntime();
  7905. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7906. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7907. ]);
  7908. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7909. turns: [
  7910. {
  7911. turnId: "turn-1",
  7912. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7913. },
  7914. ],
  7915. });
  7916. vi.mocked(runtime.rewindSession).mockResolvedValue({
  7917. rewound: true,
  7918. turnDiffRewind: { status: "rewound", revertedTurnIds: ["turn-1"] },
  7919. });
  7920. vi.mocked(runtime.getMessages).mockRejectedValueOnce(
  7921. new Error("refresh unavailable"),
  7922. );
  7923. const app = createTuiApp({
  7924. runtime,
  7925. terminal,
  7926. version: "0.1.0",
  7927. workspaceDir: "/workspace",
  7928. });
  7929. app.start();
  7930. await app.ready;
  7931. await app.submit("Seed rewind session");
  7932. await app.submit("/rewind");
  7933. await vi.waitFor(() =>
  7934. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7935. kind: "feature",
  7936. id: "session-mutation:history",
  7937. }),
  7938. );
  7939. terminal.input?.("\r");
  7940. await vi.waitFor(() =>
  7941. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7942. kind: "feature",
  7943. id: "session-mutation:rewind-preview",
  7944. }),
  7945. );
  7946. terminal.input?.("\r");
  7947. await vi.waitFor(() =>
  7948. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7949. kind: "feature",
  7950. id: "session-mutation:scope",
  7951. }),
  7952. );
  7953. terminal.input?.("\u001b[B");
  7954. terminal.input?.("\r");
  7955. await vi.waitFor(() =>
  7956. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7957. kind: "feature",
  7958. id: "session-mutation:rewind-confirm",
  7959. }),
  7960. );
  7961. terminal.input?.("\r");
  7962. await vi.waitFor(() =>
  7963. expect(
  7964. app.transcript
  7965. .snapshot()
  7966. .some((cell) => cell.content.includes("could not be refreshed")),
  7967. ),
  7968. );
  7969. await app.stop();
  7970. });
  7971. it("does not apply a pending rewind refresh result after switching sessions", async () => {
  7972. const terminal = new FakeTerminal();
  7973. const runtime = createRuntime();
  7974. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7975. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7976. ]);
  7977. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7978. turns: [
  7979. {
  7980. turnId: "turn-1",
  7981. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7982. },
  7983. ],
  7984. });
  7985. vi.mocked(runtime.rewindSession).mockResolvedValue({
  7986. rewound: true,
  7987. turnDiffRewind: { status: "rewound", revertedTurnIds: ["turn-1"] },
  7988. });
  7989. let resolveRefresh!: (messages: readonly TuiMessage[]) => void;
  7990. const refreshPromise = new Promise<readonly TuiMessage[]>((resolve) => {
  7991. resolveRefresh = resolve;
  7992. });
  7993. const app = createTuiApp({
  7994. runtime,
  7995. terminal,
  7996. version: "0.1.0",
  7997. workspaceDir: "/workspace",
  7998. });
  7999. app.start();
  8000. await app.ready;
  8001. await app.submit("Seed rewind session");
  8002. vi.mocked(runtime.getMessages).mockImplementationOnce(() => refreshPromise);
  8003. await app.submit("/rewind");
  8004. await vi.waitFor(() =>
  8005. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8006. kind: "feature",
  8007. id: "session-mutation:history",
  8008. }),
  8009. );
  8010. terminal.input?.("\r");
  8011. await vi.waitFor(() =>
  8012. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8013. kind: "feature",
  8014. id: "session-mutation:rewind-preview",
  8015. }),
  8016. );
  8017. terminal.input?.("\r");
  8018. await vi.waitFor(() =>
  8019. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8020. kind: "feature",
  8021. id: "session-mutation:scope",
  8022. }),
  8023. );
  8024. terminal.input?.("\u001b[B");
  8025. terminal.input?.("\r");
  8026. await vi.waitFor(() =>
  8027. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8028. kind: "feature",
  8029. id: "session-mutation:rewind-confirm",
  8030. }),
  8031. );
  8032. terminal.input?.("\r");
  8033. await vi.waitFor(() =>
  8034. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  8035. );
  8036. const other = {
  8037. sessionId: "session-other",
  8038. title: "Other",
  8039. workspaceDir: "/workspace",
  8040. };
  8041. vi.mocked(runtime.getSession).mockResolvedValue(other);
  8042. vi.mocked(runtime.getMessages).mockResolvedValue([]);
  8043. const open = app.openSession(other.sessionId);
  8044. resolveRefresh([
  8045. {
  8046. id: "stale-message",
  8047. role: "assistant",
  8048. content: "stale",
  8049. timestamp: 3,
  8050. },
  8051. ]);
  8052. await open;
  8053. expect(app.controller.snapshot().session?.sessionId).toBe(other.sessionId);
  8054. expect(
  8055. app.transcript
  8056. .snapshot()
  8057. .some((cell) => cell.content.includes("Files rewound")),
  8058. ).toBe(false);
  8059. await app.stop();
  8060. });
  8061. it("redirects a hidden task child to its parent before rendering", async () => {
  8062. const runtime = createRuntime();
  8063. const parent = {
  8064. sessionId: "session-parent",
  8065. title: "CLI integration",
  8066. workspaceDir: "/workspace",
  8067. };
  8068. const child = {
  8069. sessionId: "session-child",
  8070. parentSessionId: parent.sessionId,
  8071. title: "Review recent CLI changes",
  8072. workspaceDir: "/workspace",
  8073. sessionType: "branch",
  8074. sessionKind: "task",
  8075. visibility: "hidden",
  8076. purpose: "local-task:turn-1:tool-1",
  8077. agentName: "verifier",
  8078. };
  8079. vi.mocked(runtime.listSessions).mockResolvedValue([parent]);
  8080. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  8081. sessionId === child.sessionId ? child : parent,
  8082. );
  8083. const app = createTuiApp({
  8084. runtime,
  8085. terminal: new FakeTerminal(),
  8086. version: "0.1.0",
  8087. workspaceDir: "/workspace",
  8088. });
  8089. await app.ready;
  8090. await app.openSession(child.sessionId);
  8091. expect(runtime.getSession).toHaveBeenLastCalledWith(parent.sessionId);
  8092. expect(app.controller.snapshot().session?.sessionId).toBe(parent.sessionId);
  8093. expect(app.tui.render(140).join("\n")).not.toContain("Sub: verifier");
  8094. expect(app.transcript.snapshot().at(-1)?.content).toBe(
  8095. "Sub-agent Sessions are internal. Opened the parent Session instead.",
  8096. );
  8097. await app.stop();
  8098. });
  8099. it("shows compact Agent Team status without exposing child details or commands", async () => {
  8100. const terminal = new FakeTerminal();
  8101. terminal.rows = 24;
  8102. const runtime = createRuntime();
  8103. const parent = {
  8104. sessionId: "session-parent",
  8105. title: "Agent Team parent",
  8106. workspaceDir: "/workspace",
  8107. };
  8108. const child = {
  8109. sessionId: "session-child",
  8110. parentSessionId: parent.sessionId,
  8111. title: "Verify the TUI",
  8112. workspaceDir: "/workspace",
  8113. sessionType: "branch" as const,
  8114. sessionKind: "task",
  8115. visibility: "hidden" as const,
  8116. purpose: "local-task:turn-1:tool-1",
  8117. agentName: "verifier",
  8118. status: "finished",
  8119. };
  8120. vi.mocked(runtime.listSessions).mockResolvedValue([parent]);
  8121. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  8122. sessionId === child.sessionId ? child : parent,
  8123. );
  8124. vi.mocked(runtime.getDelegationSnapshot).mockResolvedValue({
  8125. schemaVersion: 1,
  8126. rootSessionId: parent.sessionId,
  8127. members: [
  8128. {
  8129. sessionId: child.sessionId,
  8130. parentSessionId: parent.sessionId,
  8131. agentName: child.agentName,
  8132. task: child.title,
  8133. status: "running",
  8134. createdAtMs: 100,
  8135. updatedAtMs: 200,
  8136. },
  8137. ],
  8138. });
  8139. vi.mocked(runtime.getMessages).mockImplementation(async (sessionId) =>
  8140. sessionId === child.sessionId
  8141. ? [
  8142. {
  8143. id: "child-answer",
  8144. turnId: "turn-child",
  8145. role: "assistant",
  8146. content: "Child verification result",
  8147. timestamp: 200,
  8148. },
  8149. ]
  8150. : [],
  8151. );
  8152. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
  8153. schemaVersion: 1,
  8154. sessionId,
  8155. state: sessionId === child.sessionId ? "running" : "idle",
  8156. ...(sessionId === child.sessionId ? { turnId: "turn-child" } : {}),
  8157. actions: { steer: false },
  8158. }));
  8159. const app = createTuiApp({
  8160. runtime,
  8161. terminal,
  8162. version: "0.1.0",
  8163. workspaceDir: "/workspace",
  8164. });
  8165. await app.ready;
  8166. await app.openSession(parent.sessionId);
  8167. app.start();
  8168. const summary = app.tui.render(100).join("\n");
  8169. expect(summary).toContain("Tasks · 1 agent active · /tasks details");
  8170. expect(summary).not.toContain("verifier");
  8171. expect(summary).not.toContain("/agents");
  8172. expect(
  8173. app.transcript.snapshot().some((cell) => cell.kind === "agent-team"),
  8174. ).toBe(false);
  8175. await app.submit("/agents");
  8176. await app.submit("/team");
  8177. expect(app.controller.snapshot().session?.sessionId).toBe(parent.sessionId);
  8178. expect(app.tui.hasOverlay()).toBe(false);
  8179. expect(app.interaction.isActive()).toBe(false);
  8180. expect(app.tui.render(100).join("\n")).not.toContain(
  8181. "Child verification result",
  8182. );
  8183. expect(
  8184. vi
  8185. .mocked(runtime.sendMessage)
  8186. .mock.calls.map(([request]) => request.content),
  8187. ).toEqual(["/agents", "/team"]);
  8188. await app.stop();
  8189. });
  8190. it("allocates enough standard-terminal space for ten session choices", async () => {
  8191. const terminal = new FakeTerminal();
  8192. terminal.rows = 24;
  8193. const runtime = createRuntime();
  8194. vi.mocked(runtime.listSessionPage).mockResolvedValue({
  8195. sessions: Array.from({ length: 12 }, (_, index) => ({
  8196. sessionId: `session-${String(index + 1).padStart(2, "0")}`,
  8197. title: `Session ${String(index + 1).padStart(2, "0")}`,
  8198. workspaceDir: "/workspace",
  8199. updatedAt: 12 - index,
  8200. })),
  8201. hasMore: false,
  8202. });
  8203. const app = createTuiApp({
  8204. runtime,
  8205. terminal,
  8206. version: "0.1.0",
  8207. workspaceDir: "/workspace",
  8208. });
  8209. await app.submit("/sessions");
  8210. const lines = app.interaction.current()?.render(80) ?? [];
  8211. const rendered = lines.join("\n");
  8212. expect(lines.length).toBeLessThanOrEqual(terminal.rows);
  8213. expect(rendered).toContain("Session 10");
  8214. expect(rendered).not.toContain("Session 11");
  8215. });
  8216. it("switches, restores, and resumes archived Desktop sessions from the session manager", async () => {
  8217. const terminal = new FakeTerminal();
  8218. const runtime = createRuntime();
  8219. let archived = true;
  8220. const activeSession = {
  8221. sessionId: "session-active",
  8222. title: "Active session",
  8223. workspaceDir: "/workspace",
  8224. updatedAt: 200,
  8225. };
  8226. const archivedSession = {
  8227. sessionId: "session-archived",
  8228. title: "Archived session",
  8229. workspaceDir: "/workspace",
  8230. updatedAt: 100,
  8231. archived: true,
  8232. };
  8233. vi.mocked(runtime.listSessions).mockResolvedValue([activeSession]);
  8234. vi.mocked(runtime.listSessionPage).mockResolvedValue({
  8235. sessions: [activeSession, archivedSession],
  8236. hasMore: false,
  8237. });
  8238. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) => ({
  8239. ...(sessionId === archivedSession.sessionId
  8240. ? archivedSession
  8241. : activeSession),
  8242. archived: sessionId === archivedSession.sessionId ? archived : false,
  8243. }));
  8244. vi.mocked(runtime.archiveSession).mockImplementation(
  8245. async (_sessionId, value) => {
  8246. archived = value;
  8247. },
  8248. );
  8249. const app = createTuiApp({
  8250. runtime,
  8251. terminal,
  8252. version: "0.1.0",
  8253. workspaceDir: "/workspace",
  8254. });
  8255. app.start();
  8256. await app.ready;
  8257. await app.submit("/sessions");
  8258. expect(runtime.listSessionPage).toHaveBeenCalledWith({
  8259. allAgents: true,
  8260. workspaceDir: "/workspace",
  8261. limit: 50,
  8262. includeArchived: true,
  8263. includeHidden: true,
  8264. });
  8265. expect(app.tui.hasOverlay()).toBe(false);
  8266. expect(app.interaction.isActive()).toBe(true);
  8267. terminal.input?.("\t");
  8268. terminal.input?.("\r");
  8269. await vi.waitFor(() =>
  8270. expect(runtime.archiveSession).toHaveBeenCalledWith(
  8271. "session-archived",
  8272. false,
  8273. ),
  8274. );
  8275. await vi.waitFor(() =>
  8276. expect(runtime.getMessages).toHaveBeenCalledWith("session-archived"),
  8277. );
  8278. expect(app.getSurface()).toBe("conversation");
  8279. expect(app.controller.snapshot().session?.sessionId).toBe(
  8280. "session-archived",
  8281. );
  8282. expect(app.tui.hasOverlay()).toBe(false);
  8283. await app.stop();
  8284. });
  8285. it("uses the resume alias to search every Desktop session page", async () => {
  8286. const terminal = new FakeTerminal();
  8287. const runtime = createRuntime();
  8288. vi.mocked(runtime.listSessionPage)
  8289. .mockResolvedValueOnce({
  8290. sessions: [
  8291. {
  8292. sessionId: "session-page-1",
  8293. title: "First page",
  8294. workspaceDir: "/workspace",
  8295. updatedAt: 200,
  8296. },
  8297. ],
  8298. hasMore: true,
  8299. nextCursor: "session-page-1",
  8300. })
  8301. .mockResolvedValueOnce({
  8302. sessions: [
  8303. {
  8304. sessionId: "session-page-2",
  8305. title: "Second page",
  8306. workspaceDir: "/workspace",
  8307. updatedAt: 100,
  8308. },
  8309. ],
  8310. hasMore: false,
  8311. });
  8312. const app = createTuiApp({
  8313. runtime,
  8314. terminal,
  8315. version: "0.1.0",
  8316. workspaceDir: "/workspace",
  8317. });
  8318. app.start();
  8319. await app.ready;
  8320. await app.submit("/resume Second page");
  8321. await vi.waitFor(() =>
  8322. expect(runtime.listSessionPage).toHaveBeenNthCalledWith(2, {
  8323. allAgents: true,
  8324. workspaceDir: "/workspace",
  8325. limit: 50,
  8326. cursor: "session-page-1",
  8327. includeArchived: true,
  8328. includeHidden: true,
  8329. }),
  8330. );
  8331. expect(app.tui.hasOverlay()).toBe(false);
  8332. expect(app.interaction.isActive()).toBe(true);
  8333. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8334. "Second page",
  8335. );
  8336. await app.stop();
  8337. });
  8338. it("queries the current workspace first and reloads the global catalog on Ctrl+A", async () => {
  8339. const terminal = new FakeTerminal();
  8340. const runtime = createRuntime();
  8341. vi.mocked(runtime.listSessionPage).mockImplementation(
  8342. async (input = {}) => {
  8343. if (input.cursor === "all-page-2") {
  8344. return {
  8345. sessions: [
  8346. {
  8347. sessionId: "session-other-older",
  8348. title: "Older session elsewhere",
  8349. workspaceDir: "/other-workspace",
  8350. updatedAt: 50,
  8351. },
  8352. ],
  8353. hasMore: false,
  8354. };
  8355. }
  8356. return input.workspaceDir
  8357. ? {
  8358. sessions: [
  8359. {
  8360. sessionId: "session-workspace-old",
  8361. title: "Older workspace session",
  8362. workspaceDir: "/workspace",
  8363. updatedAt: 100,
  8364. },
  8365. ],
  8366. hasMore: false,
  8367. }
  8368. : {
  8369. sessions: [
  8370. {
  8371. sessionId: "session-other-new",
  8372. title: "Newer session elsewhere",
  8373. workspaceDir: "/other-workspace",
  8374. updatedAt: 200,
  8375. },
  8376. {
  8377. sessionId: "session-workspace-old",
  8378. title: "Older workspace session",
  8379. workspaceDir: "/workspace",
  8380. updatedAt: 100,
  8381. },
  8382. ],
  8383. hasMore: true,
  8384. nextCursor: "all-page-2",
  8385. };
  8386. },
  8387. );
  8388. const app = createTuiApp({
  8389. runtime,
  8390. terminal,
  8391. version: "0.1.0",
  8392. workspaceDir: "/workspace",
  8393. });
  8394. app.start();
  8395. await app.ready;
  8396. await app.submit("/sessions");
  8397. expect(runtime.listSessionPage).toHaveBeenNthCalledWith(1, {
  8398. allAgents: true,
  8399. workspaceDir: "/workspace",
  8400. limit: 50,
  8401. includeArchived: true,
  8402. includeHidden: true,
  8403. });
  8404. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8405. "Older workspace session",
  8406. );
  8407. terminal.input?.("\x01");
  8408. await vi.waitFor(() =>
  8409. expect(runtime.listSessionPage).toHaveBeenNthCalledWith(2, {
  8410. allAgents: true,
  8411. limit: 50,
  8412. includeArchived: true,
  8413. includeHidden: true,
  8414. }),
  8415. );
  8416. await vi.waitFor(() =>
  8417. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8418. "Newer session elsewhere",
  8419. ),
  8420. );
  8421. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8422. "All sessions",
  8423. );
  8424. terminal.input?.("\x0c");
  8425. await vi.waitFor(() =>
  8426. expect(runtime.listSessionPage).toHaveBeenNthCalledWith(3, {
  8427. allAgents: true,
  8428. limit: 50,
  8429. cursor: "all-page-2",
  8430. includeArchived: true,
  8431. includeHidden: true,
  8432. }),
  8433. );
  8434. await vi.waitFor(() =>
  8435. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8436. "Older session elsewhere",
  8437. ),
  8438. );
  8439. await app.stop();
  8440. });
  8441. it("shows account status and resolves pending permission and questionnaire decisions", async () => {
  8442. const terminal = new FakeTerminal();
  8443. const runtime = createRuntime();
  8444. vi.mocked(runtime.listSessions).mockResolvedValue([
  8445. {
  8446. sessionId: "session-existing",
  8447. title: "Existing session",
  8448. workspaceDir: "/workspace",
  8449. },
  8450. ]);
  8451. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  8452. {
  8453. requestId: "permission-1",
  8454. sessionId: "session-existing",
  8455. agentName: "mavis",
  8456. toolName: "bash",
  8457. reason: "Run tests",
  8458. allowAlwaysSupported: true,
  8459. },
  8460. ]);
  8461. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8462. id: "question-1",
  8463. title: "Choose",
  8464. steps: [
  8465. {
  8466. id: "step-1",
  8467. question: "Proceed?",
  8468. selectionMode: "single",
  8469. options: [
  8470. { id: "yes", label: "Yes" },
  8471. { id: "no", label: "No" },
  8472. ],
  8473. },
  8474. ],
  8475. });
  8476. const app = createTuiApp({
  8477. runtime,
  8478. terminal,
  8479. version: "0.1.0",
  8480. workspaceDir: "/workspace",
  8481. });
  8482. await app.ready;
  8483. await app.submit("/resume session-existing");
  8484. expect(app.transcript.snapshot()).toEqual(
  8485. expect.arrayContaining([
  8486. expect.objectContaining({ kind: "permission", status: "blocked" }),
  8487. expect.objectContaining({ kind: "question", status: "blocked" }),
  8488. ]),
  8489. );
  8490. expect(app.transcript.get("permission:permission-1")).toMatchObject({
  8491. title: "bash",
  8492. content: "Run tests",
  8493. });
  8494. expect(
  8495. app.transcript.get("permission:permission-1")?.content,
  8496. ).not.toContain("decision panel");
  8497. expect(app.transcript.get("permission:permission-1")?.content).not.toMatch(
  8498. /\/(?:allow|always|deny)\b/u,
  8499. );
  8500. expect(app.transcript.get("question:question-1")?.content).toBe("");
  8501. await app.submit("/q1 1");
  8502. expect(runtime.replyQuestionnaire).not.toHaveBeenCalled();
  8503. expect(app.tui.hasOverlay()).toBe(false);
  8504. expect(app.interaction.isActive()).toBe(true);
  8505. expect(terminal.mouseTracking).toBe(false);
  8506. await app.submit("/allow");
  8507. await app.submit("/q1 1");
  8508. await app.submit("/status");
  8509. expect(runtime.replyPermission).toHaveBeenCalledWith(
  8510. "mavis",
  8511. "permission-1",
  8512. "allowOnce",
  8513. );
  8514. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  8515. "mavis",
  8516. "question-1",
  8517. [
  8518. {
  8519. stepId: "step-1",
  8520. selectedOptionIds: ["yes"],
  8521. selectedOther: false,
  8522. },
  8523. ],
  8524. );
  8525. expect(terminal.mouseTracking).toBe(false);
  8526. expect(app.transcript.get("question:question-1")).toMatchObject({
  8527. status: "resolved",
  8528. title: "Answers sent",
  8529. content: "Proceed? Yes",
  8530. });
  8531. expect(app.interaction.current()).toBeDefined();
  8532. expect(app.tui.render(80).join("\n")).toContain("MCode status");
  8533. expect(app.transcript.snapshot()).not.toEqual(
  8534. expect.arrayContaining([
  8535. expect.objectContaining({
  8536. kind: "inspection",
  8537. inspection: expect.objectContaining({
  8538. visualization: { kind: "status" },
  8539. }),
  8540. }),
  8541. ]),
  8542. );
  8543. });
  8544. it("does not let a stale permission response hide a newer decision surface", async () => {
  8545. const terminal = new FakeTerminal();
  8546. const runtime = createRuntime();
  8547. vi.mocked(runtime.listSessions).mockResolvedValue([
  8548. {
  8549. sessionId: "session-race",
  8550. title: "Decision race",
  8551. workspaceDir: "/workspace",
  8552. },
  8553. ]);
  8554. const firstPermission = {
  8555. requestId: "permission-first",
  8556. sessionId: "session-race",
  8557. agentName: "mavis",
  8558. toolName: "bash",
  8559. reason: "First request",
  8560. allowAlwaysSupported: true,
  8561. };
  8562. const secondPermission = {
  8563. requestId: "permission-second",
  8564. sessionId: "session-race",
  8565. agentName: "mavis",
  8566. toolName: "write_file",
  8567. reason: "Newer request",
  8568. allowAlwaysSupported: false,
  8569. };
  8570. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  8571. firstPermission,
  8572. ]);
  8573. let finishReply: ((value: boolean) => void) | undefined;
  8574. vi.mocked(runtime.replyPermission).mockImplementation(
  8575. async () =>
  8576. await new Promise<boolean>((resolve) => {
  8577. finishReply = resolve;
  8578. }),
  8579. );
  8580. let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  8581. vi.mocked(runtime.watchEvents).mockImplementation(
  8582. async function* watchEvents(signal) {
  8583. const event = await new Promise<TuiRuntimeEvent | undefined>(
  8584. (resolve) => {
  8585. emitEvent = resolve;
  8586. signal.addEventListener("abort", () => resolve(undefined), {
  8587. once: true,
  8588. });
  8589. },
  8590. );
  8591. if (event) yield event;
  8592. await new Promise<void>((resolve) => {
  8593. signal.addEventListener("abort", resolve, { once: true });
  8594. });
  8595. },
  8596. );
  8597. const app = createTuiApp({
  8598. runtime,
  8599. terminal,
  8600. version: "0.1.0",
  8601. workspaceDir: "/workspace",
  8602. });
  8603. app.start();
  8604. await app.ready;
  8605. await app.submit("/resume session-race");
  8606. const resolving = app.submit("/allow");
  8607. await vi.waitFor(() => expect(runtime.replyPermission).toHaveBeenCalled());
  8608. await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
  8609. emitEvent?.(
  8610. runtimeEvent({
  8611. type: "permission.ask",
  8612. timestamp: Date.now(),
  8613. source: "test",
  8614. payload: secondPermission,
  8615. }),
  8616. );
  8617. await vi.waitFor(() =>
  8618. expect(app.tui.render(80).join("\n")).toContain("Newer request"),
  8619. );
  8620. finishReply?.(true);
  8621. await resolving;
  8622. const rendered = app.tui.render(80).join("\n");
  8623. expect(rendered).toContain("Write file");
  8624. expect(rendered).toContain("Newer request");
  8625. expect(runtime.replyPermission).toHaveBeenCalledTimes(1);
  8626. await app.stop();
  8627. });
  8628. it("closes a permission that another surface resolved before the reply arrived", async () => {
  8629. const terminal = new FakeTerminal();
  8630. const runtime = createRuntime();
  8631. const permission = {
  8632. requestId: "permission-stale",
  8633. sessionId: "session-permission-stale",
  8634. agentName: "mavis",
  8635. toolName: "bash",
  8636. reason: "Run tests",
  8637. allowAlwaysSupported: true,
  8638. };
  8639. vi.mocked(runtime.listSessions).mockResolvedValue([
  8640. {
  8641. sessionId: "session-permission-stale",
  8642. title: "Permission race",
  8643. workspaceDir: "/workspace",
  8644. },
  8645. ]);
  8646. vi.mocked(runtime.listPendingPermissions)
  8647. .mockResolvedValueOnce([permission])
  8648. .mockResolvedValue([]);
  8649. vi.mocked(runtime.replyPermission).mockResolvedValue(false);
  8650. const app = createTuiApp({
  8651. runtime,
  8652. terminal,
  8653. version: "0.1.0",
  8654. workspaceDir: "/workspace",
  8655. });
  8656. await app.ready;
  8657. await app.submit("/resume session-permission-stale");
  8658. await app.submit("/allow");
  8659. expect(app.transcript.get("permission:permission-stale")).toMatchObject({
  8660. status: "resolved",
  8661. detail: "Resolved on another surface.",
  8662. });
  8663. expect(app.interaction.isActive()).toBe(false);
  8664. });
  8665. it("keeps an option-only questionnaire pending after an invalid slash answer", async () => {
  8666. const terminal = new FakeTerminal();
  8667. const runtime = createRuntime();
  8668. vi.mocked(runtime.listSessions).mockResolvedValue([
  8669. {
  8670. sessionId: "session-questionnaire",
  8671. title: "Questionnaire session",
  8672. workspaceDir: "/workspace",
  8673. },
  8674. ]);
  8675. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8676. id: "question-options-only",
  8677. title: "Choose",
  8678. steps: [
  8679. {
  8680. id: "channel",
  8681. question: "Choose a release channel",
  8682. selectionMode: "single",
  8683. options: [
  8684. { id: "preview", label: "Preview" },
  8685. { id: "stable", label: "Stable" },
  8686. ],
  8687. allowOther: false,
  8688. },
  8689. ],
  8690. });
  8691. const app = createTuiApp({
  8692. runtime,
  8693. terminal,
  8694. version: "0.1.0",
  8695. workspaceDir: "/workspace",
  8696. });
  8697. await app.ready;
  8698. await app.submit("/resume session-questionnaire");
  8699. await app.submit("/q1 nightly");
  8700. expect(runtime.replyQuestionnaire).not.toHaveBeenCalled();
  8701. expect(app.transcript.get("question:question-options-only")).toMatchObject({
  8702. status: "blocked",
  8703. });
  8704. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  8705. kind: "warning",
  8706. content:
  8707. "/q1 accepts only listed options. Use an option number, ID, or label.",
  8708. });
  8709. await app.submit("/q1 1");
  8710. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  8711. "mavis",
  8712. "question-options-only",
  8713. [
  8714. {
  8715. stepId: "channel",
  8716. selectedOptionIds: ["preview"],
  8717. selectedOther: false,
  8718. },
  8719. ],
  8720. );
  8721. });
  8722. it("shows the first AskUser answer immediately while later questions remain pending", async () => {
  8723. const terminal = new FakeTerminal();
  8724. const runtime = createRuntime();
  8725. vi.mocked(runtime.listSessions).mockResolvedValue([
  8726. {
  8727. sessionId: "session-multi-question",
  8728. title: "Multi question",
  8729. workspaceDir: "/workspace",
  8730. },
  8731. ]);
  8732. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8733. id: "question-multi-step",
  8734. title: "Preferences",
  8735. steps: [
  8736. {
  8737. id: "animal",
  8738. question: "Favorite animal?",
  8739. selectionMode: "single",
  8740. options: [
  8741. { id: "cat", label: "Cat" },
  8742. { id: "dog", label: "Dog" },
  8743. ],
  8744. },
  8745. {
  8746. id: "color",
  8747. question: "Favorite color?",
  8748. selectionMode: "single",
  8749. options: [
  8750. { id: "blue", label: "Blue" },
  8751. { id: "green", label: "Green" },
  8752. ],
  8753. },
  8754. ],
  8755. });
  8756. const app = createTuiApp({
  8757. runtime,
  8758. terminal,
  8759. version: "0.1.0",
  8760. workspaceDir: "/workspace",
  8761. });
  8762. await app.ready;
  8763. app.start();
  8764. await app.submit("/resume session-multi-question");
  8765. const picker = app.interaction.current();
  8766. expect(picker).toBeDefined();
  8767. terminal.input?.("1");
  8768. expect(runtime.replyQuestionnaire).not.toHaveBeenCalled();
  8769. expect(app.interaction.current()).toBe(picker);
  8770. expect(app.transcript.get("question:question-multi-step")).toMatchObject({
  8771. status: "blocked",
  8772. content: "Favorite animal? Cat",
  8773. detail: "1 of 2 answered",
  8774. });
  8775. const rendered = app.tui.render(80).join("\n");
  8776. expect(rendered).toContain("Answers so far");
  8777. expect(rendered).toContain("Favorite animal? Cat");
  8778. expect(rendered).toContain("Favorite color?");
  8779. terminal.input?.("\u001B[B");
  8780. expect(app.tui.render(80).join("\n")).toContain("› 2 Green");
  8781. terminal.input?.("\r");
  8782. await vi.waitFor(() => {
  8783. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  8784. "mavis",
  8785. "question-multi-step",
  8786. [
  8787. {
  8788. stepId: "animal",
  8789. selectedOptionIds: ["cat"],
  8790. selectedOther: false,
  8791. },
  8792. {
  8793. stepId: "color",
  8794. selectedOptionIds: ["green"],
  8795. selectedOther: false,
  8796. },
  8797. ],
  8798. );
  8799. });
  8800. await app.stop();
  8801. });
  8802. it("sends the selected answer immediately and refreshes the Agent continuation", async () => {
  8803. const terminal = new FakeTerminal();
  8804. const runtime = createRuntime();
  8805. vi.mocked(runtime.listSessions).mockResolvedValue([
  8806. {
  8807. sessionId: "session-review",
  8808. title: "Questionnaire review",
  8809. workspaceDir: "/workspace",
  8810. },
  8811. ]);
  8812. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8813. id: "question-review",
  8814. title: "Release setup",
  8815. steps: [
  8816. {
  8817. id: "channel",
  8818. question: "Choose a channel",
  8819. selectionMode: "single",
  8820. options: [
  8821. { id: "preview", label: "Preview" },
  8822. { id: "stable", label: "Stable" },
  8823. ],
  8824. },
  8825. ],
  8826. });
  8827. const previousMessages = [
  8828. {
  8829. id: "previous-question-answer",
  8830. role: "user" as const,
  8831. content: [
  8832. "<questionnaire-response>",
  8833. " <requestId>question-previous</requestId>",
  8834. " <answers />",
  8835. "</questionnaire-response>",
  8836. "",
  8837. "Q: Choose a channel",
  8838. "A: Preview",
  8839. ].join("\n"),
  8840. },
  8841. ];
  8842. vi.mocked(runtime.getMessages).mockResolvedValue(previousMessages);
  8843. const app = createTuiApp({
  8844. runtime,
  8845. terminal,
  8846. version: "0.1.0",
  8847. workspaceDir: "/workspace",
  8848. });
  8849. let releaseReply: ((result: boolean) => void) | undefined;
  8850. let releaseContinuation: (() => void) | undefined;
  8851. vi.mocked(runtime.replyQuestionnaire).mockImplementation(
  8852. async () =>
  8853. await new Promise<boolean>((resolve) => {
  8854. releaseReply = resolve;
  8855. }),
  8856. );
  8857. vi.mocked(runtime.watchEvents).mockImplementation(
  8858. async function* watchEvents(signal) {
  8859. await new Promise<void>((resolve) => {
  8860. releaseContinuation = resolve;
  8861. signal.addEventListener("abort", resolve, { once: true });
  8862. });
  8863. if (signal.aborted) return;
  8864. yield runtimeEvent({
  8865. type: "session.start",
  8866. timestamp: Date.now(),
  8867. source: "runtime",
  8868. payload: {
  8869. sessionId: "session-review",
  8870. turnId: "turn-questionnaire-continuation",
  8871. },
  8872. });
  8873. yield runtimeEvent({
  8874. type: "session.finish",
  8875. timestamp: Date.now(),
  8876. source: "runtime",
  8877. payload: {
  8878. sessionId: "session-review",
  8879. turnId: "turn-questionnaire-continuation",
  8880. },
  8881. });
  8882. },
  8883. );
  8884. app.start();
  8885. await app.ready;
  8886. await app.submit("/resume session-review");
  8887. expect(app.tui.hasOverlay()).toBe(false);
  8888. expect(app.interaction.isActive()).toBe(true);
  8889. terminal.input?.("2");
  8890. await vi.waitFor(() =>
  8891. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  8892. "mavis",
  8893. "question-review",
  8894. [
  8895. {
  8896. stepId: "channel",
  8897. selectedOptionIds: ["stable"],
  8898. selectedOther: false,
  8899. },
  8900. ],
  8901. ),
  8902. );
  8903. expect(app.tui.hasOverlay()).toBe(false);
  8904. expect(app.transcript.get("question:question-review")).toMatchObject({
  8905. status: "pending",
  8906. detail: "Sending your answer…",
  8907. });
  8908. releaseReply?.(true);
  8909. await vi.waitFor(() =>
  8910. expect(app.transcript.get("question:question-review")).toMatchObject({
  8911. status: "resolved",
  8912. detail: "Answer sent · MCode is continuing…",
  8913. }),
  8914. );
  8915. vi.mocked(runtime.getMessages).mockResolvedValue([
  8916. ...previousMessages,
  8917. {
  8918. id: "assistant-after-question",
  8919. role: "assistant",
  8920. content: "Agent continued after your answer.",
  8921. },
  8922. ]);
  8923. releaseContinuation?.();
  8924. await vi.waitFor(() =>
  8925. expect(
  8926. app.transcript
  8927. .snapshot()
  8928. .map((cell) => cell.content)
  8929. .join("\n"),
  8930. ).toContain("Agent continued after your answer."),
  8931. );
  8932. expect(app.transcript.get("question:question-review")).toMatchObject({
  8933. kind: "question",
  8934. status: "resolved",
  8935. title: "Answers sent",
  8936. content: "Choose a channel Stable",
  8937. detail: undefined,
  8938. });
  8939. expect(
  8940. app.transcript
  8941. .snapshot()
  8942. .filter((cell) => cell.kind === "question")
  8943. .map((cell) => cell.content),
  8944. ).toEqual(["Choose a channel Preview", "Choose a channel Stable"]);
  8945. expect(app.tui.render(80).join("\n")).not.toContain("Thinking · Message");
  8946. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
  8947. await app.stop();
  8948. });
  8949. it("redraws after a delayed questionnaire reply resolves", async () => {
  8950. const terminal = new FakeTerminal();
  8951. const runtime = createRuntime();
  8952. vi.mocked(runtime.listSessions).mockResolvedValue([
  8953. {
  8954. sessionId: "session-delayed-reply",
  8955. title: "Delayed questionnaire reply",
  8956. workspaceDir: "/workspace",
  8957. },
  8958. ]);
  8959. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8960. id: "question-delayed-reply",
  8961. steps: [
  8962. {
  8963. id: "channel",
  8964. question: "Choose a channel",
  8965. selectionMode: "single",
  8966. options: [{ id: "preview", label: "Preview" }],
  8967. },
  8968. ],
  8969. });
  8970. let finishReply: ((result: boolean) => void) | undefined;
  8971. vi.mocked(runtime.replyQuestionnaire).mockImplementation(
  8972. async () =>
  8973. await new Promise<boolean>((resolve) => {
  8974. finishReply = resolve;
  8975. }),
  8976. );
  8977. const app = createTuiApp({
  8978. runtime,
  8979. terminal,
  8980. version: "0.1.0",
  8981. workspaceDir: "/workspace",
  8982. });
  8983. app.start();
  8984. await app.ready;
  8985. await app.submit("/resume session-delayed-reply");
  8986. terminal.input?.("1");
  8987. await vi.waitFor(() =>
  8988. expect(runtime.replyQuestionnaire).toHaveBeenCalledTimes(1),
  8989. );
  8990. expect(app.tui.hasOverlay()).toBe(false);
  8991. const writesBeforeResolution = terminal.writes.length;
  8992. finishReply?.(true);
  8993. await vi.waitFor(() =>
  8994. expect(
  8995. app.transcript.get("question:question-delayed-reply"),
  8996. ).toMatchObject({
  8997. status: "resolved",
  8998. detail: "Answer sent · MCode is continuing…",
  8999. }),
  9000. );
  9001. await vi.waitFor(() =>
  9002. expect(terminal.writes.length).toBeGreaterThan(writesBeforeResolution),
  9003. );
  9004. await app.stop();
  9005. });
  9006. it("keeps the questionnaire interactive when the Runtime cannot start its continuation", async () => {
  9007. const terminal = new FakeTerminal();
  9008. const runtime = createRuntime();
  9009. vi.mocked(runtime.listSessions).mockResolvedValue([
  9010. {
  9011. sessionId: "session-retry-questionnaire",
  9012. title: "Retry questionnaire",
  9013. workspaceDir: "/workspace",
  9014. },
  9015. ]);
  9016. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9017. id: "question-retry",
  9018. title: "Choose a channel",
  9019. steps: [
  9020. {
  9021. id: "channel",
  9022. question: "Choose a channel",
  9023. selectionMode: "single",
  9024. options: [{ id: "preview", label: "Preview" }],
  9025. },
  9026. ],
  9027. });
  9028. vi.mocked(runtime.replyQuestionnaire).mockRejectedValue(
  9029. new Error(
  9030. "Questionnaire answer was saved, but the continuation could not start.",
  9031. ),
  9032. );
  9033. const app = createTuiApp({
  9034. runtime,
  9035. terminal,
  9036. version: "0.1.0",
  9037. workspaceDir: "/workspace",
  9038. });
  9039. app.start();
  9040. app.start();
  9041. await app.ready;
  9042. await app.submit("/resume session-retry-questionnaire");
  9043. terminal.input?.("1");
  9044. await vi.waitFor(() =>
  9045. expect(app.transcript.get("question:question-retry")).toMatchObject({
  9046. status: "blocked",
  9047. title: "Choose a channel",
  9048. detail: "Answer could not be sent · retry",
  9049. }),
  9050. );
  9051. expect(app.interaction.isActive()).toBe(true);
  9052. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  9053. kind: "error",
  9054. content:
  9055. "Couldn't send your answers: Questionnaire answer was saved, but the continuation could not start. Retry. The question remains open.",
  9056. });
  9057. await app.stop();
  9058. });
  9059. it("redraws after a delayed questionnaire dismissal resolves", async () => {
  9060. const terminal = new FakeTerminal();
  9061. const runtime = createRuntime();
  9062. vi.mocked(runtime.listSessions).mockResolvedValue([
  9063. {
  9064. sessionId: "session-delayed-dismiss",
  9065. title: "Delayed questionnaire dismissal",
  9066. workspaceDir: "/workspace",
  9067. },
  9068. ]);
  9069. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9070. id: "question-delayed-dismiss",
  9071. steps: [{ id: "confirmation", question: "Continue?" }],
  9072. });
  9073. let finishDismiss: ((result: boolean) => void) | undefined;
  9074. vi.mocked(runtime.dismissQuestionnaire).mockImplementation(
  9075. async () =>
  9076. await new Promise<boolean>((resolve) => {
  9077. finishDismiss = resolve;
  9078. }),
  9079. );
  9080. const app = createTuiApp({
  9081. runtime,
  9082. terminal,
  9083. version: "0.1.0",
  9084. workspaceDir: "/workspace",
  9085. });
  9086. app.start();
  9087. await app.ready;
  9088. await app.submit("/resume session-delayed-dismiss");
  9089. const dismissing = app.submit("/ask-cancel");
  9090. await vi.waitFor(() =>
  9091. expect(runtime.dismissQuestionnaire).toHaveBeenCalledTimes(1),
  9092. );
  9093. const writesBeforeResolution = terminal.writes.length;
  9094. finishDismiss?.(true);
  9095. await dismissing;
  9096. expect(
  9097. app.transcript.get("question:question-delayed-dismiss"),
  9098. ).toMatchObject({
  9099. status: "resolved",
  9100. title: "Question dismissed",
  9101. content: "",
  9102. detail: undefined,
  9103. });
  9104. await vi.waitFor(() =>
  9105. expect(terminal.writes.length).toBeGreaterThan(writesBeforeResolution),
  9106. );
  9107. await app.stop();
  9108. });
  9109. it.each([
  9110. { keyName: "Escape", input: "\x1b" },
  9111. { keyName: "Ctrl-C", input: "\x03" },
  9112. ])(
  9113. "keeps AskUser focused while $keyName dismisses the pending questionnaire",
  9114. async ({ input }) => {
  9115. const terminal = new FakeTerminal();
  9116. const runtime = createRuntime();
  9117. vi.mocked(runtime.listSessions).mockResolvedValue([
  9118. {
  9119. sessionId: "session-escape-dismiss",
  9120. title: "Escape questionnaire dismissal",
  9121. workspaceDir: "/workspace",
  9122. },
  9123. ]);
  9124. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9125. id: "question-escape-dismiss",
  9126. steps: [
  9127. {
  9128. id: "channel",
  9129. question: "Choose a channel",
  9130. selectionMode: "single",
  9131. options: [{ id: "preview", label: "Preview" }],
  9132. },
  9133. ],
  9134. });
  9135. let finishDismiss: ((result: boolean) => void) | undefined;
  9136. vi.mocked(runtime.dismissQuestionnaire).mockImplementation(
  9137. async () =>
  9138. await new Promise<boolean>((resolve) => {
  9139. finishDismiss = resolve;
  9140. }),
  9141. );
  9142. const app = createTuiApp({
  9143. runtime,
  9144. terminal,
  9145. version: "0.1.0",
  9146. workspaceDir: "/workspace",
  9147. });
  9148. app.start();
  9149. await app.ready;
  9150. await app.submit("/resume session-escape-dismiss");
  9151. terminal.input?.(input);
  9152. if (input === "\x1b") {
  9153. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9154. "Cancel this question?",
  9155. );
  9156. terminal.input?.("\r");
  9157. }
  9158. await vi.waitFor(() =>
  9159. expect(runtime.dismissQuestionnaire).toHaveBeenCalledWith(
  9160. "mavis",
  9161. "question-escape-dismiss",
  9162. ),
  9163. );
  9164. expect(app.interaction.isActive()).toBe(true);
  9165. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9166. "Closing question",
  9167. );
  9168. expect(
  9169. app.state.snapshot().sessions.get("session-escape-dismiss")?.attention
  9170. .question,
  9171. ).toBe(true);
  9172. finishDismiss?.(true);
  9173. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  9174. expect(
  9175. app.transcript.get("question:question-escape-dismiss"),
  9176. ).toMatchObject({
  9177. status: "resolved",
  9178. title: "Question dismissed",
  9179. });
  9180. expect(
  9181. app.state.snapshot().sessions.get("session-escape-dismiss")?.attention
  9182. .question,
  9183. ).toBe(false);
  9184. expect(app.tui.render(80).join("\n")).not.toContain("Reply required");
  9185. await app.stop();
  9186. },
  9187. );
  9188. it("denies a pending permission explicitly and releases the blocked interaction", async () => {
  9189. const terminal = new FakeTerminal();
  9190. const runtime = createRuntime();
  9191. vi.mocked(runtime.listSessions).mockResolvedValue([
  9192. {
  9193. sessionId: "session-pending",
  9194. title: "Pending permission",
  9195. workspaceDir: "/workspace",
  9196. },
  9197. ]);
  9198. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  9199. {
  9200. requestId: "permission-pending",
  9201. sessionId: "session-pending",
  9202. agentName: "mavis",
  9203. toolName: "bash",
  9204. toolInput: "pnpm test",
  9205. ruleContents: ["Bash(pnpm test:*)"],
  9206. allowAlwaysSupported: true,
  9207. },
  9208. ]);
  9209. const app = createTuiApp({
  9210. runtime,
  9211. terminal,
  9212. version: "0.1.0",
  9213. workspaceDir: "/workspace",
  9214. });
  9215. app.start();
  9216. await app.ready;
  9217. await app.submit("/resume session-pending");
  9218. expect(app.tui.hasOverlay()).toBe(false);
  9219. expect(app.interaction.isActive()).toBe(true);
  9220. terminal.input?.("3");
  9221. terminal.input?.("\r");
  9222. await vi.waitFor(() =>
  9223. expect(runtime.replyPermission).toHaveBeenCalledWith(
  9224. "mavis",
  9225. "permission-pending",
  9226. "deny",
  9227. ),
  9228. );
  9229. expect(app.tui.hasOverlay()).toBe(false);
  9230. expect(app.interaction.isActive()).toBe(false);
  9231. expect(app.transcript.get("permission:permission-pending")).toMatchObject({
  9232. status: "resolved",
  9233. detail: "Denied · bash",
  9234. });
  9235. expect(app.tui.render(80).join("\n")).not.toContain("Approval required");
  9236. await app.stop();
  9237. });
  9238. it("resolves a regular inline permission without clearing the terminal viewport", async () => {
  9239. const terminal = new FakeTerminal();
  9240. terminal.rows = 8;
  9241. const runtime = createRuntime();
  9242. vi.mocked(runtime.listSessions).mockResolvedValue([
  9243. {
  9244. sessionId: "session-permission-render",
  9245. title: "Permission render",
  9246. workspaceDir: "/workspace",
  9247. },
  9248. ]);
  9249. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  9250. {
  9251. requestId: "permission-render",
  9252. sessionId: "session-permission-render",
  9253. agentName: "mavis",
  9254. toolName: "bash",
  9255. toolInput: "pnpm test",
  9256. reason: "Run focused tests",
  9257. allowAlwaysSupported: true,
  9258. },
  9259. ]);
  9260. const app = createTuiApp({
  9261. runtime,
  9262. terminal,
  9263. version: "0.2.6",
  9264. workspaceDir: "/workspace",
  9265. tuiMode: "regular",
  9266. });
  9267. app.start();
  9268. await app.ready;
  9269. await app.submit("/resume session-permission-render");
  9270. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  9271. app.tui.renderNow();
  9272. terminal.writes.length = 0;
  9273. terminal.input?.("\r");
  9274. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  9275. await vi.waitFor(() => expect(terminal.writes.length).toBeGreaterThan(0));
  9276. expect(runtime.replyPermission).toHaveBeenCalledWith(
  9277. "mavis",
  9278. "permission-render",
  9279. "allowOnce",
  9280. );
  9281. expect(app.transcript.get("permission:permission-render")).toMatchObject({
  9282. status: "resolved",
  9283. detail: "Allowed for this conversation · bash",
  9284. });
  9285. expect(terminal.writes.join("")).not.toContain("\x1b[2J");
  9286. expect(terminal.writes.join("")).not.toContain("\x1b[3J");
  9287. await app.stop();
  9288. });
  9289. it("keeps a submission retryable when a pending decision blocks admission", async () => {
  9290. const terminal = new FakeTerminal();
  9291. const runtime = createRuntime();
  9292. vi.mocked(runtime.listSessions).mockResolvedValue([
  9293. {
  9294. sessionId: "session-draft-blocked",
  9295. title: "Pending decision",
  9296. workspaceDir: "/workspace",
  9297. },
  9298. ]);
  9299. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  9300. {
  9301. requestId: "permission-draft-blocked",
  9302. sessionId: "session-draft-blocked",
  9303. agentName: "mavis",
  9304. toolName: "bash",
  9305. allowAlwaysSupported: true,
  9306. },
  9307. ]);
  9308. const app = createTuiApp({
  9309. runtime,
  9310. terminal,
  9311. version: "0.1.0",
  9312. workspaceDir: "/workspace",
  9313. });
  9314. app.start();
  9315. await app.ready;
  9316. await app.submit("/resume session-draft-blocked");
  9317. app.editor.setText("Keep this draft for later");
  9318. app.editor.handleInput("\r");
  9319. await vi.waitFor(() => expect(app.editor.getText()).toBe(""));
  9320. expect(runtime.sendMessage).not.toHaveBeenCalled();
  9321. expect(app.tui.render(80).join("\n")).toContain("Approval required");
  9322. expect(app.tui.render(80).join("\n")).not.toContain("Message · Enter");
  9323. await app.stop();
  9324. });
  9325. it("keeps a pending questionnaire when Runtime rejects dismissal", async () => {
  9326. const terminal = new FakeTerminal();
  9327. const runtime = createRuntime();
  9328. vi.mocked(runtime.listSessions).mockResolvedValue([
  9329. {
  9330. sessionId: "session-existing",
  9331. title: "Existing session",
  9332. workspaceDir: "/workspace",
  9333. },
  9334. ]);
  9335. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9336. id: "question-rejected",
  9337. steps: [{ id: "step-1", question: "Proceed?" }],
  9338. });
  9339. vi.mocked(runtime.dismissQuestionnaire).mockResolvedValue(false);
  9340. const app = createTuiApp({
  9341. runtime,
  9342. terminal,
  9343. version: "0.1.0",
  9344. workspaceDir: "/workspace",
  9345. });
  9346. await app.ready;
  9347. await app.submit("/resume session-existing");
  9348. await app.submit("/ask-cancel");
  9349. expect(app.transcript.get("question:question-rejected")).toMatchObject({
  9350. status: "blocked",
  9351. });
  9352. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  9353. kind: "error",
  9354. content: "Couldn't dismiss this question. It remains open; retry.",
  9355. });
  9356. });
  9357. it("restores the questionnaire panel when an Escape dismissal request fails", async () => {
  9358. const runtime = createRuntime();
  9359. vi.mocked(runtime.listSessions).mockResolvedValue([
  9360. {
  9361. sessionId: "session-dismiss-retry",
  9362. title: "Dismiss retry",
  9363. workspaceDir: "/workspace",
  9364. },
  9365. ]);
  9366. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9367. id: "question-dismiss-retry",
  9368. steps: [
  9369. {
  9370. id: "step-1",
  9371. question: "Proceed?",
  9372. selectionMode: "single",
  9373. options: [{ id: "yes", label: "Yes" }],
  9374. },
  9375. ],
  9376. });
  9377. vi.mocked(runtime.dismissQuestionnaire).mockRejectedValue(
  9378. new Error("connection lost"),
  9379. );
  9380. const app = createTuiApp({
  9381. runtime,
  9382. terminal: new FakeTerminal(),
  9383. version: "0.1.0",
  9384. workspaceDir: "/workspace",
  9385. });
  9386. await app.ready;
  9387. await app.submit("/resume session-dismiss-retry");
  9388. app.interaction.current()?.handleInput("\u001b");
  9389. app.interaction.current()?.handleInput("\r");
  9390. await vi.waitFor(() =>
  9391. expect(runtime.dismissQuestionnaire).toHaveBeenCalledOnce(),
  9392. );
  9393. await vi.waitFor(() => {
  9394. const panel = app.interaction.current();
  9395. expect(panel).toBeDefined();
  9396. expect(panel?.render(80).join("\n")).toContain("Ask");
  9397. });
  9398. expect(app.transcript.get("question:question-dismiss-retry")).toMatchObject(
  9399. {
  9400. status: "blocked",
  9401. },
  9402. );
  9403. });
  9404. it("settles a questionnaire dismissal that already reached a terminal Runtime state", async () => {
  9405. const terminal = new FakeTerminal();
  9406. const runtime = createRuntime();
  9407. vi.mocked(runtime.listSessions).mockResolvedValue([
  9408. {
  9409. sessionId: "session-terminal-dismiss",
  9410. title: "Terminal dismissal",
  9411. workspaceDir: "/workspace",
  9412. },
  9413. ]);
  9414. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9415. id: "question-terminal-dismiss",
  9416. steps: [{ id: "step-1", question: "Proceed?" }],
  9417. });
  9418. vi.mocked(runtime.dismissQuestionnaire).mockRejectedValue(
  9419. Object.assign(new Error("already superseded"), {
  9420. status: 410,
  9421. code: "QUESTIONNAIRE_NOT_PENDING",
  9422. }),
  9423. );
  9424. const app = createTuiApp({
  9425. runtime,
  9426. terminal,
  9427. version: "0.1.0",
  9428. workspaceDir: "/workspace",
  9429. });
  9430. await app.ready;
  9431. await app.submit("/resume session-terminal-dismiss");
  9432. await app.submit("/ask-cancel");
  9433. expect(
  9434. app.transcript.get("question:question-terminal-dismiss"),
  9435. ).toMatchObject({
  9436. status: "resolved",
  9437. title: "Question closed",
  9438. detail: "Question is no longer pending.",
  9439. });
  9440. expect(app.interaction.isActive()).toBe(false);
  9441. });
  9442. it("projects live Desktop permission events into the transcript", async () => {
  9443. const terminal = new FakeTerminal();
  9444. const runtime = createRuntime();
  9445. vi.mocked(runtime.watchEvents).mockImplementation(
  9446. async function* watchEvents() {
  9447. yield runtimeEvent({
  9448. type: "permission.ask",
  9449. timestamp: 100,
  9450. source: "runtime",
  9451. payload: {
  9452. requestId: "permission-live",
  9453. sessionId: "session-1",
  9454. agentName: "mavis",
  9455. toolName: "bash",
  9456. toolDescription: "Run a shell command",
  9457. reason: "Run checks",
  9458. ruleContents: ["Bash(pnpm test:*)"],
  9459. allowAlwaysSupported: true,
  9460. },
  9461. });
  9462. },
  9463. );
  9464. const app = createTuiApp({
  9465. runtime,
  9466. terminal,
  9467. version: "0.1.0",
  9468. workspaceDir: "/workspace",
  9469. });
  9470. await app.ready;
  9471. await app.submit("Start the current session");
  9472. await app.submit("/transcript");
  9473. expect(app.surfaceHost.getActiveSurface()).toEqual({
  9474. kind: "feature",
  9475. id: "transcript",
  9476. });
  9477. app.start();
  9478. await vi.waitFor(() =>
  9479. expect(app.transcript.get("permission:permission-live")).toMatchObject({
  9480. kind: "permission",
  9481. status: "blocked",
  9482. content: expect.stringContaining("Run checks"),
  9483. }),
  9484. );
  9485. expect(app.transcript.get("permission:permission-live")).toMatchObject({
  9486. title: "bash",
  9487. content: "Run checks",
  9488. });
  9489. expect(
  9490. app.transcript.get("permission:permission-live")?.content,
  9491. ).not.toContain("Rules:");
  9492. expect(app.surfaceHost.getActiveSurface()).toEqual({
  9493. kind: "chat",
  9494. id: "chat",
  9495. });
  9496. await app.submit("/allow");
  9497. expect(app.surfaceHost.getActiveSurface()).toEqual({
  9498. kind: "feature",
  9499. id: "transcript",
  9500. });
  9501. await app.stop();
  9502. });
  9503. it("ignores Desktop interaction events until their session is active", async () => {
  9504. const terminal = new FakeTerminal();
  9505. const runtime = createRuntime();
  9506. let resolveEventsDelivered: (() => void) | undefined;
  9507. const eventsDelivered = new Promise<void>((resolve) => {
  9508. resolveEventsDelivered = resolve;
  9509. });
  9510. vi.mocked(runtime.watchEvents).mockImplementation(
  9511. async function* watchEvents(signal) {
  9512. yield runtimeEvent({
  9513. type: "permission.ask",
  9514. timestamp: 100,
  9515. source: "runtime",
  9516. payload: {
  9517. requestId: "permission-other-session",
  9518. sessionId: "session-other",
  9519. agentName: "mavis",
  9520. toolName: "bash",
  9521. },
  9522. });
  9523. yield runtimeEvent({
  9524. type: "questionnaire.ask",
  9525. timestamp: 101,
  9526. source: "runtime",
  9527. payload: {
  9528. sessionId: "session-other",
  9529. agentName: "mavis",
  9530. request: {
  9531. id: "question-other-session",
  9532. steps: [
  9533. { id: "step-1", question: "Proceed?", selectionMode: "single" },
  9534. ],
  9535. },
  9536. },
  9537. });
  9538. resolveEventsDelivered?.();
  9539. await new Promise<void>((resolve) => {
  9540. signal.addEventListener("abort", () => resolve(), { once: true });
  9541. });
  9542. },
  9543. );
  9544. const app = createTuiApp({
  9545. runtime,
  9546. terminal,
  9547. version: "0.1.0",
  9548. workspaceDir: "/workspace",
  9549. });
  9550. app.start();
  9551. await app.ready;
  9552. await eventsDelivered;
  9553. expect(
  9554. app.transcript.get("permission:permission-other-session"),
  9555. ).toBeUndefined();
  9556. expect(
  9557. app.transcript.get("question:question-other-session"),
  9558. ).toBeUndefined();
  9559. expect(
  9560. app.state.snapshot().sessions.get("session-other")?.interactions
  9561. .permission?.requestId,
  9562. ).toBe("permission-other-session");
  9563. expect(
  9564. app.state.snapshot().sessions.get("session-other")?.interactions
  9565. .questionnaire?.request.id,
  9566. ).toBe("question-other-session");
  9567. await app.stop();
  9568. });
  9569. it("surfaces only descendant permissions while keeping explicit Deny separate from Stop", async () => {
  9570. const terminal = new FakeTerminal();
  9571. const runtime = createRuntime();
  9572. const rootSession = {
  9573. sessionId: "session-root",
  9574. title: "Root session",
  9575. workspaceDir: "/workspace",
  9576. status: "started",
  9577. };
  9578. vi.mocked(runtime.listSessions).mockResolvedValue([rootSession]);
  9579. vi.mocked(runtime.getSession).mockResolvedValue(rootSession);
  9580. vi.mocked(runtime.getDelegationSnapshot).mockResolvedValue({
  9581. schemaVersion: 1,
  9582. rootSessionId: "session-root",
  9583. members: [
  9584. {
  9585. sessionId: "session-child",
  9586. parentSessionId: "session-root",
  9587. agentName: "worker",
  9588. task: "Delegate nested work",
  9589. status: "running",
  9590. },
  9591. {
  9592. sessionId: "session-grandchild",
  9593. parentSessionId: "session-child",
  9594. agentName: "verifier",
  9595. task: "Verify the result",
  9596. status: "running",
  9597. },
  9598. ],
  9599. });
  9600. vi.mocked(runtime.getActiveRun).mockImplementation(
  9601. async (sessionId: string) => ({
  9602. schemaVersion: 1,
  9603. sessionId,
  9604. state:
  9605. sessionId === rootSession.sessionId ? "decision-blocked" : "running",
  9606. turnId:
  9607. sessionId === rootSession.sessionId
  9608. ? "turn-root"
  9609. : `turn-${sessionId}`,
  9610. actions: { steer: false },
  9611. }),
  9612. );
  9613. const deniedPermissionIds = new Set<string>();
  9614. vi.mocked(runtime.replyPermission).mockImplementation(
  9615. async (_agentName, requestId) => {
  9616. deniedPermissionIds.add(requestId);
  9617. return true;
  9618. },
  9619. );
  9620. vi.mocked(runtime.listPendingPermissions).mockImplementation(async () =>
  9621. deniedPermissionIds.has("permission-grandchild")
  9622. ? [
  9623. {
  9624. requestId: "permission-unrelated-next",
  9625. sessionId: "session-unrelated",
  9626. agentName: "worker",
  9627. toolName: "bash",
  9628. reason: "Must remain hidden",
  9629. },
  9630. {
  9631. requestId: deniedPermissionIds.has("permission-child-next")
  9632. ? "permission-child-stop"
  9633. : "permission-child-next",
  9634. sessionId: "session-child",
  9635. agentName: "worker",
  9636. toolName: "read",
  9637. reason: deniedPermissionIds.has("permission-child-next")
  9638. ? "Wait for an explicit Stop"
  9639. : "Inspect the delegated output",
  9640. },
  9641. ]
  9642. : [],
  9643. );
  9644. vi.mocked(runtime.watchEvents).mockImplementation(
  9645. async function* watchEvents(signal) {
  9646. yield runtimeEvent({
  9647. type: "permission.ask",
  9648. timestamp: 100,
  9649. source: "runtime",
  9650. payload: {
  9651. requestId: "permission-unrelated",
  9652. sessionId: "session-unrelated",
  9653. agentName: "worker",
  9654. toolName: "bash",
  9655. reason: "Must stay hidden",
  9656. },
  9657. });
  9658. yield runtimeEvent({
  9659. type: "permission.ask",
  9660. timestamp: 101,
  9661. source: "runtime",
  9662. payload: {
  9663. requestId: "permission-grandchild",
  9664. sessionId: "session-grandchild",
  9665. agentName: "verifier",
  9666. toolName: "write",
  9667. reason: "Update the verification report",
  9668. allowAlwaysSupported: true,
  9669. },
  9670. });
  9671. await new Promise<void>((resolve) => {
  9672. signal.addEventListener("abort", resolve, { once: true });
  9673. });
  9674. },
  9675. );
  9676. const app = createTuiApp({
  9677. runtime,
  9678. terminal,
  9679. version: "0.1.0",
  9680. workspaceDir: "/workspace",
  9681. });
  9682. await app.ready;
  9683. await app.submit("/resume session-root");
  9684. vi.mocked(runtime.abortSession).mockClear();
  9685. vi.mocked(runtime.stopDelegation).mockClear();
  9686. app.start();
  9687. await vi.waitFor(() =>
  9688. expect(
  9689. app.transcript.get("permission:permission-grandchild"),
  9690. ).toMatchObject({
  9691. kind: "permission",
  9692. status: "blocked",
  9693. }),
  9694. );
  9695. expect(
  9696. app.transcript.get("permission:permission-unrelated"),
  9697. ).toBeUndefined();
  9698. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9699. "Update the verification report",
  9700. );
  9701. app.interaction.current()?.handleInput?.("3");
  9702. app.interaction.current()?.handleInput?.("\r");
  9703. await vi.waitFor(() =>
  9704. expect(runtime.replyPermission).toHaveBeenCalledWith(
  9705. "verifier",
  9706. "permission-grandchild",
  9707. "deny",
  9708. ),
  9709. );
  9710. expect(runtime.stopDelegation).not.toHaveBeenCalled();
  9711. expect(runtime.abortSession).not.toHaveBeenCalled();
  9712. await vi.waitFor(() =>
  9713. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9714. "Inspect the delegated output",
  9715. ),
  9716. );
  9717. expect(
  9718. app.transcript.get("permission:permission-unrelated-next"),
  9719. ).toBeUndefined();
  9720. terminal.input?.("\x1b");
  9721. await vi.waitFor(() =>
  9722. expect(runtime.replyPermission).toHaveBeenCalledWith(
  9723. "worker",
  9724. "permission-child-next",
  9725. "deny",
  9726. ),
  9727. );
  9728. expect(runtime.abortSession).not.toHaveBeenCalled();
  9729. expect(runtime.stopDelegation).not.toHaveBeenCalled();
  9730. await vi.waitFor(() =>
  9731. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9732. "Wait for an explicit Stop",
  9733. ),
  9734. );
  9735. terminal.input?.("\x03");
  9736. await vi.waitFor(() =>
  9737. expect(runtime.abortSession).toHaveBeenCalledWith({
  9738. id: rootSession.sessionId,
  9739. turnId: "turn-root",
  9740. reason: "user_stop",
  9741. }),
  9742. );
  9743. expect(runtime.stopDelegation).toHaveBeenCalledOnce();
  9744. expect(runtime.stopDelegation).toHaveBeenCalledWith(rootSession.sessionId);
  9745. expect(runtime.replyPermission).not.toHaveBeenCalledWith(
  9746. "worker",
  9747. "permission-child-stop",
  9748. "deny",
  9749. );
  9750. await app.stop();
  9751. });
  9752. it("recovers a descendant permission from the Runtime pending list without leaking unrelated requests", async () => {
  9753. const runtime = createRuntime();
  9754. const rootSession = {
  9755. sessionId: "session-recovery-root",
  9756. title: "Recovery root",
  9757. workspaceDir: "/workspace",
  9758. };
  9759. vi.mocked(runtime.listSessions).mockResolvedValue([rootSession]);
  9760. vi.mocked(runtime.getSession).mockResolvedValue(rootSession);
  9761. vi.mocked(runtime.getDelegationSnapshot).mockResolvedValue({
  9762. schemaVersion: 1,
  9763. rootSessionId: rootSession.sessionId,
  9764. members: [
  9765. {
  9766. sessionId: "session-recovery-child",
  9767. parentSessionId: rootSession.sessionId,
  9768. agentName: "worker",
  9769. task: "Resume delegated work",
  9770. status: "running",
  9771. },
  9772. ],
  9773. });
  9774. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  9775. {
  9776. requestId: "permission-recovery-unrelated",
  9777. sessionId: "session-other-root",
  9778. agentName: "worker",
  9779. toolName: "bash",
  9780. reason: "Do not show this request",
  9781. },
  9782. {
  9783. requestId: "permission-recovery-child",
  9784. sessionId: "session-recovery-child",
  9785. agentName: "worker",
  9786. toolName: "write",
  9787. reason: "Resume the child request",
  9788. },
  9789. ]);
  9790. const app = createTuiApp({
  9791. runtime,
  9792. terminal: new FakeTerminal(),
  9793. version: "0.1.0",
  9794. workspaceDir: "/workspace",
  9795. });
  9796. await app.ready;
  9797. await app.submit("/resume session-recovery-root");
  9798. expect(
  9799. app.transcript.get("permission:permission-recovery-child"),
  9800. ).toMatchObject({
  9801. kind: "permission",
  9802. status: "blocked",
  9803. });
  9804. expect(
  9805. app.transcript.get("permission:permission-recovery-unrelated"),
  9806. ).toBeUndefined();
  9807. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9808. "Resume the child request",
  9809. );
  9810. await app.stop();
  9811. });
  9812. it("reconnects the Runtime event stream after a transient disconnect", async () => {
  9813. const terminal = new FakeTerminal();
  9814. const runtime = createRuntime();
  9815. const observability = createObservability();
  9816. let attempt = 0;
  9817. vi.mocked(runtime.watchEvents).mockImplementation(
  9818. async function* watchEvents() {
  9819. attempt += 1;
  9820. if (attempt === 1) throw new Error("connection reset");
  9821. yield runtimeEvent({
  9822. type: "permission.ask",
  9823. timestamp: 101,
  9824. source: "runtime",
  9825. payload: {
  9826. requestId: "permission-after-reconnect",
  9827. sessionId: "session-1",
  9828. toolName: "read",
  9829. },
  9830. });
  9831. },
  9832. );
  9833. const app = createTuiApp({
  9834. runtime,
  9835. terminal,
  9836. version: "0.1.0",
  9837. workspaceDir: "/workspace",
  9838. observability,
  9839. });
  9840. await app.ready;
  9841. await app.submit("Start the current session");
  9842. app.start();
  9843. await vi.waitFor(
  9844. () =>
  9845. expect(
  9846. app.transcript.get("permission:permission-after-reconnect"),
  9847. ).toMatchObject({
  9848. status: "blocked",
  9849. }),
  9850. { timeout: 1500 },
  9851. );
  9852. expect(runtime.watchEvents).toHaveBeenCalledTimes(2);
  9853. expect(observability.recordEventStream).toHaveBeenCalledWith(
  9854. expect.objectContaining({
  9855. state: "retry-scheduled",
  9856. attempt: 1,
  9857. retryDelayMs: 250,
  9858. errorKind: "Error",
  9859. }),
  9860. );
  9861. expect(observability.recordEventStream).toHaveBeenCalledWith(
  9862. expect.objectContaining({
  9863. state: "reconnected",
  9864. attempt: 1,
  9865. downtimeMs: expect.any(Number),
  9866. }),
  9867. );
  9868. expect(app.transcript.snapshot()).not.toEqual(
  9869. expect.arrayContaining([
  9870. expect.objectContaining({
  9871. kind: "warning",
  9872. content: expect.stringContaining("Runtime event stream"),
  9873. }),
  9874. ]),
  9875. );
  9876. await app.stop();
  9877. });
  9878. it("sends pasted local attachments and restores failed sends to the Composer", async () => {
  9879. const terminal = new FakeTerminal();
  9880. const runtime = createRuntime();
  9881. const readClipboardImage = vi.fn(async () => ({
  9882. attachment: {
  9883. type: "image" as const,
  9884. filePath: "/tmp/minimax-code-clipboard/diagram.png",
  9885. fileName: "diagram.png",
  9886. mimeType: "image/png",
  9887. sizeBytes: 2048,
  9888. },
  9889. dispose: vi.fn(async () => undefined),
  9890. }));
  9891. const app = createTuiApp({
  9892. runtime,
  9893. terminal,
  9894. version: "0.1.0",
  9895. workspaceDir: "/workspace",
  9896. readClipboardImage,
  9897. readClipboardText: async () => null,
  9898. });
  9899. app.start();
  9900. await app.ready;
  9901. terminal.input?.("\u001bv");
  9902. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(1));
  9903. await app.submit("Inspect the diagram");
  9904. expect(runtime.sendMessage).toHaveBeenCalledWith(
  9905. expect.objectContaining({
  9906. id: "session-1",
  9907. content: "Inspect the diagram",
  9908. attachments: [
  9909. expect.objectContaining({
  9910. local: { filePath: "/tmp/minimax-code-clipboard/diagram.png" },
  9911. meta: expect.objectContaining({ mimeType: "image/png" }),
  9912. }),
  9913. ],
  9914. }),
  9915. expect.any(AbortSignal),
  9916. );
  9917. expect(app.tui.render(80).join("\n")).not.toContain("[Image #1]");
  9918. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  9919. async function* sendMessage() {
  9920. yield { type: "error", message: "provider unavailable" };
  9921. },
  9922. );
  9923. terminal.input?.("\x16");
  9924. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(2));
  9925. app.editor.setText("Try again");
  9926. app.editor.handleInput("\r");
  9927. await vi.waitFor(() => expect(app.editor.getText()).toContain("Try again"));
  9928. expect(app.tui.render(80).join("\n")).toContain(
  9929. "Error The model provider is temporarily unavailable.",
  9930. );
  9931. expect(app.tui.render(80).join("\n")).not.toContain("Request failed");
  9932. expect(app.editor.getText()).toContain("[Image #1]");
  9933. expect(app.tui.render(80).join("\n")).not.toContain(
  9934. "Message kept under Failed",
  9935. );
  9936. await app.submit("/retry");
  9937. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  9938. expect.objectContaining({
  9939. content: "Try again",
  9940. attachments: [
  9941. expect.objectContaining({
  9942. local: { filePath: "/tmp/minimax-code-clipboard/diagram.png" },
  9943. }),
  9944. ],
  9945. }),
  9946. expect.any(AbortSignal),
  9947. );
  9948. await app.submit("A fresh turn");
  9949. expect(app.tui.render(80).join("\n")).not.toContain("Couldn't send");
  9950. await app.stop();
  9951. });
  9952. it.each([
  9953. ['content', 'Content review withdrew this response. Rephrase your request, then retry.'],
  9954. ['network', 'Content review did not return a usable result, so this response stopped.'],
  9955. ] as const)("presents a %s review stop without a failed Queue item", async (variant, notice) => {
  9956. const terminal = new FakeTerminal();
  9957. const runtime = createRuntime();
  9958. const busEvents: TuiRuntimeEvent[] = [];
  9959. let wakeBus: (() => void) | undefined;
  9960. vi.mocked(runtime.watchEvents).mockImplementation(
  9961. async function* watchEvents(signal) {
  9962. while (!signal.aborted) {
  9963. if (busEvents.length === 0) {
  9964. await new Promise<void>((resolve) => {
  9965. wakeBus = resolve;
  9966. signal.addEventListener("abort", resolve, { once: true });
  9967. });
  9968. }
  9969. const event = busEvents.shift();
  9970. if (event) yield event;
  9971. }
  9972. },
  9973. );
  9974. let releaseTurn: (() => void) | undefined;
  9975. vi.mocked(runtime.sendMessage).mockImplementation(
  9976. async function* sendMessage() {
  9977. await new Promise<void>((resolve) => {
  9978. releaseTurn = resolve;
  9979. });
  9980. yield { type: "done" };
  9981. },
  9982. );
  9983. const app = createTuiApp({
  9984. runtime,
  9985. terminal,
  9986. version: "0.1.0",
  9987. workspaceDir: "/workspace",
  9988. });
  9989. app.start();
  9990. await app.ready;
  9991. terminal.input?.("review this response");
  9992. terminal.input?.("\r");
  9993. await vi.waitFor(() =>
  9994. expect(app.controller.snapshot().activeTurnId).toBeTruthy(),
  9995. );
  9996. busEvents.push(
  9997. runtimeEvent({
  9998. type: "content.retry.exceeded",
  9999. timestamp: 100,
  10000. source: "runtime-v2",
  10001. payload: { sessionId: "session-1", variant },
  10002. }),
  10003. runtimeEvent({
  10004. type: "message.rewind",
  10005. timestamp: 101,
  10006. source: "runtime-v2",
  10007. payload: { sessionId: "session-1", contextReset: true },
  10008. }),
  10009. );
  10010. wakeBus?.();
  10011. releaseTurn?.();
  10012. await vi.waitFor(() =>
  10013. expect(app.editor.getText()).toBe("review this response"),
  10014. );
  10015. const rendered = app.tui.render(100).join("\n");
  10016. expect(rendered).toContain(notice);
  10017. expect(rendered).not.toContain('Check your network');
  10018. expect(rendered).not.toContain("Message kept under Failed");
  10019. await app.submit("/queue");
  10020. expect(app.interaction.current()).toBeUndefined();
  10021. await app.stop();
  10022. });
  10023. it("sends editable @directory/ input as ordinary text", async () => {
  10024. const terminal = new FakeTerminal();
  10025. const runtime = createRuntime();
  10026. const app = createTuiApp({
  10027. runtime,
  10028. terminal,
  10029. version: "0.1.0",
  10030. workspaceDir: "/workspace",
  10031. });
  10032. await app.submit("Review @src/");
  10033. expect(runtime.sendMessage).toHaveBeenCalledWith(
  10034. { id: "session-1", content: "Review @src/", turnId: expect.any(String) },
  10035. expect.any(AbortSignal),
  10036. );
  10037. await expect(app.submit("Review @generated/")).resolves.toBeUndefined();
  10038. expect(runtime.sendMessage).toHaveBeenCalledTimes(2);
  10039. });
  10040. it("pastes a clipboard image without replacing the text draft and cleans it after send", async () => {
  10041. const terminal = new FakeTerminal();
  10042. const runtime = createRuntime();
  10043. const dispose = vi.fn(async () => undefined);
  10044. const readClipboardImage = vi.fn(async () => ({
  10045. attachment: {
  10046. type: "image" as const,
  10047. filePath: "/tmp/minimax-code-clipboard/clipboard-1.png",
  10048. fileName: "clipboard-1.png",
  10049. mimeType: "image/png",
  10050. sizeBytes: 4096,
  10051. },
  10052. dispose,
  10053. }));
  10054. const app = createTuiApp({
  10055. runtime,
  10056. terminal,
  10057. version: "0.1.0",
  10058. workspaceDir: "/workspace",
  10059. readClipboardImage,
  10060. readClipboardText: async () => null,
  10061. });
  10062. app.start();
  10063. await app.ready;
  10064. app.editor.setText("Keep this draft");
  10065. terminal.input?.("\u001B[118;9u");
  10066. terminal.input?.("\u001B[118;9:3u");
  10067. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledOnce());
  10068. await vi.waitFor(() =>
  10069. expect(app.editor.getText()).toContain("[Image #1]"),
  10070. );
  10071. expect(app.editor.getText()).toBe("Keep this draft [Image #1] ");
  10072. expect(app.tui.render(100).join("\n")).not.toContain(
  10073. "A clipboard media paste is already in progress.",
  10074. );
  10075. await app.submit("Keep this draft");
  10076. expect(runtime.sendMessage).toHaveBeenCalledWith(
  10077. expect.objectContaining({
  10078. id: "session-1",
  10079. content: "Keep this draft",
  10080. attachments: [
  10081. expect.objectContaining({
  10082. local: { filePath: "/tmp/minimax-code-clipboard/clipboard-1.png" },
  10083. meta: expect.objectContaining({ mimeType: "image/png" }),
  10084. }),
  10085. ],
  10086. }),
  10087. expect.any(AbortSignal),
  10088. );
  10089. expect(dispose).toHaveBeenCalledOnce();
  10090. await app.stop();
  10091. });
  10092. it("retains existing draft state when clipboard read or send fails", async () => {
  10093. const terminal = new FakeTerminal();
  10094. const runtime = createRuntime();
  10095. const dispose = vi.fn(async () => undefined);
  10096. const readClipboardImage = vi
  10097. .fn()
  10098. .mockResolvedValueOnce({
  10099. attachment: {
  10100. type: "image" as const,
  10101. filePath: "/tmp/minimax-code-clipboard/clipboard-2.png",
  10102. fileName: "clipboard-2.png",
  10103. mimeType: "image/png",
  10104. sizeBytes: 1024,
  10105. },
  10106. dispose,
  10107. })
  10108. .mockRejectedValueOnce(new Error("clipboard has no image"));
  10109. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  10110. async function* sendMessage() {
  10111. yield { type: "error", message: "provider unavailable" };
  10112. },
  10113. );
  10114. const app = createTuiApp({
  10115. runtime,
  10116. terminal,
  10117. version: "0.1.0",
  10118. workspaceDir: "/workspace",
  10119. readClipboardImage,
  10120. readClipboardText: async () => null,
  10121. });
  10122. app.start();
  10123. await app.ready;
  10124. app.editor.setText("Do not clear me");
  10125. terminal.input?.("\x16");
  10126. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(1));
  10127. terminal.input?.("\x16");
  10128. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(2));
  10129. expect(app.editor.getText()).toBe("Do not clear me [Image #1] ");
  10130. await app.submit("Try the image");
  10131. expect(dispose).not.toHaveBeenCalled();
  10132. expect(app.tui.render(80).join("\n")).toContain("[Image #1]");
  10133. terminal.input?.("\x7f");
  10134. expect(app.tui.render(80).join("\n")).not.toContain("[Image #1]");
  10135. expect(dispose).not.toHaveBeenCalled();
  10136. await app.stop();
  10137. expect(dispose).toHaveBeenCalledOnce();
  10138. });
  10139. it("cancels an in-flight clipboard read with Ctrl+C and keeps the draft", async () => {
  10140. const terminal = new FakeTerminal();
  10141. const runtime = createRuntime();
  10142. let observedSignal: AbortSignal | undefined;
  10143. const readClipboardImage = vi.fn(
  10144. async (signal?: AbortSignal) =>
  10145. await new Promise<never>((_resolve, reject) => {
  10146. observedSignal = signal;
  10147. signal?.addEventListener(
  10148. "abort",
  10149. () => reject(new Error("cancelled")),
  10150. { once: true },
  10151. );
  10152. }),
  10153. );
  10154. const app = createTuiApp({
  10155. runtime,
  10156. terminal,
  10157. version: "0.1.0",
  10158. workspaceDir: "/workspace",
  10159. readClipboardImage,
  10160. readClipboardText: async () => null,
  10161. });
  10162. app.start();
  10163. await app.ready;
  10164. app.editor.setText("Draft survives");
  10165. terminal.input?.("\x16");
  10166. await vi.waitFor(() => expect(observedSignal).toBeDefined());
  10167. terminal.input?.("\x03");
  10168. await vi.waitFor(() => expect(observedSignal?.aborted).toBe(true));
  10169. expect(app.editor.getText()).toBe("Draft survives");
  10170. await app.stop();
  10171. });
  10172. it("keeps queued clipboard files alive until the Runtime reports a terminal queue state", async () => {
  10173. const terminal = new FakeTerminal();
  10174. const runtime = createRuntime();
  10175. const dispose = vi.fn(async () => undefined);
  10176. let finishTurn: (() => void) | undefined;
  10177. let deliverQueueEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  10178. vi.mocked(runtime.sendMessage).mockImplementation(
  10179. async function* sendMessage() {
  10180. await new Promise<void>((resolve) => {
  10181. finishTurn = resolve;
  10182. });
  10183. yield { type: "done" };
  10184. },
  10185. );
  10186. vi.mocked(runtime.watchEvents).mockImplementation(
  10187. async function* watchEvents() {
  10188. const event = await new Promise<TuiRuntimeEvent>((resolve) => {
  10189. deliverQueueEvent = resolve;
  10190. });
  10191. yield event;
  10192. },
  10193. );
  10194. const readClipboardImage = vi.fn(async () => ({
  10195. attachment: {
  10196. type: "image" as const,
  10197. filePath: "/tmp/minimax-code-clipboard/clipboard-queue.png",
  10198. fileName: "clipboard-queue.png",
  10199. mimeType: "image/png",
  10200. sizeBytes: 2048,
  10201. },
  10202. dispose,
  10203. }));
  10204. const app = createTuiApp({
  10205. runtime,
  10206. terminal,
  10207. version: "0.1.0",
  10208. workspaceDir: "/workspace",
  10209. productFeatures: { queue: true },
  10210. readClipboardImage,
  10211. });
  10212. app.start();
  10213. await app.ready;
  10214. const first = app.submit("First turn");
  10215. await vi.waitFor(() =>
  10216. expect(app.controller.snapshot().status).toBe("running"),
  10217. );
  10218. terminal.input?.("\x16");
  10219. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledOnce());
  10220. await app.submit("Queued with image");
  10221. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  10222. "session-1",
  10223. "Queued with image",
  10224. expect.objectContaining({
  10225. attachments: [
  10226. expect.objectContaining({ fileName: "clipboard-queue.png" }),
  10227. ],
  10228. }),
  10229. );
  10230. expect(dispose).not.toHaveBeenCalled();
  10231. deliverQueueEvent?.(
  10232. runtimeEvent({
  10233. type: "session.queue.updated",
  10234. timestamp: Date.now(),
  10235. source: "runtime",
  10236. payload: {
  10237. sessionId: "session-1",
  10238. itemId: "queue-1",
  10239. status: "completed",
  10240. queuedCount: 0,
  10241. },
  10242. }),
  10243. );
  10244. await vi.waitFor(() => expect(dispose).toHaveBeenCalledOnce());
  10245. finishTurn?.();
  10246. await first;
  10247. await app.stop();
  10248. });
  10249. it("opens the Desktop model picker and applies the selected session model", async () => {
  10250. const terminal = new FakeTerminal();
  10251. const runtime = createRuntime();
  10252. vi.mocked(runtime.listModels).mockResolvedValue([
  10253. {
  10254. providerId: "minimax",
  10255. modelId: "MiniMax-M3",
  10256. displayName: "MiniMax M3",
  10257. variant: "thinking",
  10258. thinkingConfig: { mode: "switchable", defaultValue: "true" },
  10259. providerKind: "minimax-managed",
  10260. selected: true,
  10261. },
  10262. ]);
  10263. const app = createTuiApp({
  10264. runtime,
  10265. terminal,
  10266. version: "0.1.0",
  10267. workspaceDir: "/workspace",
  10268. });
  10269. app.start();
  10270. await app.ready;
  10271. await app.submit("Create a session");
  10272. await app.submit("/model");
  10273. expect(app.tui.hasOverlay()).toBe(false);
  10274. expect(app.interaction.isActive()).toBe(true);
  10275. terminal.input?.("\x1b");
  10276. expect(app.tui.hasOverlay()).toBe(false);
  10277. await app.submit("/model");
  10278. terminal.input?.("\r");
  10279. await vi.waitFor(() =>
  10280. expect(runtime.selectModel).toHaveBeenCalledWith(
  10281. expect.objectContaining({
  10282. providerId: "minimax",
  10283. modelId: "MiniMax-M3",
  10284. variant: "thinking",
  10285. }),
  10286. "session-1",
  10287. ),
  10288. );
  10289. await vi.waitFor(() => {
  10290. const rendered = app.tui.render(120).join("\n");
  10291. expect(rendered).toContain("✦ MiniMax M3");
  10292. expect(rendered).toContain("Thinking On");
  10293. expect(rendered).not.toContain("MiniMax M3#thinking");
  10294. });
  10295. await app.stop();
  10296. });
  10297. it("queues a thinking-on model with the configured effort even when the Session stored none", async () => {
  10298. const terminal = new FakeTerminal();
  10299. const runtime = createRuntime();
  10300. let finishTurn: (() => void) | undefined;
  10301. vi.mocked(runtime.listModels).mockResolvedValue([
  10302. {
  10303. providerId: "minimax",
  10304. modelId: "deep-reasoner-1",
  10305. displayName: "deep-reasoner-1",
  10306. selected: true,
  10307. variant: "thinking",
  10308. thinkingConfig: { mode: "switchable", defaultValue: "true" },
  10309. effortOptions: ["xhigh"],
  10310. },
  10311. ]);
  10312. vi.mocked(runtime.sendMessage).mockImplementation(
  10313. async function* sendMessage() {
  10314. await new Promise<void>((resolve) => {
  10315. finishTurn = resolve;
  10316. });
  10317. yield { type: "done" };
  10318. },
  10319. );
  10320. const app = createTuiApp({
  10321. runtime,
  10322. terminal,
  10323. version: "0.1.0",
  10324. workspaceDir: "/workspace",
  10325. productFeatures: { queue: true },
  10326. });
  10327. app.start();
  10328. await app.ready;
  10329. const first = app.submit("First turn");
  10330. await vi.waitFor(() =>
  10331. expect(app.controller.snapshot().status).toBe("running"),
  10332. );
  10333. await app.submit("Queued turn");
  10334. // The Session echo carries no stored effort, so the per-Turn selection has to
  10335. // resolve the configured level. Sending only `variant: thinking` makes Runtime
  10336. // drop the effort and the provider apply its own default.
  10337. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  10338. "session-1",
  10339. "Queued turn",
  10340. expect.objectContaining({
  10341. model: expect.objectContaining({
  10342. providerId: "minimax",
  10343. modelId: "deep-reasoner-1",
  10344. variant: "thinking",
  10345. thinking: { effort: "xhigh" },
  10346. }),
  10347. }),
  10348. );
  10349. finishTurn?.();
  10350. await first;
  10351. await app.stop();
  10352. });
  10353. it("applies a welcome-screen effort to the new Session before sending its first message", async () => {
  10354. const terminal = new FakeTerminal();
  10355. const runtime = createRuntime();
  10356. vi.mocked(runtime.listModels).mockResolvedValue([
  10357. {
  10358. providerId: "custom_provider:byok",
  10359. modelId: "byok-large-5",
  10360. displayName: "BYOK Large 5",
  10361. selected: true,
  10362. variant: "",
  10363. thinkingConfig: { mode: "switchable", defaultValue: "false" },
  10364. effortOptions: ["low", "medium", "high"],
  10365. },
  10366. ]);
  10367. let releaseDefaultSelection: ((selected: boolean) => void) | undefined;
  10368. let releaseSessionSelection: ((selected: boolean) => void) | undefined;
  10369. vi.mocked(runtime.selectModel)
  10370. .mockImplementationOnce(
  10371. async () =>
  10372. await new Promise<boolean>((resolve) => {
  10373. releaseDefaultSelection = resolve;
  10374. }),
  10375. )
  10376. .mockImplementationOnce(
  10377. async () =>
  10378. await new Promise<boolean>((resolve) => {
  10379. releaseSessionSelection = resolve;
  10380. }),
  10381. );
  10382. const app = createTuiApp({
  10383. runtime,
  10384. terminal,
  10385. version: "0.1.0",
  10386. workspaceDir: "/workspace",
  10387. });
  10388. app.start();
  10389. await app.ready;
  10390. await app.submit("/model");
  10391. terminal.input?.("\u001b[C");
  10392. terminal.input?.("\r");
  10393. const firstTurn = app.submit("First turn");
  10394. await vi.waitFor(() =>
  10395. expect(runtime.selectModel).toHaveBeenNthCalledWith(
  10396. 1,
  10397. expect.objectContaining({ thinking: { effort: "high" }, variant: "" }),
  10398. undefined,
  10399. ),
  10400. );
  10401. expect(runtime.selectModel).toHaveBeenCalledOnce();
  10402. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10403. releaseDefaultSelection?.(true);
  10404. await vi.waitFor(() =>
  10405. expect(runtime.selectModel).toHaveBeenNthCalledWith(
  10406. 2,
  10407. expect.objectContaining({ thinking: { effort: "high" }, variant: "" }),
  10408. "session-1",
  10409. ),
  10410. );
  10411. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10412. releaseSessionSelection?.(true);
  10413. await firstTurn;
  10414. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  10415. expect(runtime.selectModel.mock.invocationCallOrder[1]).toBeLessThan(
  10416. runtime.sendMessage.mock.invocationCallOrder[0] ??
  10417. Number.POSITIVE_INFINITY,
  10418. );
  10419. await app.stop();
  10420. });
  10421. it("does not send the first message when Runtime rejects its pending effort", async () => {
  10422. const terminal = new FakeTerminal();
  10423. const runtime = createRuntime();
  10424. vi.mocked(runtime.listModels).mockResolvedValue([
  10425. {
  10426. providerId: "custom_provider:byok",
  10427. modelId: "byok-large-5",
  10428. displayName: "BYOK Large 5",
  10429. selected: true,
  10430. effortOptions: ["low", "medium", "high"],
  10431. },
  10432. ]);
  10433. vi.mocked(runtime.selectModel)
  10434. .mockResolvedValueOnce(true)
  10435. .mockResolvedValueOnce(false);
  10436. const app = createTuiApp({
  10437. runtime,
  10438. terminal,
  10439. version: "0.1.0",
  10440. workspaceDir: "/workspace",
  10441. });
  10442. app.start();
  10443. await app.ready;
  10444. await app.submit("/model");
  10445. terminal.input?.("\r");
  10446. await vi.waitFor(() => expect(runtime.selectModel).toHaveBeenCalledOnce());
  10447. await app.submit("First turn");
  10448. expect(runtime.selectModel).toHaveBeenCalledTimes(2);
  10449. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10450. await app.stop();
  10451. });
  10452. it("lets Escape cancel the first turn while Desktop is creating its session", async () => {
  10453. const terminal = new FakeTerminal();
  10454. const runtime = createRuntime();
  10455. let finishSessionCreation:
  10456. | ((session: { sessionId: string; workspaceDir: string }) => void)
  10457. | undefined;
  10458. vi.mocked(runtime.createSession).mockImplementation(
  10459. async () =>
  10460. await new Promise<{ sessionId: string; workspaceDir: string }>(
  10461. (resolve) => {
  10462. finishSessionCreation = resolve;
  10463. },
  10464. ),
  10465. );
  10466. const app = createTuiApp({
  10467. runtime,
  10468. terminal,
  10469. version: "0.1.0",
  10470. workspaceDir: "/workspace",
  10471. });
  10472. app.start();
  10473. await app.ready;
  10474. const submitting = app.submit("Wait for the session");
  10475. await vi.waitFor(() =>
  10476. expect(app.controller.snapshot()).toMatchObject({
  10477. status: "starting",
  10478. activeTurnId: expect.any(String),
  10479. }),
  10480. );
  10481. expect(app.tui.render(80).join("\n")).toContain("Loading");
  10482. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  10483. expect(app.tui.render(80).join("\n")).not.toContain("MCode ·");
  10484. terminal.input?.("\x1b");
  10485. await vi.waitFor(() =>
  10486. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  10487. );
  10488. finishSessionCreation?.({
  10489. sessionId: "session-created",
  10490. workspaceDir: "/workspace",
  10491. });
  10492. await submitting;
  10493. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10494. expect(app.transcript.snapshot()).toEqual(
  10495. expect.arrayContaining([
  10496. expect.objectContaining({ kind: "assistant", status: "cancelled" }),
  10497. ]),
  10498. );
  10499. await app.stop();
  10500. });
  10501. it("restores a submission attempted while the previous cancellation fence is active", async () => {
  10502. const terminal = new FakeTerminal();
  10503. const runtime = createRuntime();
  10504. let releaseCancelledStream: (() => void) | undefined;
  10505. let sendCount = 0;
  10506. vi.mocked(runtime.sendMessage).mockImplementation(
  10507. async function* sendMessage(_req: SendMessageReq, signal?: AbortSignal) {
  10508. sendCount += 1;
  10509. if (sendCount === 1) {
  10510. await new Promise<void>((resolve) => {
  10511. signal?.addEventListener("abort", resolve, { once: true });
  10512. });
  10513. await new Promise<void>((resolve) => {
  10514. releaseCancelledStream = resolve;
  10515. });
  10516. } else {
  10517. yield { type: "delta", content: "Second response" };
  10518. }
  10519. yield { type: "done" };
  10520. },
  10521. );
  10522. vi.mocked(runtime.abortSession).mockImplementation(async () => {
  10523. setTimeout(() => releaseCancelledStream?.(), 10);
  10524. return true;
  10525. });
  10526. const app = createTuiApp({
  10527. runtime,
  10528. terminal,
  10529. version: "0.1.0",
  10530. workspaceDir: "/workspace",
  10531. });
  10532. app.start();
  10533. await app.ready;
  10534. terminal.input?.("First request");
  10535. terminal.input?.("\r");
  10536. await vi.waitFor(() =>
  10537. expect(app.controller.snapshot().status).toBe("running"),
  10538. );
  10539. terminal.input?.("\x1b");
  10540. await vi.waitFor(() =>
  10541. expect(app.controller.snapshot().cancelling).toBe(true),
  10542. );
  10543. terminal.input?.("Second request");
  10544. terminal.input?.("\r");
  10545. await vi.waitFor(() => expect(app.editor.getText()).toBe("Second request"));
  10546. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  10547. await vi.waitFor(() =>
  10548. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  10549. );
  10550. await vi.waitFor(() =>
  10551. expect(app.controller.snapshot().retiringTurnId).toBeUndefined(),
  10552. );
  10553. expect(app.controller.snapshot().cancelling).toBe(false);
  10554. expect(app.tui.render(80).join("\n")).not.toContain(
  10555. "Stopping the current response",
  10556. );
  10557. app.editor.handleInput("\r");
  10558. await vi.waitFor(() =>
  10559. expect(runtime.sendMessage).toHaveBeenCalledTimes(2),
  10560. );
  10561. expect(runtime.sendMessage).toHaveBeenCalledTimes(2);
  10562. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  10563. expect(app.transcript.snapshot()).toEqual(
  10564. expect.arrayContaining([
  10565. expect.objectContaining({ kind: "assistant", status: "cancelled" }),
  10566. ]),
  10567. );
  10568. await app.stop();
  10569. });
  10570. it("restores a failed submission before text typed while cancellation is retiring", async () => {
  10571. const terminal = new FakeTerminal();
  10572. const runtime = createRuntime();
  10573. let releaseRuntimeOwnership: (() => void) | undefined;
  10574. const runtimeOwnershipReleased = new Promise<void>((resolve) => {
  10575. releaseRuntimeOwnership = resolve;
  10576. });
  10577. vi.mocked(runtime.sendMessage).mockImplementation(
  10578. async function* sendMessage(_req: SendMessageReq, signal?: AbortSignal) {
  10579. await new Promise<void>((resolve) => {
  10580. signal?.addEventListener("abort", resolve, { once: true });
  10581. });
  10582. await runtimeOwnershipReleased;
  10583. yield { type: "done" };
  10584. },
  10585. );
  10586. const app = createTuiApp({
  10587. runtime,
  10588. terminal,
  10589. version: "0.1.0",
  10590. workspaceDir: "/workspace",
  10591. });
  10592. app.start();
  10593. await app.ready;
  10594. terminal.input?.("First request");
  10595. terminal.input?.("\r");
  10596. await vi.waitFor(() =>
  10597. expect(app.controller.snapshot().status).toBe("running"),
  10598. );
  10599. terminal.input?.("\x1b");
  10600. await vi.waitFor(
  10601. () => expect(app.controller.snapshot().retiringTurnId).toBeTruthy(),
  10602. {
  10603. timeout: 2_000,
  10604. },
  10605. );
  10606. expect(app.controller.snapshot()).toMatchObject({
  10607. status: "idle",
  10608. activeTurnId: undefined,
  10609. cancelling: false,
  10610. });
  10611. terminal.input?.("Second request");
  10612. terminal.input?.("\r");
  10613. terminal.input?.("extra detail");
  10614. await vi.waitFor(() => expect(app.editor.getText()).toBe("extra detail"));
  10615. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  10616. await vi.waitFor(() =>
  10617. expect(app.tui.render(160).join("\n")).toContain("Second request"),
  10618. );
  10619. expect(app.editor.getText()).toBe("Second request\nextra detail");
  10620. releaseRuntimeOwnership?.();
  10621. await vi.waitFor(() =>
  10622. expect(app.controller.snapshot().retiringTurnId).toBeUndefined(),
  10623. );
  10624. expect(app.tui.render(160).join("\n")).not.toContain(
  10625. "Runtime is still stopping; your draft is preserved",
  10626. );
  10627. await app.stop();
  10628. });
  10629. it("aborts session creation when the TUI stops during its first turn", async () => {
  10630. const terminal = new FakeTerminal();
  10631. const runtime = createRuntime();
  10632. let finishSessionCreation:
  10633. | ((session: { sessionId: string; workspaceDir: string }) => void)
  10634. | undefined;
  10635. vi.mocked(runtime.createSession).mockImplementation(
  10636. async () =>
  10637. await new Promise<{ sessionId: string; workspaceDir: string }>(
  10638. (resolve) => {
  10639. finishSessionCreation = resolve;
  10640. },
  10641. ),
  10642. );
  10643. const app = createTuiApp({
  10644. runtime,
  10645. terminal,
  10646. version: "0.1.0",
  10647. workspaceDir: "/workspace",
  10648. });
  10649. app.start();
  10650. await app.ready;
  10651. const submitting = app.submit("Wait for the session");
  10652. await vi.waitFor(() =>
  10653. expect(app.controller.snapshot().activeTurnId).toEqual(
  10654. expect.any(String),
  10655. ),
  10656. );
  10657. const stopping = app.stop();
  10658. finishSessionCreation?.({
  10659. sessionId: "session-created",
  10660. workspaceDir: "/workspace",
  10661. });
  10662. await Promise.all([submitting, stopping]);
  10663. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10664. expect(app.transcript.snapshot()).toEqual(
  10665. expect.arrayContaining([
  10666. expect.objectContaining({ kind: "assistant", status: "cancelled" }),
  10667. ]),
  10668. );
  10669. expect(terminal.stopped).toBe(true);
  10670. });
  10671. it.each(["minimax", "custom_provider:work"])(
  10672. "hydrates the Runtime-selected startup model for %s",
  10673. async (providerId) => {
  10674. const runtime = createRuntime();
  10675. vi.mocked(runtime.listModels).mockResolvedValue([
  10676. { providerId, modelId: "MiniMax-M3", selected: true },
  10677. ]);
  10678. const app = createTuiApp({
  10679. runtime,
  10680. terminal: new FakeTerminal(),
  10681. version: "0.1.0",
  10682. workspaceDir: "/workspace",
  10683. });
  10684. try {
  10685. await app.ready;
  10686. expect(runtime.listModels).toHaveBeenCalled();
  10687. expect(runtime.selectModel).not.toHaveBeenCalled();
  10688. await app.submit("/model");
  10689. expect(runtime.selectModel).not.toHaveBeenCalled();
  10690. } finally {
  10691. await app.stop();
  10692. }
  10693. },
  10694. );
  10695. it("offers provider onboarding when Desktop has no models", async () => {
  10696. const terminal = new FakeTerminal();
  10697. const runtime = createRuntime();
  10698. vi.mocked(runtime.listModels).mockResolvedValue([]);
  10699. const app = createTuiApp({
  10700. runtime,
  10701. terminal,
  10702. version: "0.1.0",
  10703. workspaceDir: "/workspace",
  10704. });
  10705. await app.ready;
  10706. await app.submit("/model unavailable");
  10707. expect(app.tui.hasOverlay()).toBe(false);
  10708. expect(app.interaction.isActive()).toBe(true);
  10709. const rendered = app.tui.render(120).join("\n");
  10710. expect(rendered).toContain("No matching models");
  10711. expect(rendered).toContain("Add 3rd-party provider");
  10712. terminal.input?.("\x1b");
  10713. await app.stop();
  10714. });
  10715. it("keeps the TUI usable when the Runtime model catalog fails to load", async () => {
  10716. const terminal = new FakeTerminal();
  10717. const runtime = createRuntime();
  10718. vi.mocked(runtime.listModels).mockRejectedValue(
  10719. new Error("catalog unavailable"),
  10720. );
  10721. const app = createTuiApp({
  10722. runtime,
  10723. terminal,
  10724. version: "0.1.0",
  10725. workspaceDir: "/workspace",
  10726. });
  10727. await app.ready;
  10728. await expect(app.submit("/model")).resolves.toBeUndefined();
  10729. expect(app.tui.hasOverlay()).toBe(false);
  10730. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  10731. kind: "warning",
  10732. content: "Couldn't load models: catalog unavailable. Retry /model.",
  10733. });
  10734. });
  10735. it("shows a follow-up as queued while Runtime admission is pending", async () => {
  10736. const terminal = new FakeTerminal();
  10737. const runtime = createRuntime();
  10738. let finishFirstTurn: (() => void) | undefined;
  10739. let finishEnqueue: (() => void) | undefined;
  10740. let admitted = false;
  10741. vi.mocked(runtime.sendMessage).mockImplementation(
  10742. async function* sendMessage() {
  10743. await new Promise<void>((resolve) => {
  10744. finishFirstTurn = resolve;
  10745. });
  10746. yield { type: "done" };
  10747. },
  10748. );
  10749. vi.mocked(runtime.enqueueMessage).mockImplementation(async () => {
  10750. await new Promise<void>((resolve) => {
  10751. finishEnqueue = resolve;
  10752. });
  10753. admitted = true;
  10754. return { itemId: "queue-pending-1", status: "queued", position: 1 };
  10755. });
  10756. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () =>
  10757. admitted
  10758. ? [
  10759. {
  10760. itemId: "queue-pending-1",
  10761. sessionId: "session-1",
  10762. status: "queued",
  10763. content: "Second turn",
  10764. },
  10765. ]
  10766. : [],
  10767. );
  10768. const app = createTuiApp({
  10769. runtime,
  10770. terminal,
  10771. version: "0.1.0",
  10772. workspaceDir: "/workspace",
  10773. });
  10774. app.start();
  10775. await app.ready;
  10776. const first = app.submit("First turn");
  10777. await vi.waitFor(() =>
  10778. expect(app.controller.snapshot().activeTurnId).toEqual(
  10779. expect.any(String),
  10780. ),
  10781. );
  10782. terminal.input?.("Second turn");
  10783. terminal.input?.("\x1b\r");
  10784. await vi.waitFor(() =>
  10785. expect(runtime.enqueueMessage).toHaveBeenCalledOnce(),
  10786. );
  10787. try {
  10788. expect(
  10789. app.transcript
  10790. .snapshot()
  10791. .find((cell) => cell.content.includes("Second turn")),
  10792. ).toBeUndefined();
  10793. const rendered = app.tui.render(100).join("\n");
  10794. expect(rendered).not.toContain("Adding to Queue");
  10795. expect(rendered).toContain("Next · after current response");
  10796. expect(rendered).toContain("Second turn");
  10797. finishEnqueue?.();
  10798. await vi.waitFor(() => {
  10799. const confirmed = app.tui.render(100).join("\n");
  10800. expect(confirmed).not.toContain("Adding to Queue");
  10801. expect(confirmed).toContain("Next · after current response");
  10802. expect(confirmed).toContain("Second turn");
  10803. });
  10804. } finally {
  10805. finishEnqueue?.();
  10806. finishFirstTurn?.();
  10807. await first;
  10808. await app.stop();
  10809. }
  10810. });
  10811. it("removes the local Queue admission and restores the Draft when Runtime rejects it", async () => {
  10812. const terminal = new FakeTerminal();
  10813. const runtime = createRuntime();
  10814. let finishFirstTurn: (() => void) | undefined;
  10815. let rejectEnqueue: ((error: Error) => void) | undefined;
  10816. vi.mocked(runtime.sendMessage).mockImplementation(
  10817. async function* sendMessage() {
  10818. await new Promise<void>((resolve) => {
  10819. finishFirstTurn = resolve;
  10820. });
  10821. yield { type: "done" };
  10822. },
  10823. );
  10824. vi.mocked(runtime.enqueueMessage).mockImplementation(
  10825. async () =>
  10826. await new Promise<never>((_resolve, reject) => {
  10827. rejectEnqueue = reject;
  10828. }),
  10829. );
  10830. const app = createTuiApp({
  10831. runtime,
  10832. terminal,
  10833. version: "0.1.0",
  10834. workspaceDir: "/workspace",
  10835. });
  10836. app.start();
  10837. await app.ready;
  10838. const first = app.submit("First turn");
  10839. await vi.waitFor(() =>
  10840. expect(app.controller.snapshot().activeTurnId).toEqual(
  10841. expect.any(String),
  10842. ),
  10843. );
  10844. terminal.input?.("Keep this Draft");
  10845. terminal.input?.("\x1b\r");
  10846. await vi.waitFor(() =>
  10847. expect(app.tui.render(100).join("\n")).toContain(
  10848. "Next · after current response",
  10849. ),
  10850. );
  10851. await vi.waitFor(() =>
  10852. expect(runtime.enqueueMessage).toHaveBeenCalledOnce(),
  10853. );
  10854. rejectEnqueue?.(new Error("queue unavailable"));
  10855. await vi.waitFor(() =>
  10856. expect(app.editor.getText()).toBe("Keep this Draft"),
  10857. );
  10858. const rendered = app.tui.render(100).join("\n");
  10859. expect(rendered).not.toContain("Next · after current response");
  10860. expect(rendered).toContain("Couldn't add this message to the Queue");
  10861. finishFirstTurn?.();
  10862. await first;
  10863. await app.stop();
  10864. });
  10865. it("shows every rapid follow-up as queued while Runtime admissions are serialized", async () => {
  10866. const terminal = new FakeTerminal();
  10867. const runtime = createRuntime();
  10868. let finishFirstTurn: (() => void) | undefined;
  10869. const releaseAdmissions: Array<() => void> = [];
  10870. const queued: TuiQueuedMessage[] = [];
  10871. vi.mocked(runtime.sendMessage).mockImplementation(
  10872. async function* sendMessage() {
  10873. await new Promise<void>((resolve) => {
  10874. finishFirstTurn = resolve;
  10875. });
  10876. yield { type: "done" };
  10877. },
  10878. );
  10879. vi.mocked(runtime.enqueueMessage).mockImplementation(
  10880. async (sessionId, content) => {
  10881. await new Promise<void>((resolve) => releaseAdmissions.push(resolve));
  10882. const item = {
  10883. itemId: `queue-rapid-${String(queued.length + 1)}`,
  10884. sessionId,
  10885. status: "queued",
  10886. content,
  10887. } satisfies TuiQueuedMessage;
  10888. queued.push(item);
  10889. return {
  10890. itemId: item.itemId,
  10891. status: item.status,
  10892. position: queued.length,
  10893. };
  10894. },
  10895. );
  10896. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  10897. ...queued,
  10898. ]);
  10899. const app = createTuiApp({
  10900. runtime,
  10901. terminal,
  10902. version: "0.1.0",
  10903. workspaceDir: "/workspace",
  10904. });
  10905. app.start();
  10906. await app.ready;
  10907. const first = app.submit("First turn");
  10908. await vi.waitFor(() =>
  10909. expect(app.controller.snapshot().activeTurnId).toEqual(
  10910. expect.any(String),
  10911. ),
  10912. );
  10913. terminal.input?.("Second turn");
  10914. terminal.input?.("\x1b\r");
  10915. terminal.input?.("Third turn");
  10916. terminal.input?.("\x1b\r");
  10917. await vi.waitFor(() => {
  10918. const rendered = app.tui.render(100).join("\n");
  10919. expect(rendered).not.toContain("Adding");
  10920. expect(rendered).toContain("Queue · 2 next");
  10921. expect(rendered).toContain("Second turn");
  10922. expect(rendered).toContain("Third turn");
  10923. });
  10924. expect(
  10925. app.transcript
  10926. .snapshot()
  10927. .filter(
  10928. (cell) =>
  10929. cell.content.includes("Second turn") ||
  10930. cell.content.includes("Third turn"),
  10931. ),
  10932. ).toEqual([]);
  10933. await vi.waitFor(() =>
  10934. expect(runtime.enqueueMessage).toHaveBeenCalledOnce(),
  10935. );
  10936. releaseAdmissions[0]?.();
  10937. await vi.waitFor(() =>
  10938. expect(runtime.enqueueMessage).toHaveBeenCalledTimes(2),
  10939. );
  10940. const partiallyConfirmed = app.tui.render(100).join("\n");
  10941. expect(partiallyConfirmed).toContain("Queue · 2 next");
  10942. expect(partiallyConfirmed.indexOf("Second turn")).toBeLessThan(
  10943. partiallyConfirmed.indexOf("Third turn"),
  10944. );
  10945. releaseAdmissions[1]?.();
  10946. await vi.waitFor(() =>
  10947. expect(app.tui.render(100).join("\n")).toContain("Queue · 2 next"),
  10948. );
  10949. finishFirstTurn?.();
  10950. await first;
  10951. await app.stop();
  10952. });
  10953. it("submits follow-ups to the runtime-owned queue and never drains them in the CLI", async () => {
  10954. const terminal = new FakeTerminal();
  10955. const runtime = createRuntime();
  10956. let finishFirstTurn: (() => void) | undefined;
  10957. vi.mocked(runtime.sendMessage).mockImplementation(
  10958. async function* sendMessage(req: SendMessageReq) {
  10959. const content = req.content ?? "";
  10960. if (content === "First turn") {
  10961. await new Promise<void>((resolve) => {
  10962. finishFirstTurn = resolve;
  10963. });
  10964. }
  10965. yield { type: "delta", content: `Reply to ${content || "attachment"}` };
  10966. yield { type: "done" };
  10967. },
  10968. );
  10969. const attachment = {
  10970. type: "file" as const,
  10971. filePath: "/workspace/notes.md",
  10972. fileName: "notes.md",
  10973. mimeType: "text/markdown",
  10974. sizeBytes: 32,
  10975. };
  10976. const queued: Array<{
  10977. itemId: string;
  10978. sessionId: string;
  10979. status: string;
  10980. content: string;
  10981. }> = [];
  10982. vi.mocked(runtime.enqueueMessage).mockImplementation(
  10983. async (sessionId, content) => {
  10984. const item = {
  10985. itemId: `queue-${queued.length + 1}`,
  10986. sessionId,
  10987. status: "queued",
  10988. content,
  10989. };
  10990. queued.push(item);
  10991. return {
  10992. itemId: item.itemId,
  10993. status: item.status,
  10994. position: queued.length,
  10995. };
  10996. },
  10997. );
  10998. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  10999. ...queued,
  11000. ]);
  11001. vi.mocked(runtime.deleteQueuedMessage).mockImplementation(
  11002. async (_sessionId, itemId) => {
  11003. const index = queued.findIndex((item) => item.itemId === itemId);
  11004. if (index < 0) return undefined;
  11005. return queued.splice(index, 1)[0];
  11006. },
  11007. );
  11008. const readClipboardImage = vi.fn(async () => ({
  11009. attachment,
  11010. dispose: vi.fn(async () => undefined),
  11011. }));
  11012. const app = createTuiApp({
  11013. runtime,
  11014. terminal,
  11015. version: "0.1.0",
  11016. workspaceDir: "/workspace",
  11017. readClipboardImage,
  11018. });
  11019. app.start();
  11020. await app.ready;
  11021. const first = app.submit("First turn");
  11022. await vi.waitFor(() =>
  11023. expect(app.controller.snapshot().activeTurnId).toEqual(
  11024. expect.any(String),
  11025. ),
  11026. );
  11027. terminal.input?.("\x16");
  11028. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledOnce());
  11029. await app.submit("Second turn");
  11030. await app.submit("Third turn");
  11031. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  11032. expect(runtime.enqueueMessage).toHaveBeenNthCalledWith(
  11033. 1,
  11034. "session-1",
  11035. "Second turn",
  11036. {
  11037. attachments: [attachment],
  11038. model: { providerId: "minimax", modelId: "MiniMax-M2.7" },
  11039. },
  11040. );
  11041. expect(runtime.enqueueMessage).toHaveBeenNthCalledWith(
  11042. 2,
  11043. "session-1",
  11044. "Third turn",
  11045. {
  11046. attachments: [],
  11047. model: { providerId: "minimax", modelId: "MiniMax-M2.7" },
  11048. },
  11049. );
  11050. expect(app.transcript.get("queue:queue-1")).toBeUndefined();
  11051. expect(app.transcript.get("queue:queue-2")).toBeUndefined();
  11052. const queuedUi = app.tui.render(80).join("\n");
  11053. expect(queuedUi).toContain("Queue · 2 next");
  11054. expect(queuedUi).toContain("after current response");
  11055. expect(queuedUi).toContain("Second turn");
  11056. expect(queuedUi).toContain("Third turn");
  11057. expect(queuedUi).toContain("/queue manage");
  11058. await app.submit("/queue");
  11059. expect(app.interaction.render(80).join("\n")).toContain("Queue");
  11060. expect(app.interaction.render(80).join("\n")).toContain("2 next");
  11061. expect(app.interaction.render(80).join("\n")).toContain("› 2. Third turn");
  11062. expect(app.editor.getText()).toBe("");
  11063. terminal.input?.("d");
  11064. expect(app.interaction.render(80).join("\n")).toContain(
  11065. "Remove this next message?",
  11066. );
  11067. terminal.input?.("\r");
  11068. await vi.waitFor(() =>
  11069. expect(runtime.deleteQueuedMessage).toHaveBeenCalledWith(
  11070. "session-1",
  11071. "queue-2",
  11072. ),
  11073. );
  11074. await vi.waitFor(() =>
  11075. expect(app.tui.render(80).join("\n")).not.toContain("Third turn"),
  11076. );
  11077. expect(app.tui.render(80).join("\n")).toContain("Second turn");
  11078. terminal.input?.("\x1b");
  11079. finishFirstTurn?.();
  11080. await first;
  11081. expect(
  11082. vi.mocked(runtime.sendMessage).mock.calls.map((call) => call[0].content),
  11083. ).toEqual(["First turn"]);
  11084. expect(app.tui.render(80).join("\n")).toContain(
  11085. "Next · after current response",
  11086. );
  11087. expect(app.tui.render(80).join("\n")).toContain("Second turn");
  11088. expect(app.tui.render(80).join("\n")).not.toContain("Sending next");
  11089. await app.stop();
  11090. });
  11091. it("uses the Runtime queue when a resumed started session is active before queue/model hydration finishes", async () => {
  11092. const terminal = new FakeTerminal();
  11093. const runtime = createRuntime();
  11094. let releaseQueue: ((items: TuiQueuedMessage[]) => void) | undefined;
  11095. const slowQueue = new Promise<TuiQueuedMessage[]>((resolve) => {
  11096. releaseQueue = resolve;
  11097. });
  11098. let releaseModels: ((models: TuiModel[]) => void) | undefined;
  11099. const slowModels = new Promise<TuiModel[]>((resolve) => {
  11100. releaseModels = resolve;
  11101. });
  11102. const session = {
  11103. sessionId: "session-running",
  11104. title: "Running session",
  11105. workspaceDir: "/workspace",
  11106. status: "started",
  11107. };
  11108. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11109. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11110. vi.mocked(runtime.getActiveRun).mockResolvedValue({
  11111. schemaVersion: 1,
  11112. sessionId: "session-running",
  11113. state: "running",
  11114. turnId: "turn-running",
  11115. actions: { steer: true },
  11116. });
  11117. vi.mocked(runtime.listQueuedMessages).mockImplementation(
  11118. async () => slowQueue,
  11119. );
  11120. vi.mocked(runtime.listModels).mockImplementation(async (sessionId) =>
  11121. sessionId ? slowModels : [],
  11122. );
  11123. vi.mocked(runtime.enqueueMessage).mockResolvedValue({
  11124. itemId: "queue-running-1",
  11125. status: "queued",
  11126. position: 1,
  11127. });
  11128. const app = createTuiApp({
  11129. runtime,
  11130. terminal,
  11131. version: "0.1.0",
  11132. workspaceDir: "/workspace",
  11133. productFeatures: { queue: true },
  11134. });
  11135. await app.ready;
  11136. const resuming = app.submit("/resume session-running");
  11137. await vi.waitFor(() =>
  11138. expect(app.tui.render(80).join("\n")).toContain("Loading"),
  11139. );
  11140. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  11141. const followUp = app.submit("Send this through the Runtime queue");
  11142. await vi.waitFor(() =>
  11143. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  11144. "session-running",
  11145. "Send this through the Runtime queue",
  11146. { attachments: [] },
  11147. ),
  11148. );
  11149. expect(runtime.sendMessage).not.toHaveBeenCalled();
  11150. releaseQueue?.([]);
  11151. releaseModels?.([]);
  11152. await Promise.all([resuming, followUp]);
  11153. await app.stop();
  11154. });
  11155. it("does not recover a terminal session as an active turn", async () => {
  11156. const terminal = new FakeTerminal();
  11157. const runtime = createRuntime();
  11158. const session = {
  11159. sessionId: "session-finished",
  11160. title: "Finished session",
  11161. workspaceDir: "/workspace",
  11162. status: "finished",
  11163. };
  11164. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11165. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11166. const app = createTuiApp({
  11167. runtime,
  11168. terminal,
  11169. version: "0.1.0",
  11170. workspaceDir: "/workspace",
  11171. });
  11172. await app.ready;
  11173. await app.submit("/resume session-finished");
  11174. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
  11175. expect(app.tui.render(80).join("\n")).toContain("Message · Enter send");
  11176. await app.stop();
  11177. });
  11178. it("does not recover a stale started Session when Runtime is already idle", async () => {
  11179. const terminal = new FakeTerminal();
  11180. const runtime = createRuntime();
  11181. const session = {
  11182. sessionId: "session-stale",
  11183. title: "Stale session",
  11184. workspaceDir: "/workspace",
  11185. status: "started",
  11186. };
  11187. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11188. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11189. const app = createTuiApp({
  11190. runtime,
  11191. terminal,
  11192. version: "0.1.0",
  11193. workspaceDir: "/workspace",
  11194. });
  11195. app.start();
  11196. await app.ready;
  11197. await app.submit("/resume session-stale");
  11198. await vi.waitFor(() =>
  11199. expect(app.tui.render(80).join("\n")).not.toContain("Loading"),
  11200. );
  11201. const rendered = app.tui.render(80).join("\n");
  11202. expect(rendered).not.toContain("Thinking");
  11203. expect(rendered).not.toContain("Stopping response");
  11204. expect(rendered).not.toContain("Stopping the current response");
  11205. expect(rendered).toContain("Message · Enter send");
  11206. await app.stop();
  11207. });
  11208. it("stops a recovered Runtime turn with /stop and Escape through abortSession", async () => {
  11209. const terminal = new FakeTerminal();
  11210. const runtime = createRuntime();
  11211. const session = {
  11212. sessionId: "session-running",
  11213. title: "Running session",
  11214. workspaceDir: "/workspace",
  11215. status: "started",
  11216. };
  11217. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11218. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11219. vi.mocked(runtime.getActiveRun).mockResolvedValue({
  11220. schemaVersion: 1,
  11221. sessionId: "session-running",
  11222. state: "running",
  11223. turnId: "turn-running",
  11224. actions: { steer: true },
  11225. });
  11226. vi.mocked(runtime.abortSession).mockResolvedValue(true);
  11227. const app = createTuiApp({
  11228. runtime,
  11229. terminal,
  11230. version: "0.1.0",
  11231. workspaceDir: "/workspace",
  11232. });
  11233. app.start();
  11234. await app.ready;
  11235. await app.submit("/resume session-running");
  11236. await app.submit("/stop");
  11237. expect(runtime.abortSession).toHaveBeenCalledWith(
  11238. expect.objectContaining({ id: "session-running" }),
  11239. );
  11240. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
  11241. vi.mocked(runtime.abortSession).mockClear();
  11242. await app.submit("/resume session-running");
  11243. terminal.input?.("\x1b");
  11244. await vi.waitFor(() =>
  11245. expect(runtime.abortSession).toHaveBeenCalledWith(
  11246. expect.objectContaining({ id: "session-running" }),
  11247. ),
  11248. );
  11249. await vi.waitFor(() =>
  11250. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt"),
  11251. );
  11252. expect(app.tui.render(80).join("\n")).not.toMatch(
  11253. /Stopped after|Interrupted after/u,
  11254. );
  11255. await app.stop();
  11256. });
  11257. it.each([
  11258. [
  11259. "rejects the abort",
  11260. async () => false,
  11261. "Runtime did not confirm that the active response stopped.",
  11262. ],
  11263. [
  11264. "fails the abort request",
  11265. async () => Promise.reject(new Error("connection lost")),
  11266. "Couldn't stop the current response:",
  11267. ],
  11268. ])(
  11269. "clears the recovered foreground projection and reports when Runtime %s",
  11270. async (_label, abort, expectedError) => {
  11271. const terminal = new FakeTerminal();
  11272. const runtime = createRuntime();
  11273. const session = {
  11274. sessionId: "session-running",
  11275. title: "Running session",
  11276. workspaceDir: "/workspace",
  11277. status: "started",
  11278. };
  11279. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11280. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11281. vi.mocked(runtime.getActiveRun).mockResolvedValue({
  11282. schemaVersion: 1,
  11283. sessionId: "session-running",
  11284. state: "running",
  11285. turnId: "turn-running",
  11286. actions: { steer: false },
  11287. });
  11288. vi.mocked(runtime.abortSession).mockImplementation(abort);
  11289. const app = createTuiApp({
  11290. runtime,
  11291. terminal,
  11292. version: "0.1.0",
  11293. workspaceDir: "/workspace",
  11294. });
  11295. app.start();
  11296. await app.ready;
  11297. await app.submit("/resume session-running");
  11298. terminal.input?.("\x1b");
  11299. await vi.waitFor(() =>
  11300. expect(runtime.abortSession).toHaveBeenCalledWith(
  11301. expect.objectContaining({ id: "session-running" }),
  11302. ),
  11303. );
  11304. await vi.waitFor(() =>
  11305. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt"),
  11306. );
  11307. await vi.waitFor(() =>
  11308. expect(app.tui.render(80).join("\n")).toContain(expectedError),
  11309. );
  11310. await app.stop();
  11311. },
  11312. );
  11313. it("keeps Request failed visible when Runtime still has queued follow-ups", async () => {
  11314. const terminal = new FakeTerminal();
  11315. const runtime = createRuntime();
  11316. let finishTurn: (() => void) | undefined;
  11317. const queued = [
  11318. {
  11319. itemId: "queue-after-error",
  11320. sessionId: "session-1",
  11321. status: "queued",
  11322. content: "Continue after failure",
  11323. },
  11324. ];
  11325. vi.mocked(runtime.listQueuedMessages).mockResolvedValue(queued);
  11326. vi.mocked(runtime.enqueueMessage).mockResolvedValue({
  11327. itemId: "queue-after-error",
  11328. status: "queued",
  11329. position: 1,
  11330. });
  11331. vi.mocked(runtime.sendMessage).mockImplementation(
  11332. async function* sendMessage() {
  11333. await new Promise<void>((resolve) => {
  11334. finishTurn = resolve;
  11335. });
  11336. yield { type: "error", message: "provider unavailable" };
  11337. },
  11338. );
  11339. const app = createTuiApp({
  11340. runtime,
  11341. terminal,
  11342. version: "0.1.0",
  11343. workspaceDir: "/workspace",
  11344. productFeatures: { queue: true },
  11345. });
  11346. await app.ready;
  11347. const first = app.submit("First turn");
  11348. await vi.waitFor(() =>
  11349. expect(app.controller.snapshot().activeTurnId).toEqual(
  11350. expect.any(String),
  11351. ),
  11352. );
  11353. await app.submit("Continue after failure");
  11354. finishTurn?.();
  11355. await first;
  11356. expect(app.tui.render(80).join("\n")).toContain(
  11357. "Error The model provider is temporarily unavailable.",
  11358. );
  11359. expect(app.tui.render(80).join("\n")).not.toContain("Request failed");
  11360. await app.stop();
  11361. });
  11362. it("converges a recovered running state after the Runtime emits a terminal event", async () => {
  11363. const terminal = new FakeTerminal();
  11364. const runtime = createRuntime();
  11365. const session = {
  11366. sessionId: "session-recovered",
  11367. title: "Recovered session",
  11368. workspaceDir: "/workspace",
  11369. status: "started",
  11370. };
  11371. const busEvents: TuiRuntimeEvent[] = [];
  11372. let wakeBus: (() => void) | undefined;
  11373. const waitForNextBusEvent = (signal: AbortSignal) =>
  11374. new Promise<void>((resolve) => {
  11375. wakeBus = resolve;
  11376. signal.addEventListener("abort", resolve, { once: true });
  11377. });
  11378. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11379. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11380. let activeRecoveredTurn = true;
  11381. vi.mocked(runtime.getActiveRun).mockImplementation(async () =>
  11382. activeRecoveredTurn
  11383. ? {
  11384. schemaVersion: 1,
  11385. sessionId: "session-recovered",
  11386. state: "running",
  11387. turnId: "turn-recovered",
  11388. actions: { steer: true },
  11389. }
  11390. : {
  11391. schemaVersion: 1,
  11392. sessionId: "session-recovered",
  11393. state: "terminal",
  11394. turnId: "turn-recovered",
  11395. actions: { steer: false },
  11396. },
  11397. );
  11398. let durableMessages: Awaited<ReturnType<TuiRuntime["getMessages"]>> = [];
  11399. vi.mocked(runtime.getMessages).mockImplementation(
  11400. async () => durableMessages,
  11401. );
  11402. vi.mocked(runtime.watchEvents).mockImplementation(
  11403. async function* watchEvents(signal) {
  11404. while (!signal.aborted) {
  11405. if (busEvents.length === 0) await waitForNextBusEvent(signal);
  11406. if (signal.aborted) return;
  11407. const event = busEvents.shift();
  11408. if (event) yield event;
  11409. }
  11410. },
  11411. );
  11412. const app = createTuiApp({
  11413. runtime,
  11414. terminal,
  11415. version: "0.1.0",
  11416. workspaceDir: "/workspace",
  11417. });
  11418. app.start();
  11419. await app.ready;
  11420. await app.submit("/resume session-recovered");
  11421. expect(app.tui.render(80).join("\n")).toContain("Loading");
  11422. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  11423. await vi.waitFor(() =>
  11424. expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
  11425. "session-recovered",
  11426. "turn-recovered",
  11427. expect.any(AbortSignal),
  11428. ),
  11429. );
  11430. activeRecoveredTurn = false;
  11431. const historyCallsBeforeTerminal = vi.mocked(runtime.getMessages).mock.calls
  11432. .length;
  11433. durableMessages = [
  11434. {
  11435. id: "message-recovered-assistant",
  11436. turnId: "turn-recovered",
  11437. role: "assistant",
  11438. content: "Recovered answer",
  11439. timestamp: 101,
  11440. },
  11441. ];
  11442. busEvents.push(
  11443. runtimeEvent({
  11444. type: "session.finish",
  11445. timestamp: 101,
  11446. source: "runtime",
  11447. payload: {
  11448. sessionId: "session-recovered",
  11449. turnId: "turn-recovered",
  11450. status: "finished",
  11451. },
  11452. }),
  11453. );
  11454. wakeBus?.();
  11455. wakeBus = undefined;
  11456. await vi.waitFor(() =>
  11457. expect(vi.mocked(runtime.getMessages).mock.calls.length).toBeGreaterThan(
  11458. historyCallsBeforeTerminal,
  11459. ),
  11460. );
  11461. await vi.waitFor(() => {
  11462. const rendered = app.tui.render(80).join("\n");
  11463. expect(rendered).not.toContain("Esc to interrupt");
  11464. expect(app.transcript.snapshot()).toEqual(
  11465. expect.arrayContaining([
  11466. expect.objectContaining({
  11467. kind: "assistant",
  11468. content: "Recovered answer",
  11469. }),
  11470. ]),
  11471. );
  11472. });
  11473. await app.stop();
  11474. });
  11475. it("clears a recovered decision block when switching to a session without a pending decision", async () => {
  11476. const terminal = new FakeTerminal();
  11477. const runtime = createRuntime();
  11478. let controllerSessionId = "";
  11479. const firstSession = {
  11480. sessionId: "session-blocked",
  11481. title: "Blocked session",
  11482. workspaceDir: "/workspace",
  11483. status: "started",
  11484. };
  11485. const secondSession = {
  11486. sessionId: "session-clear",
  11487. title: "Clear session",
  11488. workspaceDir: "/workspace",
  11489. status: "finished",
  11490. };
  11491. vi.mocked(runtime.listSessions).mockResolvedValue([
  11492. firstSession,
  11493. secondSession,
  11494. ]);
  11495. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  11496. sessionId === firstSession.sessionId ? firstSession : secondSession,
  11497. );
  11498. vi.mocked(runtime.listPendingPermissions).mockImplementation(async () =>
  11499. controllerSessionId === firstSession.sessionId
  11500. ? [
  11501. {
  11502. requestId: "permission-blocked",
  11503. sessionId: firstSession.sessionId,
  11504. agentName: "mavis",
  11505. toolName: "bash",
  11506. reason: "Run checks",
  11507. allowAlwaysSupported: true,
  11508. },
  11509. ]
  11510. : [],
  11511. );
  11512. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue(undefined);
  11513. const app = createTuiApp({
  11514. runtime,
  11515. terminal,
  11516. version: "0.1.0",
  11517. workspaceDir: "/workspace",
  11518. });
  11519. await app.ready;
  11520. controllerSessionId = firstSession.sessionId;
  11521. await app.submit("/resume session-blocked");
  11522. expect(app.tui.hasOverlay()).toBe(false);
  11523. expect(app.interaction.isActive()).toBe(true);
  11524. expect(app.tui.render(80).join("\n")).toContain("Approval required");
  11525. controllerSessionId = secondSession.sessionId;
  11526. await app.submit("/resume session-clear");
  11527. expect(app.tui.hasOverlay()).toBe(false);
  11528. const rendered = app.tui.render(80).join("\n");
  11529. expect(rendered).not.toContain("Approval required");
  11530. expect(rendered).not.toContain("Reply required");
  11531. await app.stop();
  11532. });
  11533. it("moves a sending follow-up from the Composer area into the user transcript", async () => {
  11534. const terminal = new FakeTerminal();
  11535. const runtime = createRuntime();
  11536. const busEvents: TuiRuntimeEvent[] = [];
  11537. let wakeBus: (() => void) | undefined;
  11538. const waitForNextBusEvent = (signal: AbortSignal) =>
  11539. new Promise<void>((resolve) => {
  11540. wakeBus = resolve;
  11541. signal.addEventListener("abort", resolve, { once: true });
  11542. });
  11543. vi.mocked(runtime.listSessions).mockResolvedValue([
  11544. {
  11545. sessionId: "session-existing",
  11546. title: "Existing",
  11547. workspaceDir: "/workspace",
  11548. },
  11549. ]);
  11550. vi.mocked(runtime.listQueuedMessages).mockResolvedValue([
  11551. {
  11552. itemId: "queue-with-attachment",
  11553. sessionId: "session-existing",
  11554. status: "queued",
  11555. content: "Review the attached plan",
  11556. attachments: [
  11557. {
  11558. meta: {
  11559. attachmentType: "file",
  11560. fileName: "plan.md",
  11561. mimeType: "text/markdown",
  11562. sizeBytes: 42,
  11563. },
  11564. local: { filePath: "/workspace/plan.md" },
  11565. },
  11566. ],
  11567. },
  11568. {
  11569. itemId: "queue-that-fails",
  11570. sessionId: "session-existing",
  11571. status: "queued",
  11572. content: "Run the failing follow-up",
  11573. },
  11574. ]);
  11575. vi.mocked(runtime.watchEvents).mockImplementation(
  11576. async function* watchEvents(signal) {
  11577. while (!signal.aborted) {
  11578. if (busEvents.length === 0) await waitForNextBusEvent(signal);
  11579. if (signal.aborted) return;
  11580. const event = busEvents.shift();
  11581. if (event) yield event;
  11582. }
  11583. },
  11584. );
  11585. const emitQueueStatus = (
  11586. itemId: string,
  11587. status: string,
  11588. failedReason?: string,
  11589. ) => {
  11590. busEvents.push(
  11591. runtimeEvent({
  11592. type: "session.queue.updated",
  11593. timestamp: Date.now(),
  11594. source: "runtime",
  11595. payload: {
  11596. sessionId: "session-existing",
  11597. itemId,
  11598. status,
  11599. queuedCount: status === "queued" ? 1 : 0,
  11600. ...(failedReason ? { failedReason } : {}),
  11601. },
  11602. }),
  11603. );
  11604. wakeBus?.();
  11605. wakeBus = undefined;
  11606. };
  11607. const app = createTuiApp({
  11608. runtime,
  11609. terminal,
  11610. version: "0.1.0",
  11611. workspaceDir: "/workspace",
  11612. productFeatures: { queue: true },
  11613. });
  11614. app.start();
  11615. await app.ready;
  11616. await app.submit("/resume session-existing");
  11617. expect(app.tui.render(80).join("\n")).toContain("Queue · 2 next");
  11618. expect(app.tui.render(80).join("\n")).toContain("Review the attached plan");
  11619. expect(app.transcript.get("queue:queue-with-attachment")).toBeUndefined();
  11620. emitQueueStatus("queue-with-attachment", "running");
  11621. await vi.waitFor(() =>
  11622. expect(app.transcript.get("queue:queue-with-attachment")).toMatchObject({
  11623. kind: "user",
  11624. status: "succeeded",
  11625. content: expect.stringContaining("Review the attached plan"),
  11626. }),
  11627. );
  11628. expect(app.tui.render(80).join("\n")).not.toContain("SENDING");
  11629. expect(app.tui.render(80).join("\n")).toContain(
  11630. "Next · after current response",
  11631. );
  11632. expect(app.tui.render(80).join("\n")).toContain(
  11633. "Run the failing follow-up",
  11634. );
  11635. expect(
  11636. app.transcript.get("queue:queue-with-attachment")?.attachments,
  11637. ).toEqual([
  11638. expect.objectContaining({
  11639. fileName: "plan.md",
  11640. mimeType: "text/markdown",
  11641. sizeBytes: 42,
  11642. }),
  11643. ]);
  11644. emitQueueStatus("queue-with-attachment", "completed");
  11645. await vi.waitFor(() =>
  11646. expect(app.transcript.get("queue:queue-with-attachment")).toMatchObject({
  11647. kind: "user",
  11648. status: "succeeded",
  11649. content: expect.stringContaining("Review the attached plan"),
  11650. }),
  11651. );
  11652. emitQueueStatus("queue-that-fails", "running");
  11653. await vi.waitFor(() =>
  11654. expect(app.transcript.get("queue:queue-that-fails")).toMatchObject({
  11655. kind: "user",
  11656. status: "succeeded",
  11657. }),
  11658. );
  11659. emitQueueStatus(
  11660. "queue-that-fails",
  11661. "admission-rejected",
  11662. "provider unavailable",
  11663. );
  11664. await vi.waitFor(() =>
  11665. expect(app.editor.getText()).toBe("Run the failing follow-up"),
  11666. );
  11667. expect(app.tui.render(80).join("\n")).toContain(
  11668. "Error Message was not added to the Queue: provider unavailable.",
  11669. );
  11670. expect(app.transcript.get("queue:queue-that-fails")).toMatchObject({
  11671. kind: "user",
  11672. status: "succeeded",
  11673. });
  11674. expect(app.tui.render(80).join("\n")).toContain(
  11675. "Run the failing follow-up",
  11676. );
  11677. await app.stop();
  11678. });
  11679. it("refreshes history when Desktop Runtime finishes an auto-drained queued turn", async () => {
  11680. const terminal = new FakeTerminal();
  11681. const runtime = createRuntime();
  11682. const busEvents: TuiRuntimeEvent[] = [];
  11683. let wakeBus: (() => void) | undefined;
  11684. const waitForNextBusEvent = (signal: AbortSignal) =>
  11685. new Promise<void>((resolve) => {
  11686. wakeBus = resolve;
  11687. signal.addEventListener("abort", resolve, { once: true });
  11688. });
  11689. vi.mocked(runtime.listSessions).mockResolvedValue([
  11690. {
  11691. sessionId: "session-existing",
  11692. title: "Existing",
  11693. workspaceDir: "/workspace",
  11694. },
  11695. ]);
  11696. vi.mocked(runtime.getMessages)
  11697. .mockResolvedValueOnce([])
  11698. .mockResolvedValue([
  11699. {
  11700. id: "message-user-queued",
  11701. turnId: "turn-queued",
  11702. role: "user",
  11703. content: "Runtime follow-up",
  11704. timestamp: 100,
  11705. },
  11706. {
  11707. id: "message-assistant-queued",
  11708. turnId: "turn-queued",
  11709. role: "assistant",
  11710. content: "Runtime follow-up answer",
  11711. timestamp: 101,
  11712. },
  11713. ]);
  11714. vi.mocked(runtime.watchEvents).mockImplementation(
  11715. async function* watchEvents(signal) {
  11716. while (!signal.aborted) {
  11717. if (busEvents.length === 0) {
  11718. await waitForNextBusEvent(signal);
  11719. }
  11720. if (signal.aborted) return;
  11721. const event = busEvents.shift();
  11722. if (event) yield event;
  11723. }
  11724. },
  11725. );
  11726. const emit = (event: RawTuiRuntimeEvent) => {
  11727. busEvents.push(runtimeEvent(event));
  11728. wakeBus?.();
  11729. wakeBus = undefined;
  11730. };
  11731. const app = createTuiApp({
  11732. runtime,
  11733. terminal,
  11734. version: "0.1.0",
  11735. workspaceDir: "/workspace",
  11736. });
  11737. app.start();
  11738. await app.ready;
  11739. await app.submit("/resume session-existing");
  11740. emit({
  11741. type: "session.start",
  11742. timestamp: 100,
  11743. source: "runtime",
  11744. payload: {
  11745. sessionId: "session-existing",
  11746. turnId: "turn-queued",
  11747. source: "queued-drain",
  11748. queueItemIds: ["queue-1"],
  11749. },
  11750. });
  11751. await vi.waitFor(() =>
  11752. expect(app.tui.render(80).join("\n")).toContain("Loading"),
  11753. );
  11754. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  11755. expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
  11756. "session-existing",
  11757. "turn-queued",
  11758. expect.any(AbortSignal),
  11759. );
  11760. emit({
  11761. type: "session.finish",
  11762. timestamp: 101,
  11763. source: "runtime",
  11764. payload: {
  11765. sessionId: "session-existing",
  11766. turnId: "turn-queued",
  11767. status: "finished",
  11768. },
  11769. });
  11770. await vi.waitFor(() =>
  11771. expect(app.transcript.snapshot()).toEqual(
  11772. expect.arrayContaining([
  11773. expect.objectContaining({
  11774. kind: "assistant",
  11775. content: "Runtime follow-up answer",
  11776. }),
  11777. ]),
  11778. ),
  11779. );
  11780. const historyProjectionCalls = vi
  11781. .mocked(runtime.getMessages)
  11782. .mock.calls.filter(
  11783. ([sessionId, limit]) =>
  11784. sessionId === "session-existing" && limit === undefined,
  11785. );
  11786. expect(historyProjectionCalls).toHaveLength(2);
  11787. await app.stop();
  11788. });
  11789. it("writes one structured result when an auto-drained queued turn finishes", async () => {
  11790. const dataDir = await mkdtemp(join(tmpdir(), "mcode-queued-result-"));
  11791. const resultPath = join(dataDir, "results.jsonl");
  11792. const terminal = new FakeTerminal();
  11793. const runtime = createRuntime();
  11794. const busEvents: TuiRuntimeEvent[] = [];
  11795. let wakeBus: (() => void) | undefined;
  11796. let durableMessages: Awaited<ReturnType<TuiRuntime["getMessages"]>> = [];
  11797. vi.mocked(runtime.listSessions).mockResolvedValue([
  11798. {
  11799. sessionId: "session-existing",
  11800. title: "Existing",
  11801. workspaceDir: "/workspace",
  11802. },
  11803. ]);
  11804. vi.mocked(runtime.getMessages).mockImplementation(
  11805. async () => durableMessages,
  11806. );
  11807. const waitForBusEvent = (signal: AbortSignal) =>
  11808. new Promise<void>((resolve) => {
  11809. wakeBus = resolve;
  11810. signal.addEventListener("abort", resolve, { once: true });
  11811. });
  11812. vi.mocked(runtime.watchEvents).mockImplementation(
  11813. async function* watchEvents(signal) {
  11814. while (!signal.aborted) {
  11815. if (busEvents.length === 0) await waitForBusEvent(signal);
  11816. if (signal.aborted) return;
  11817. const event = busEvents.shift();
  11818. if (event) yield event;
  11819. }
  11820. },
  11821. );
  11822. const emit = (event: RawTuiRuntimeEvent) => {
  11823. busEvents.push(runtimeEvent(event));
  11824. wakeBus?.();
  11825. wakeBus = undefined;
  11826. };
  11827. const app = createTuiApp({
  11828. runtime,
  11829. terminal,
  11830. version: "0.1.0",
  11831. workspaceDir: "/workspace",
  11832. statusLineItems: ["build-mode"],
  11833. automationResultPath: resultPath,
  11834. });
  11835. try {
  11836. app.start();
  11837. await app.ready;
  11838. await app.submit("/resume session-existing");
  11839. emit({
  11840. type: "session.start",
  11841. timestamp: 100,
  11842. source: "runtime",
  11843. payload: {
  11844. sessionId: "session-existing",
  11845. turnId: "turn-queued-result",
  11846. source: "queued-drain",
  11847. queueItemIds: ["queue-result"],
  11848. },
  11849. });
  11850. await vi.waitFor(() =>
  11851. expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
  11852. "session-existing",
  11853. "turn-queued-result",
  11854. expect.any(AbortSignal),
  11855. ),
  11856. );
  11857. durableMessages = [
  11858. {
  11859. id: "message-user-result",
  11860. turnId: "turn-queued-result",
  11861. role: "user",
  11862. content: "Queued request",
  11863. timestamp: 101,
  11864. },
  11865. {
  11866. id: "message-assistant-result",
  11867. turnId: "turn-queued-result",
  11868. role: "assistant",
  11869. content: "Queued structured answer",
  11870. timestamp: 102,
  11871. },
  11872. ];
  11873. emit({
  11874. type: "session.finish",
  11875. timestamp: 103,
  11876. source: "runtime",
  11877. payload: {
  11878. sessionId: "session-existing",
  11879. turnId: "turn-queued-result",
  11880. status: "finished",
  11881. },
  11882. });
  11883. await vi.waitFor(async () => {
  11884. const records = (await readFile(resultPath, "utf8"))
  11885. .trim()
  11886. .split("\n")
  11887. .map(JSON.parse);
  11888. expect(records).toEqual([
  11889. expect.objectContaining({
  11890. type: "exec.result",
  11891. sessionId: "session-existing",
  11892. turnId: "turn-queued-result",
  11893. status: "succeeded",
  11894. answer: "Queued structured answer",
  11895. }),
  11896. ]);
  11897. });
  11898. expect(app.controller.snapshot().lastSettledTurn).toEqual({
  11899. sessionId: "session-existing",
  11900. turnId: "turn-queued-result",
  11901. status: "succeeded",
  11902. });
  11903. } finally {
  11904. await app.stop();
  11905. await rm(dataDir, { recursive: true, force: true });
  11906. }
  11907. });
  11908. it("settles an auto-drained follow-up once and replaces waiting state with run duration", async () => {
  11909. const terminal = new FakeTerminal();
  11910. const runtime = createRuntime();
  11911. const busEvents: TuiRuntimeEvent[] = [];
  11912. const queuedItems: TuiQueuedMessage[] = [];
  11913. let wakeBus: (() => void) | undefined;
  11914. let finishFirstTurn: (() => void) | undefined;
  11915. let finishQueuedStream: (() => void) | undefined;
  11916. const queuedStreamClosed = vi.fn();
  11917. let durableMessages: Awaited<ReturnType<TuiRuntime["getMessages"]>> = [];
  11918. const waitForNextBusEvent = (signal: AbortSignal) =>
  11919. new Promise<void>((resolve) => {
  11920. wakeBus = resolve;
  11921. signal.addEventListener("abort", resolve, { once: true });
  11922. });
  11923. vi.mocked(runtime.sendMessage).mockImplementation(
  11924. async function* sendMessage() {
  11925. await new Promise<void>((resolve) => {
  11926. finishFirstTurn = resolve;
  11927. });
  11928. yield { type: "delta", content: "First answer" };
  11929. yield { type: "done" };
  11930. },
  11931. );
  11932. vi.mocked(runtime.watchSessionTurn).mockImplementation(
  11933. async function* watchSessionTurn() {
  11934. try {
  11935. await new Promise<void>((resolve) => {
  11936. finishQueuedStream = resolve;
  11937. });
  11938. yield { type: "delta", content: "Queued answer" };
  11939. yield { type: "done" };
  11940. } finally {
  11941. queuedStreamClosed();
  11942. }
  11943. },
  11944. );
  11945. vi.mocked(runtime.enqueueMessage).mockImplementation(
  11946. async (sessionId, content) => {
  11947. const item: TuiQueuedMessage = {
  11948. itemId: "queue-b",
  11949. sessionId,
  11950. status: "queued",
  11951. content,
  11952. };
  11953. queuedItems.push(item);
  11954. return { itemId: item.itemId, status: item.status, position: 1 };
  11955. },
  11956. );
  11957. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  11958. ...queuedItems,
  11959. ]);
  11960. vi.mocked(runtime.getMessages).mockImplementation(
  11961. async () => durableMessages,
  11962. );
  11963. vi.mocked(runtime.watchEvents).mockImplementation(
  11964. async function* watchEvents(signal) {
  11965. while (!signal.aborted) {
  11966. if (busEvents.length === 0) await waitForNextBusEvent(signal);
  11967. if (signal.aborted) return;
  11968. const event = busEvents.shift();
  11969. if (event) yield event;
  11970. }
  11971. },
  11972. );
  11973. const emit = (event: RawTuiRuntimeEvent) => {
  11974. busEvents.push(runtimeEvent(event));
  11975. wakeBus?.();
  11976. wakeBus = undefined;
  11977. };
  11978. const app = createTuiApp({
  11979. runtime,
  11980. terminal,
  11981. version: "0.1.0",
  11982. workspaceDir: "/workspace",
  11983. productFeatures: { queue: true },
  11984. });
  11985. app.start();
  11986. await app.ready;
  11987. const first = app.submit("A");
  11988. await vi.waitFor(() =>
  11989. expect(app.controller.snapshot().activeTurnId).toBeDefined(),
  11990. );
  11991. await app.submit("B");
  11992. expect(app.tui.render(80).join("\n")).toContain(
  11993. "Next · after current response",
  11994. );
  11995. expect(app.tui.render(80).join("\n")).toContain("B");
  11996. finishFirstTurn?.();
  11997. await first;
  11998. const queuedItem = queuedItems[0];
  11999. expect(queuedItem).toBeDefined();
  12000. if (!queuedItem) throw new Error("Expected B to be queued.");
  12001. queuedItems[0] = { ...queuedItem, status: "running" };
  12002. emit({
  12003. type: "session.queue.updated",
  12004. timestamp: 200,
  12005. source: "runtime",
  12006. payload: {
  12007. sessionId: "session-1",
  12008. itemId: "queue-b",
  12009. status: "running",
  12010. queuedCount: 0,
  12011. },
  12012. });
  12013. emit({
  12014. type: "session.start",
  12015. timestamp: 201,
  12016. source: "runtime",
  12017. payload: {
  12018. sessionId: "session-1",
  12019. turnId: "turn_queue_b",
  12020. source: "queued-drain",
  12021. queueItemIds: ["queue-b"],
  12022. },
  12023. });
  12024. await vi.waitFor(() =>
  12025. expect(app.tui.render(80).join("\n")).toContain("Loading"),
  12026. );
  12027. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  12028. queuedItems.length = 0;
  12029. durableMessages = [
  12030. {
  12031. id: "history-user-b",
  12032. turnId: "turn_queue_b",
  12033. role: "user",
  12034. content: "B",
  12035. timestamp: 202,
  12036. },
  12037. {
  12038. id: "history-assistant-b",
  12039. turnId: "turn_queue_b",
  12040. role: "assistant",
  12041. content: "Queued answer",
  12042. timestamp: 203,
  12043. },
  12044. ];
  12045. finishQueuedStream?.();
  12046. await vi.waitFor(() => expect(queuedStreamClosed).toHaveBeenCalledOnce());
  12047. emit({
  12048. type: "session.finish",
  12049. timestamp: 3_201,
  12050. source: "runtime",
  12051. payload: {
  12052. sessionId: "session-1",
  12053. turnId: "turn_queue_b",
  12054. status: "finished",
  12055. },
  12056. });
  12057. await vi.waitFor(() =>
  12058. expect(
  12059. app.transcript
  12060. .snapshot()
  12061. .filter((cell) => cell.content === "Queued answer"),
  12062. ).toHaveLength(1),
  12063. );
  12064. await vi.waitFor(() =>
  12065. expect(app.transcript.get("turn-duration:turn_queue_b")).toMatchObject({
  12066. status: "succeeded",
  12067. durationMs: 3_000,
  12068. }),
  12069. );
  12070. const settledUi = app.tui.render(80).join("\n");
  12071. expect(settledUi).toContain("Completed in 3s");
  12072. expect(settledUi.indexOf("Completed in 3s")).toBeGreaterThan(
  12073. settledUi.indexOf("Queued answer"),
  12074. );
  12075. expect(settledUi).not.toContain("message waiting");
  12076. expect(settledUi).not.toContain("Next · after current response");
  12077. await app.stop();
  12078. });
  12079. it("records submitted drafts in editor history", async () => {
  12080. const terminal = new FakeTerminal();
  12081. const runtime = createRuntime();
  12082. const app = createTuiApp({
  12083. runtime,
  12084. terminal,
  12085. version: "0.1.0",
  12086. workspaceDir: "/workspace",
  12087. });
  12088. await app.ready;
  12089. app.editor.setText("Remember this draft");
  12090. app.editor.handleInput("\r");
  12091. await vi.waitFor(() =>
  12092. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  12093. );
  12094. app.editor.handleInput("\u001b[A");
  12095. expect(app.editor.getText()).toBe("Remember this draft");
  12096. });
  12097. it("continues sending and switching sessions when draft cleanup fails", async () => {
  12098. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-warning-"));
  12099. const runtime = createRuntime();
  12100. const app = createTuiApp({
  12101. runtime,
  12102. terminal: new FakeTerminal(),
  12103. version: "0.1.0",
  12104. dataDir,
  12105. workspaceDir: "/workspace",
  12106. });
  12107. const flush = vi.spyOn(TuiDraftRecovery.prototype, "flush");
  12108. try {
  12109. await app.ready;
  12110. flush.mockRejectedValue(
  12111. new TuiDraftRecoveryError("cleanup", new Error("deletion denied")),
  12112. );
  12113. app.editor.setText("hello");
  12114. app.editor.handleInput("\r");
  12115. await vi.waitFor(() =>
  12116. expect(
  12117. app.transcript.snapshot().filter((cell) => cell.kind === "warning"),
  12118. ).toHaveLength(1),
  12119. );
  12120. const warnings = app.transcript
  12121. .snapshot()
  12122. .filter((cell) => cell.kind === "warning");
  12123. expect(warnings[0]?.content).toContain(
  12124. composerText("draftCleanupNextStep"),
  12125. );
  12126. expect(warnings[0]?.content).not.toContain(
  12127. composerText("draftRecoveryUnavailable"),
  12128. );
  12129. expect(warnings[0]?.content).toContain("deletion denied");
  12130. await vi.waitFor(() =>
  12131. expect(runtime.sendMessage).toHaveBeenCalledOnce(),
  12132. );
  12133. await vi.waitFor(() =>
  12134. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  12135. );
  12136. await expect(app.openSession("session-2")).resolves.toBeUndefined();
  12137. expect(app.controller.snapshot().session?.sessionId).toBe("session-2");
  12138. app.editor.setText("after switching");
  12139. app.editor.handleInput("\r");
  12140. await vi.waitFor(() =>
  12141. expect(runtime.sendMessage).toHaveBeenCalledTimes(2),
  12142. );
  12143. await expect(app.stop()).resolves.toBeUndefined();
  12144. } finally {
  12145. await app.stop();
  12146. flush.mockRestore();
  12147. await rm(dataDir, { recursive: true, force: true });
  12148. }
  12149. });
  12150. it("does not read or restore a persisted Draft during TUI startup", async () => {
  12151. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-"));
  12152. try {
  12153. const first = createTuiApp({
  12154. runtime: createRuntime(),
  12155. terminal: new FakeTerminal(),
  12156. version: "0.1.0",
  12157. dataDir,
  12158. workspaceDir: "/workspace/recovery",
  12159. });
  12160. await first.ready;
  12161. first.editor.setText("/exit");
  12162. await first.stop();
  12163. const loadDraft = vi.spyOn(TuiDraftRecovery.prototype, "load");
  12164. const restored = createTuiApp({
  12165. runtime: createRuntime(),
  12166. terminal: new FakeTerminal(),
  12167. version: "0.1.0",
  12168. dataDir,
  12169. workspaceDir: "/workspace/recovery",
  12170. });
  12171. await restored.ready;
  12172. expect(loadDraft).not.toHaveBeenCalled();
  12173. expect(restored.editor.getText()).toBe("");
  12174. expect(restored.tui.render(80).join("\n")).not.toContain(
  12175. "Draft restored",
  12176. );
  12177. loadDraft.mockRestore();
  12178. restored.editor.setText("");
  12179. await restored.stop();
  12180. } finally {
  12181. await rm(dataDir, { recursive: true, force: true });
  12182. }
  12183. });
  12184. it("does not resume a persisted Draft during startup when login recovery is enabled", async () => {
  12185. const dataDir = await mkdtemp(join(tmpdir(), "mcode-login-restart-draft-"));
  12186. try {
  12187. const first = createTuiApp({
  12188. runtime: createRuntime(),
  12189. terminal: new FakeTerminal(),
  12190. version: "0.1.0",
  12191. dataDir,
  12192. workspaceDir: "/workspace/login-recovery",
  12193. });
  12194. await first.ready;
  12195. first.editor.setText("send after Global login");
  12196. await first.stop();
  12197. const restored = createTuiApp({
  12198. runtime: createRuntime(),
  12199. terminal: new FakeTerminal(),
  12200. version: "0.1.0",
  12201. dataDir,
  12202. workspaceDir: "/workspace/login-recovery",
  12203. resumeDraftAfterLogin: true,
  12204. });
  12205. await restored.ready;
  12206. restored.start();
  12207. expect(restored.editor.getText()).toBe("");
  12208. expect(restored.getSurface()).toBe("welcome");
  12209. expect(restored.tui.render(80).join("\n")).toContain(
  12210. "Tips for getting started",
  12211. );
  12212. await restored.stop();
  12213. } finally {
  12214. await rm(dataDir, { recursive: true, force: true });
  12215. }
  12216. });
  12217. it("keeps the submitted Draft recoverable when shutdown wins before Runtime admission", async () => {
  12218. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-pending-draft-"));
  12219. try {
  12220. const runtime = createRuntime();
  12221. vi.spyOn(runtime, "sendMessage").mockImplementation(
  12222. async function* sendMessage(
  12223. _req: SendMessageReq,
  12224. signal?: AbortSignal,
  12225. ) {
  12226. yield* [];
  12227. await new Promise<void>((_resolve, reject) => {
  12228. signal?.addEventListener(
  12229. "abort",
  12230. () => reject(new Error("admission aborted")),
  12231. {
  12232. once: true,
  12233. },
  12234. );
  12235. });
  12236. throw new Error("unreachable");
  12237. },
  12238. );
  12239. const first = createTuiApp({
  12240. runtime,
  12241. terminal: new FakeTerminal(),
  12242. version: "0.1.0",
  12243. dataDir,
  12244. workspaceDir: "/workspace/pending-recovery",
  12245. });
  12246. await first.ready;
  12247. first.editor.setText("recover me until Runtime accepts");
  12248. await new Promise((resolve) => setTimeout(resolve, 300));
  12249. first.editor.handleInput("\r");
  12250. await vi.waitFor(() =>
  12251. expect(runtime.sendMessage).toHaveBeenCalledOnce(),
  12252. );
  12253. await first.stop();
  12254. const restored = createTuiApp({
  12255. runtime: createRuntime(),
  12256. terminal: new FakeTerminal(),
  12257. version: "0.1.0",
  12258. dataDir,
  12259. workspaceDir: "/workspace/pending-recovery",
  12260. });
  12261. await restored.ready;
  12262. await restored.openSession("session-1");
  12263. expect(restored.editor.getText()).toBe(
  12264. "recover me until Runtime accepts",
  12265. );
  12266. const rendered = restored.tui.render(80).join("\n");
  12267. expect(rendered).toContain("recover me until Runtime accepts");
  12268. expect(rendered).not.toContain("Message kept under Failed");
  12269. await restored.stop();
  12270. } finally {
  12271. await rm(dataDir, { recursive: true, force: true });
  12272. }
  12273. });
  12274. it("does not restore a submitted Draft after Runtime accepts the turn", async () => {
  12275. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-accepted-draft-"));
  12276. try {
  12277. const runtime = createRuntime();
  12278. vi.mocked(runtime.sendMessage).mockImplementation(
  12279. async function* sendMessage(
  12280. _req: SendMessageReq,
  12281. signal?: AbortSignal,
  12282. ) {
  12283. await new Promise<void>((resolve) => {
  12284. signal?.addEventListener("abort", resolve, { once: true });
  12285. });
  12286. yield { type: "done" };
  12287. },
  12288. );
  12289. const first = createTuiApp({
  12290. runtime,
  12291. terminal: new FakeTerminal(),
  12292. version: "0.1.0",
  12293. dataDir,
  12294. workspaceDir: "/workspace/accepted-recovery",
  12295. });
  12296. await first.ready;
  12297. first.editor.setText("already accepted by Runtime");
  12298. await new Promise((resolve) => setTimeout(resolve, 300));
  12299. first.editor.handleInput("\r");
  12300. await vi.waitFor(() =>
  12301. expect(runtime.sendMessage).toHaveBeenCalledOnce(),
  12302. );
  12303. await first.stop();
  12304. const restored = createTuiApp({
  12305. runtime: createRuntime(),
  12306. terminal: new FakeTerminal(),
  12307. version: "0.1.0",
  12308. dataDir,
  12309. workspaceDir: "/workspace/accepted-recovery",
  12310. });
  12311. await restored.ready;
  12312. expect(restored.editor.getText()).toBe("");
  12313. await restored.stop();
  12314. } finally {
  12315. await rm(dataDir, { recursive: true, force: true });
  12316. }
  12317. });
  12318. it("serializes rapid Session switches without mixing their Drafts", async () => {
  12319. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-"));
  12320. try {
  12321. const app = createTuiApp({
  12322. runtime: createRuntime(),
  12323. terminal: new FakeTerminal(),
  12324. version: "0.1.0",
  12325. dataDir,
  12326. workspaceDir: "/workspace/recovery",
  12327. });
  12328. await app.ready;
  12329. await app.openSession("session-a");
  12330. app.editor.setText("Draft for Session A");
  12331. await app.openSession("session-b");
  12332. app.editor.setText("Draft for Session B");
  12333. await Promise.all([
  12334. app.openSession("session-a"),
  12335. app.openSession("session-b"),
  12336. ]);
  12337. expect(app.controller.snapshot().session?.sessionId).toBe("session-b");
  12338. expect(app.editor.getText()).toBe("Draft for Session B");
  12339. await app.openSession("session-a");
  12340. expect(app.editor.getText()).toBe("Draft for Session A");
  12341. await app.openSession("session-b");
  12342. expect(app.editor.getText()).toBe("Draft for Session B");
  12343. await app.stop();
  12344. } finally {
  12345. await rm(dataDir, { recursive: true, force: true });
  12346. }
  12347. });
  12348. it("moves to the new-session Draft namespace after archiving the current Session", async () => {
  12349. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-"));
  12350. try {
  12351. const app = createTuiApp({
  12352. runtime: createRuntime(),
  12353. terminal: new FakeTerminal(),
  12354. version: "0.1.0",
  12355. dataDir,
  12356. workspaceDir: "/workspace/recovery",
  12357. });
  12358. await app.ready;
  12359. await app.openSession("session-a");
  12360. app.editor.setText("Archived Session Draft");
  12361. await app.submit("/archive");
  12362. app.editor.setText("Fresh Session Draft");
  12363. await app.openSession("session-a");
  12364. expect(app.editor.getText()).toBe("Archived Session Draft");
  12365. await app.submit("/new");
  12366. expect(app.editor.getText()).toBe("Fresh Session Draft");
  12367. await app.stop();
  12368. } finally {
  12369. await rm(dataDir, { recursive: true, force: true });
  12370. }
  12371. });
  12372. });
  12373. describe("interactive CLI model startup", () => {
  12374. it.each([
  12375. [
  12376. "new with prompt",
  12377. ["-m", "custom_provider:relay/vendor/model#thinking", "hello"],
  12378. "session-1",
  12379. true,
  12380. ],
  12381. [
  12382. "new without prompt",
  12383. ["--model=custom_provider:relay/vendor/model#thinking"],
  12384. "session-1",
  12385. false,
  12386. ],
  12387. [
  12388. "explicit session",
  12389. ["--session", "existing", "--model", "custom_provider:relay/vendor/model#thinking", "hello"],
  12390. "existing",
  12391. true,
  12392. ],
  12393. [
  12394. "continue",
  12395. ["--continue", "--model", "custom_provider:relay/vendor/model#thinking", "hello"],
  12396. "existing",
  12397. true,
  12398. ],
  12399. [
  12400. "missing session",
  12401. ["--session", "missing", "-m", "custom_provider:relay/vendor/model#thinking", "hello"],
  12402. "missing",
  12403. false,
  12404. ],
  12405. [
  12406. "empty continue",
  12407. ["--continue", "-m", "custom_provider:relay/vendor/model#thinking", "hello"],
  12408. "existing",
  12409. false,
  12410. ],
  12411. ["invalid provider", ["--model", "missing/model", "hello"], "session-1", false],
  12412. ["invalid model", ["--model", "custom_provider:relay/missing", "hello"], "session-1", false],
  12413. ] as const)(
  12414. "routes %s through launch, hydration and submission",
  12415. async (_name, args, sessionId, hasPrompt) => {
  12416. const dataDir = await mkdtemp(join(tmpdir(), "mcode-model-startup-"));
  12417. const terminal = new FakeTerminal();
  12418. const runtime = createRuntime();
  12419. runtime.listBackgroundTasks = vi.fn(async () => []);
  12420. const models = new Map<string, { providerId: string; modelId: string; variant?: string }>();
  12421. const requested = {
  12422. providerId: "custom_provider:relay",
  12423. modelId: "vendor/model",
  12424. variant: "thinking",
  12425. };
  12426. const existing = { sessionId: "existing", workspaceDir: "/workspace", updatedAt: 10 };
  12427. vi.mocked(runtime.listSessions).mockResolvedValue([existing]);
  12428. vi.mocked(runtime.listSessionPage).mockResolvedValue({
  12429. sessions: [existing],
  12430. hasMore: false,
  12431. });
  12432. vi.mocked(runtime.getSession).mockImplementation(async (id) => ({
  12433. sessionId: id,
  12434. workspaceDir: "/workspace",
  12435. model: models.get(id),
  12436. }));
  12437. const failedResume = _name === "missing session" || _name === "empty continue";
  12438. if (_name === "missing session")
  12439. vi.mocked(runtime.getSession).mockRejectedValue(new Error("Session not found"));
  12440. if (_name === "empty continue") vi.mocked(runtime.listSessions).mockResolvedValue([]);
  12441. runtime.selectModel = vi.fn(async () => true);
  12442. runtime.selectSessionModel = vi.fn(async (model, id) => {
  12443. if (model.providerId !== requested.providerId || model.modelId !== requested.modelId) {
  12444. throw new Error("Unknown provider or model");
  12445. }
  12446. models.set(id, model);
  12447. return true;
  12448. });
  12449. vi.mocked(runtime.listModels).mockImplementation(async (id) => [
  12450. { ...requested, name: "Startup model", selected: Boolean(id && models.has(id)) },
  12451. ]);
  12452. // A global managed default needs login; the selected BYOK Session does not.
  12453. vi.mocked(runtime.getAccountStatus).mockImplementation(async (id) => ({
  12454. status: id && models.has(id) ? "ready" : "needs-login",
  12455. modelSource: id && models.has(id) ? "byok" : "token-plan",
  12456. managedTokenPresent: false,
  12457. warnings: [],
  12458. }));
  12459. const sentModels: unknown[] = [];
  12460. vi.mocked(runtime.sendMessage).mockImplementation(async function* (request) {
  12461. sentModels.push(models.get(request.id));
  12462. yield { type: "delta", content: "offline reply" };
  12463. yield { type: "done" };
  12464. });
  12465. const invalid = _name.startsWith("invalid");
  12466. const stderr = vi.fn((_text: string, callback?: () => void) => callback?.());
  12467. const processRef = {
  12468. title: "test",
  12469. argv: ["node", "cli.js", ...args],
  12470. env: {},
  12471. versions: { node: "24.2.0" },
  12472. stdout: {
  12473. destroyed: false,
  12474. writableEnded: false,
  12475. write: vi.fn((_text: string, cb?: () => void) => cb?.()),
  12476. },
  12477. stderr: { destroyed: false, writableEnded: false, write: stderr },
  12478. exit: vi.fn(),
  12479. exitCode: 0,
  12480. };
  12481. let app: ReturnType<typeof createTuiApp> | undefined;
  12482. const running = runTuiCli({
  12483. processRef,
  12484. configureNetworkProxy: () => undefined,
  12485. launchTui: (input) =>
  12486. launchTui(
  12487. { ...input, dataDir, terminal, workspaceDir: "/workspace" },
  12488. {
  12489. createObservability,
  12490. readTelemetryEnabled: () => false,
  12491. installProcessGuards: () => () => undefined,
  12492. loadRuntimeLifecycle: async () => ({
  12493. createTuiRuntime: async () => ({ adapter: runtime }) as never,
  12494. shutdownTuiRuntime: async () => false,
  12495. }),
  12496. loadUpdateApplication: async () =>
  12497. ({ inspect: async () => ({ status: "up-to-date" }) }) as never,
  12498. createApp: (options) => {
  12499. app = createTuiApp({ ...options, productFeatures: { queue: false } });
  12500. return app;
  12501. },
  12502. writeExitMessage: () => undefined,
  12503. },
  12504. ),
  12505. });
  12506. try {
  12507. if (invalid) {
  12508. await running;
  12509. expect(processRef.exitCode).toBe(1);
  12510. expect(stderr.mock.calls.flat().join(" ")).toContain("Unknown provider or model");
  12511. expect(runtime.sendMessage).not.toHaveBeenCalled();
  12512. } else if (failedResume) {
  12513. await vi.waitFor(() => expect(app?.editor.disableSubmit).toBe(false));
  12514. expect(runtime.selectSessionModel).not.toHaveBeenCalled();
  12515. expect(runtime.createSession).not.toHaveBeenCalled();
  12516. expect(runtime.sendMessage).not.toHaveBeenCalled();
  12517. } else {
  12518. await vi.waitFor(() => {
  12519. expect(app?.editor.disableSubmit).toBe(false);
  12520. expect(app?.controller.snapshot().session?.model).toEqual(requested);
  12521. if (hasPrompt) expect(sentModels).toEqual([requested]);
  12522. });
  12523. expect(runtime.selectSessionModel).toHaveBeenCalledWith(requested, sessionId);
  12524. expect(app?.controller.snapshot().account?.modelSource).toBe("byok");
  12525. if (sessionId === "existing") expect(runtime.createSession).not.toHaveBeenCalled();
  12526. if (!hasPrompt) {
  12527. expect(runtime.sendMessage).not.toHaveBeenCalled();
  12528. await app?.submit("later prompt");
  12529. expect(sentModels).toEqual([requested]);
  12530. }
  12531. await vi.waitFor(() => expect(app?.controller.snapshot().status).toBe("idle"));
  12532. await app?.submit("/new");
  12533. expect(app?.controller.snapshot().session).toBeUndefined();
  12534. expect(runtime.selectSessionModel).toHaveBeenCalledOnce();
  12535. }
  12536. expect(runtime.selectModel).not.toHaveBeenCalled();
  12537. } finally {
  12538. await app?.stop();
  12539. await running;
  12540. await rm(dataDir, { recursive: true, force: true });
  12541. }
  12542. },
  12543. );
  12544. });
  12545. describe("interactive model argument contract", () => {
  12546. function program() {
  12547. const launch = vi.fn(async () => undefined);
  12548. const command = createTuiProgram({
  12549. version: "test",
  12550. launchTui: launch,
  12551. runExec: vi.fn(),
  12552. runLogin: vi.fn(),
  12553. runLogout: vi.fn(),
  12554. runUpdate: vi.fn(),
  12555. })
  12556. .exitOverride()
  12557. .configureOutput({ writeErr: () => undefined });
  12558. return { command, launch };
  12559. }
  12560. it.each(["-m", "--model"])("rejects missing values for %s", async (flag) => {
  12561. const { command, launch } = program();
  12562. await expect(command.parseAsync([flag], { from: "user" })).rejects.toThrow();
  12563. expect(launch).not.toHaveBeenCalled();
  12564. });
  12565. it.each(["", "bare-model", "provider/", "/model", "provider/model#"])(
  12566. "rejects malformed model %j before launch",
  12567. async (model) => {
  12568. const { command, launch } = program();
  12569. await expect(command.parseAsync(["--model", model], { from: "user" })).rejects.toThrow(
  12570. "--model must use provider/model",
  12571. );
  12572. expect(launch).not.toHaveBeenCalled();
  12573. },
  12574. );
  12575. it("rejects a model with an untargeted Session picker", async () => {
  12576. const { command, launch } = program();
  12577. await expect(
  12578. command.parseAsync(["--session", "--model", "provider/model"], { from: "user" }),
  12579. ).rejects.toThrow("requires a Session id");
  12580. expect(launch).not.toHaveBeenCalled();
  12581. });
  12582. it("retains the default launch contract without a model", async () => {
  12583. const { command, launch } = program();
  12584. await command.parseAsync(["hello"], { from: "user" });
  12585. expect(launch).toHaveBeenCalledWith({ initialPrompt: "hello" });
  12586. });
  12587. it.each(["-m", "--model"])("scans startup environment after %s values", (flag) => {
  12588. expect(
  12589. resolveTuiStartupEnvironmentOption([flag, "provider/model", "--env", "staging"], true),
  12590. ).toBe("staging");
  12591. expect(() =>
  12592. resolveTuiStartupEnvironmentOption([flag, "provider/model", "--env", "prod"], false),
  12593. ).toThrow("only available");
  12594. expect(
  12595. resolveTuiStartupEnvironmentOption(
  12596. [flag, "provider/model", "exec", "--env", "staging"],
  12597. true,
  12598. ),
  12599. ).toBeUndefined();
  12600. });
  12601. });