tui-app.test.ts 404 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178
  1. import { describe, expect, it, vi } from "vitest";
  2. import { mkdtemp, readFile, rm, writeFile, mkdir } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import type { TerminalCapabilities } from "../../src/tui/platform/terminal-capabilities.js";
  6. import {
  7. TuiAltScreen,
  8. VStack,
  9. type Terminal,
  10. } from "../../src/tui/engine/public.js";
  11. import { createTuiApp } from "../../src/tui/app.js";
  12. import type {
  13. TuiModel,
  14. TuiQuestionnaireRequest,
  15. TuiQueuedMessage,
  16. TuiRuntimeEvent,
  17. TuiRuntime,
  18. TuiSessionForkPort,
  19. TuiStreamEvent,
  20. } from "../../src/runtime/port.js";
  21. import {
  22. normalizeTuiRuntimeEvent,
  23. type RawTuiRuntimeEvent,
  24. } from "../../src/runtime/event-normalizer.js";
  25. import type { SendMessageReq } from "@mavis/local-runtime-v2/cli-service";
  26. import type { TuiObservability } from "../../src/observability/local-observability.js";
  27. import type { McodeAuthProgress } from "../../src/auth/application.js";
  28. import { formatTuiShortcut } from "../../src/tui/shell/shortcut-labels.js";
  29. import { createTuiHostKeybindings } from "../../src/tui/shell/keybindings.js";
  30. import { stripAnsi } from "../../src/tui/rendering/text.js";
  31. import {
  32. TuiDraftRecovery,
  33. TuiDraftRecoveryError,
  34. } from "../../src/tui/features/composer/draft-recovery.js";
  35. import { composerText } from "../../src/tui/features/composer/copy.js";
  36. import type {
  37. McodeBusinessEvent,
  38. McodeBusinessTelemetry,
  39. } from "../../src/analytics/business-telemetry.js";
  40. import { VirtualTerminalScreen } from "../helpers/virtual-terminal.js";
  41. import { TuiFailure } from "../../src/failure.js";
  42. const runtimeEvent = (event: RawTuiRuntimeEvent): TuiRuntimeEvent =>
  43. normalizeTuiRuntimeEvent(event);
  44. function planReviewEventRequest(id: string) {
  45. return {
  46. schemaVersion: 2,
  47. id,
  48. mode: "plan",
  49. modePayload: {
  50. planReview: {
  51. markdown: "# Frozen plan\n\nImplement and verify the change.",
  52. path: "/history/session-1/artifacts/plan.md",
  53. },
  54. },
  55. presentation: {
  56. replaceComposer: true,
  57. showProgress: true,
  58. allowBackNavigation: true,
  59. },
  60. steps: [
  61. {
  62. id: "plan-review",
  63. question: "Approve?",
  64. selectionMode: "single",
  65. options: [{ id: "approve", label: "Approve" }],
  66. allowOther: true,
  67. required: true,
  68. },
  69. ],
  70. } as const;
  71. }
  72. function planEntryEventRequest(id: string) {
  73. return {
  74. schemaVersion: 2,
  75. id,
  76. mode: "plan",
  77. presentation: {
  78. replaceComposer: true,
  79. showProgress: true,
  80. allowBackNavigation: true,
  81. },
  82. steps: [
  83. {
  84. id: "plan-enter",
  85. question: "Enter Plan Mode for this task?",
  86. selectionMode: "single",
  87. options: [
  88. { id: "confirm", label: "Confirm" },
  89. { id: "decline", label: "Decline" },
  90. ],
  91. allowOther: true,
  92. otherPlaceholder: "Others...",
  93. required: true,
  94. },
  95. ],
  96. } as const;
  97. }
  98. function createObservability(): TuiObservability {
  99. return {
  100. recordStartup: vi.fn(),
  101. recordAccess: vi.fn(),
  102. recordEventStream: vi.fn(),
  103. recordTerminal: vi.fn(),
  104. recordProcessStop: vi.fn(),
  105. observeRender: vi.fn(),
  106. snapshot: vi.fn(() => ({
  107. filePath: "/tmp/mcode-observability.jsonl",
  108. eventCounts: {
  109. startup: 0,
  110. runtimeAccess: 0,
  111. eventStream: 0,
  112. terminal: 0,
  113. },
  114. accessSources: {},
  115. reconnects: 0,
  116. render: {
  117. frames: 0,
  118. averageDurationMs: 0,
  119. maxDurationMs: 0,
  120. p95DurationMs: 0,
  121. },
  122. })),
  123. flush: vi.fn(async () => undefined),
  124. };
  125. }
  126. class FakeTerminal implements Terminal {
  127. columns = 80;
  128. rows = 18;
  129. kittyProtocolActive = false;
  130. started = false;
  131. stopped = false;
  132. startCount = 0;
  133. stopCount = 0;
  134. drainCount = 0;
  135. title = "";
  136. titleUpdates: string[] = [];
  137. mouseTracking = false;
  138. mouseTrackingUpdates: boolean[] = [];
  139. writes: string[] = [];
  140. input?: (data: string) => void;
  141. start(onInput: (data: string) => void): void {
  142. this.started = true;
  143. this.stopped = false;
  144. this.startCount += 1;
  145. this.input = onInput;
  146. }
  147. stop(): void {
  148. this.stopped = true;
  149. this.stopCount += 1;
  150. }
  151. drainInput(): Promise<void> {
  152. this.drainCount += 1;
  153. return Promise.resolve();
  154. }
  155. write(data: string): void {
  156. this.writes.push(data);
  157. }
  158. moveBy(): void {}
  159. hideCursor(): void {}
  160. showCursor(): void {}
  161. clearLine(): void {}
  162. clearFromCursor(): void {}
  163. clearScreen(): void {}
  164. setProgress(): void {}
  165. setMouseTracking(enabled: boolean): void {
  166. this.mouseTracking = enabled;
  167. this.mouseTrackingUpdates.push(enabled);
  168. }
  169. setTitle(title: string): void {
  170. this.title = title;
  171. this.titleUpdates.push(title);
  172. }
  173. }
  174. function renderTerminalViewport(
  175. app: ReturnType<typeof createTuiApp>,
  176. terminal: FakeTerminal,
  177. ): string {
  178. app.tui.renderNow();
  179. const screen = new VirtualTerminalScreen(terminal.columns, terminal.rows);
  180. try {
  181. for (const write of terminal.writes) screen.feed(write);
  182. return screen.viewportText();
  183. } finally {
  184. screen.dispose();
  185. }
  186. }
  187. function createRuntime(): TuiRuntime {
  188. const abortSession = vi.fn(async () => true);
  189. let currentGoal: Awaited<ReturnType<TuiRuntime["getGoal"]>>;
  190. let createdSession:
  191. | {
  192. sessionId: string;
  193. title: string;
  194. workspaceDir: string;
  195. interactionMode?: "plan";
  196. }
  197. | undefined;
  198. const runtime: TuiRuntime = {
  199. createSession: vi.fn(async () => {
  200. createdSession = {
  201. sessionId: "session-1",
  202. title: "New session",
  203. workspaceDir: "/workspace",
  204. };
  205. return { ...createdSession };
  206. }),
  207. listSessions: vi.fn(async () => []),
  208. listSessionPage: vi.fn(async () => ({
  209. sessions: [],
  210. hasMore: false,
  211. })),
  212. getSession: vi.fn(async (sessionId: string) =>
  213. createdSession?.sessionId === sessionId
  214. ? { ...createdSession }
  215. : {
  216. sessionId,
  217. title: "Existing session",
  218. workspaceDir: "/workspace",
  219. },
  220. ),
  221. getMessages: vi.fn(async () => []),
  222. listMessagePage: vi.fn(async () => ({ messages: [], hasMore: false })),
  223. getSessionForkOptions: vi.fn(async () => ({
  224. canFork: true,
  225. worktreeVisible: false,
  226. worktreeEligible: false,
  227. })),
  228. forkSession: vi.fn(async () => ({
  229. session: {
  230. sessionId: "session-fork",
  231. parentSessionId: "session-1",
  232. title: "New session (fork 1)",
  233. workspaceDir: "/workspace",
  234. },
  235. })),
  236. getWorkspaceGitMetadata: vi.fn(async () => ({
  237. isGitRepo: false,
  238. branch: "",
  239. detached: false,
  240. isWorktree: false,
  241. })),
  242. renameSession: vi.fn(async (sessionId: string, title: string) => ({
  243. sessionId,
  244. title,
  245. workspaceDir: "/workspace",
  246. })),
  247. archiveSession: vi.fn(async () => undefined),
  248. listSessionInputSummaries: vi.fn(async () => []),
  249. getSessionRewindPreview: vi.fn(async () => ({ turns: [] })),
  250. rewindSession: vi.fn(async () => ({ rewound: true })),
  251. editSessionMessage: vi.fn(async () => ({
  252. rewound: true,
  253. turnId: "turn-edit-1",
  254. userMessageId: "msg-user-v1-edited",
  255. })),
  256. isGoalEnabled: vi.fn(() => true),
  257. getGoal: vi.fn(async () => currentGoal),
  258. createGoal: vi.fn(async ({ sessionId, objective, attachments }) => {
  259. currentGoal = {
  260. goalId: "goal-1",
  261. sessionId,
  262. objective,
  263. status: "active",
  264. createdAt: 10,
  265. updatedAt: 10,
  266. tokensUsed: 0,
  267. turnsUsed: 0,
  268. timeUsedSeconds: 0,
  269. tokenBudget: null,
  270. statusReason: null,
  271. hasKickoffAttachments: Boolean(attachments?.length),
  272. };
  273. return currentGoal;
  274. }),
  275. patchGoal: vi.fn(async (_sessionId, patch) => {
  276. if (!currentGoal) throw new Error("Goal not found");
  277. currentGoal = {
  278. ...currentGoal,
  279. ...patch,
  280. updatedAt: currentGoal.updatedAt + 1,
  281. };
  282. return currentGoal;
  283. }),
  284. clearGoal: vi.fn(async () => {
  285. const existed = Boolean(currentGoal);
  286. currentGoal = undefined;
  287. return existed;
  288. }),
  289. getInstructionSources: vi.fn(async () => []),
  290. getRuntimeDiagnostics: vi.fn(async () => ({
  291. status: "ok",
  292. surface: "cli-standalone",
  293. runtimeMode: "clean",
  294. runtimeOwnerKind: "cli",
  295. runtimeOwnerId: "minimax-code",
  296. dataDir: "/home/dev/.minimax",
  297. configPath: "/home/dev/.minimax/config.yaml",
  298. configPresent: true,
  299. authCachePresent: true,
  300. defaultModel: "minimax/MiniMax-M2.7",
  301. providerId: "minimax",
  302. modelId: "MiniMax-M2.7",
  303. authMode: "managed-login",
  304. authModeSource: "explicit",
  305. managedTokenPresent: true,
  306. apiKeyPresent: false,
  307. customProviderCount: 0,
  308. warnings: [],
  309. })),
  310. prepareFeedback: vi.fn(async ({ description, sessionId }) => ({
  311. schemaVersion: 1 as const,
  312. draftId: "feedback-draft-1",
  313. description,
  314. diagnostics: [
  315. { label: "Client", value: "mcode 0.1.0" },
  316. { label: "Runtime", value: "clean · cli" },
  317. { label: "Session", value: sessionId ?? "not included" },
  318. ],
  319. included: ["redacted feedback description"],
  320. excluded: ["credentials and tokens", "conversation prompts and messages"],
  321. expiresAtMs: Date.now() + 60_000,
  322. })),
  323. submitFeedback: vi.fn(async () => ({
  324. schemaVersion: 1 as const,
  325. ticketId: "ticket-1",
  326. status: "processing" as const,
  327. createdAtMs: Date.now(),
  328. })),
  329. cancelFeedback: vi.fn(async () => true),
  330. runDailyCheckin: vi.fn(async () => ({
  331. status: "claimed" as const,
  332. dayNo: 2,
  333. points: 20,
  334. expireAtMs: 1_800_000_000_000,
  335. panel: {
  336. scene: 2,
  337. days: Array.from({ length: 7 }, (_, index) => ({
  338. day_no: index + 1,
  339. points: (index + 1) * 10,
  340. status: index <= 1 ? 3 : 1,
  341. is_today: index === 1,
  342. })),
  343. },
  344. })),
  345. getAccountStatus: vi.fn(async () => ({
  346. status: "ready",
  347. defaultModel: "minimax/MiniMax-M2.7",
  348. providerId: "minimax",
  349. modelId: "MiniMax-M2.7",
  350. authMode: "managed-login",
  351. managedTokenPresent: true,
  352. warnings: [],
  353. })),
  354. listProviderPresets: vi.fn(async () => []),
  355. getCodexOAuthStatus: vi.fn(async () => ({
  356. state: "hidden" as const,
  357. providerId: "openai-codex" as const,
  358. })),
  359. startCodexOAuthLogin: vi.fn(async () => ({
  360. state: "hidden" as const,
  361. providerId: "openai-codex" as const,
  362. })),
  363. getPermissionMode: vi.fn(async () => "auto" as const),
  364. setPermissionMode: vi.fn(async (mode) => mode),
  365. getPlanModeCapabilities: vi.fn(async () => ({ entryEnabled: true })),
  366. getPendingQuestionnaire: vi.fn(async () => undefined),
  367. getLatestPlanReview: vi.fn(async () => undefined),
  368. replyQuestionnaire: vi.fn(async () => true),
  369. dismissQuestionnaire: vi.fn(async () => true),
  370. listPendingPermissions: vi.fn(async () => []),
  371. replyPermission: vi.fn(async () => true),
  372. listModels: vi.fn(async () => [
  373. {
  374. providerId: "minimax",
  375. modelId: "MiniMax-M2.7",
  376. displayName: "MiniMax M2.7",
  377. providerKind: "minimax-managed",
  378. selected: true,
  379. },
  380. ]),
  381. selectModel: vi.fn(async () => true),
  382. getSessionUsage: vi.fn(async () => ({
  383. summary: {
  384. inputTokens: 100,
  385. outputTokens: 20,
  386. totalTokens: 120,
  387. turns: 1,
  388. },
  389. rows: [],
  390. })),
  391. requestCompaction: vi.fn(async () => ({
  392. success: true,
  393. sessionId: "session-1",
  394. compactionId: "compact-1",
  395. messagesBefore: 12,
  396. messagesAfter: 4,
  397. tokensBefore: 4000,
  398. tokensAfter: 1200,
  399. })),
  400. getContextSnapshot: vi.fn(async () => ({ status: "empty" as const })),
  401. getActiveRun: vi.fn(async (sessionId: string) => ({
  402. schemaVersion: 1 as const,
  403. sessionId,
  404. state: "idle" as const,
  405. actions: { steer: false },
  406. })),
  407. getDelegationSnapshot: vi.fn(async (rootSessionId: string) => ({
  408. schemaVersion: 1 as const,
  409. rootSessionId,
  410. members: [],
  411. })),
  412. stopDelegation: vi.fn(async (rootSessionId: string) => ({
  413. schemaVersion: 1 as const,
  414. rootSessionId,
  415. rootStopped: await abortSession({ id: rootSessionId }),
  416. stoppedSessionIds: [],
  417. activeSessionIds: [],
  418. failedSessionIds: [],
  419. })),
  420. steer: vi.fn(async (input) => ({
  421. turnId: input.requestedTurnId ?? "turn-steer",
  422. mode: input.requestedTurnId
  423. ? ("steered" as const)
  424. : ("activated" as const),
  425. ...(input.requestedTurnId
  426. ? {}
  427. : {
  428. completion:
  429. (async function* completion(): AsyncGenerator<TuiStreamEvent> {
  430. yield { type: "done", turnId: "turn-steer" };
  431. })(),
  432. }),
  433. })),
  434. listSkills: vi.fn(async () => ({
  435. skills: [
  436. {
  437. name: "docs",
  438. displayName: "Docs",
  439. description: "Read project docs",
  440. enabled: true,
  441. sourceKind: "builtin",
  442. },
  443. ],
  444. hasMore: false,
  445. })),
  446. inspectProjectMcp: vi.fn(async () => undefined),
  447. listMcpServers: vi.fn(async () => [
  448. {
  449. name: "browser",
  450. enabled: true,
  451. transport: "stdio",
  452. description: "Browser tools",
  453. configJson: '{"env":{"TOKEN":"hidden"}}',
  454. },
  455. ]),
  456. listQueuedMessages: vi.fn(async () => []),
  457. getQueueSnapshot: vi.fn(async (sessionId: string) => {
  458. const items = await runtime.listQueuedMessages(sessionId);
  459. return {
  460. items,
  461. paused: items.some((item) => item.status === "paused"),
  462. pendingCount: items.length,
  463. };
  464. }),
  465. continueQueue: vi.fn(async () => undefined),
  466. steerQueuedMessage: vi.fn(async (_sessionId: string, itemId: string) => ({
  467. queueItemId: itemId,
  468. turnId: "turn-steered-queue",
  469. })),
  470. enqueueMessage: vi.fn(async () => ({
  471. itemId: "queue-1",
  472. status: "queued",
  473. position: 1,
  474. })),
  475. updateQueuedMessageContent: vi.fn(async () => undefined),
  476. deleteQueuedMessage: vi.fn(async () => undefined),
  477. watchEvents: vi.fn(async function* watchEvents(signal) {
  478. await new Promise<void>((resolve) => {
  479. signal.addEventListener("abort", resolve, { once: true });
  480. });
  481. for (const event of [] as TuiRuntimeEvent[]) yield event;
  482. }),
  483. watchSessionTurn: vi.fn(async function* watchSessionTurn() {}),
  484. sendMessage: vi.fn(
  485. async function* sendMessage(request): AsyncGenerator<TuiStreamEvent> {
  486. if (createdSession?.sessionId === request.id) {
  487. if (request.clientIntent === "plan-entry")
  488. createdSession.interactionMode = "plan";
  489. if (request.clientIntent === "plan-exit")
  490. delete createdSession.interactionMode;
  491. }
  492. yield { type: "delta", content: "Hello from the Agent" };
  493. yield { type: "done" };
  494. },
  495. ),
  496. abortSession,
  497. };
  498. return runtime;
  499. }
  500. describe("createTuiApp", () => {
  501. it.each(["regular", "fullscreen"] as const)(
  502. "configures /statusline from terminal input and reopens the saved selection in %s mode",
  503. async (tuiMode) => {
  504. const terminal = new FakeTerminal();
  505. const runtime = createRuntime();
  506. const persistStatusLineItems = vi.fn(async () => undefined);
  507. const app = createTuiApp({
  508. runtime,
  509. terminal,
  510. version: "test",
  511. workspaceDir: "/workspace",
  512. tuiMode,
  513. statusLineItems: ["current-dir"],
  514. persistStatusLineItems,
  515. });
  516. try {
  517. app.start();
  518. await app.ready;
  519. app.editor.setText("/statusline");
  520. terminal.input?.("\r");
  521. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  522. expect(stripAnsi(app.interaction.render(80).join("\n"))).toContain(
  523. "[x] current-dir",
  524. );
  525. terminal.input?.(" ");
  526. terminal.input?.("\r");
  527. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  528. expect(persistStatusLineItems).toHaveBeenCalledWith([]);
  529. app.editor.setText("/statusline");
  530. terminal.input?.("\r");
  531. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  532. expect(stripAnsi(app.interaction.render(80).join("\n"))).toContain(
  533. "[ ] current-dir",
  534. );
  535. terminal.input?.("\x1b");
  536. expect(app.interaction.isActive()).toBe(false);
  537. expect(persistStatusLineItems).toHaveBeenCalledOnce();
  538. expect(runtime.sendMessage).not.toHaveBeenCalled();
  539. } finally {
  540. await app.stop();
  541. }
  542. },
  543. );
  544. it.each([
  545. ["regular", false],
  546. ["regular", true],
  547. ["fullscreen", false],
  548. ["fullscreen", true],
  549. ] as const)(
  550. "runs ls unchanged in %s mode after empty-prefix Tab: %s",
  551. async (tuiMode, pressTab) => {
  552. const directory = await mkdtemp(join(tmpdir(), "tui-ls-enter-"));
  553. await mkdir(join(directory, "aaa-directory"));
  554. await writeFile(join(directory, "root-only.txt"), "root");
  555. const terminal = new FakeTerminal();
  556. const runtime = createRuntime();
  557. const app = createTuiApp({
  558. runtime,
  559. terminal,
  560. version: "0.1.0",
  561. workspaceDir: directory,
  562. tuiMode,
  563. });
  564. try {
  565. app.start();
  566. await app.ready;
  567. app.editor.setText("!ls");
  568. terminal.input?.(" ");
  569. expect(stripAnsi(app.editor.render(100).join("\n"))).not.toContain(
  570. "aaa-directory/",
  571. );
  572. if (pressTab) {
  573. terminal.input?.("\t");
  574. await vi.waitFor(() =>
  575. expect(stripAnsi(app.editor.render(100).join("\n"))).toContain(
  576. "aaa-directory/",
  577. ),
  578. );
  579. }
  580. expect(app.editor.getText()).toBe("!ls ");
  581. terminal.input?.("\r");
  582. await vi.waitFor(
  583. () =>
  584. expect(
  585. app.transcript.snapshot().find((cell) => cell.kind === "shell")
  586. ?.status,
  587. ).toBe("succeeded"),
  588. { timeout: 5000 },
  589. );
  590. expect(
  591. app.transcript.snapshot().find((cell) => cell.kind === "shell"),
  592. ).toMatchObject({
  593. title: "! ls",
  594. content: expect.stringContaining("root-only.txt"),
  595. });
  596. expect(runtime.sendMessage).not.toHaveBeenCalled();
  597. } finally {
  598. await app.stop();
  599. await rm(directory, { recursive: true, force: true });
  600. }
  601. },
  602. );
  603. it.each(["regular", "fullscreen"] as const)(
  604. "completes a shell path from terminal input in %s mode before executing",
  605. async (tuiMode) => {
  606. const directory = await mkdtemp(
  607. join(tmpdir(), "tui-shell-completion-app-"),
  608. );
  609. await writeFile(
  610. join(directory, "report file.txt"),
  611. "completed-shell-output",
  612. );
  613. const terminal = new FakeTerminal();
  614. const runtime = createRuntime();
  615. const app = createTuiApp({
  616. runtime,
  617. terminal,
  618. version: "0.1.0",
  619. workspaceDir: directory,
  620. tuiMode,
  621. });
  622. try {
  623. app.start();
  624. await app.ready;
  625. app.editor.setText(
  626. process.platform === "win32" ? "!Get-Content " : "!cat ",
  627. );
  628. for (const char of "rep") terminal.input?.(char);
  629. expect(app.editor.getText()).toBe(
  630. process.platform === "win32" ? "!Get-Content rep" : "!cat rep",
  631. );
  632. terminal.input?.("\t");
  633. await vi.waitFor(() =>
  634. expect(app.editor.getText()).toBe(
  635. process.platform === "win32"
  636. ? "!Get-Content report` file.txt "
  637. : "!cat report\\ file.txt ",
  638. ),
  639. );
  640. expect(
  641. app.transcript
  642. .snapshot()
  643. .some((cell) => cell.id.startsWith("local:bash:")),
  644. ).toBe(false);
  645. terminal.input?.("\r");
  646. await vi.waitFor(
  647. () =>
  648. expect(
  649. app.transcript
  650. .snapshot()
  651. .some(
  652. (cell) =>
  653. cell.id.startsWith("local:bash:") &&
  654. cell.status === "succeeded" &&
  655. cell.content.includes("completed-shell-output"),
  656. ),
  657. ).toBe(true),
  658. { timeout: 5000 },
  659. );
  660. expect(runtime.sendMessage).not.toHaveBeenCalled();
  661. } finally {
  662. await app.stop();
  663. await rm(directory, { recursive: true, force: true });
  664. }
  665. },
  666. );
  667. it("runs an editor ! command locally and carries its result into the next model message", async () => {
  668. const directory = await mkdtemp(join(tmpdir(), "tui-bash-app-"));
  669. const runtime = createRuntime();
  670. const app = createTuiApp({
  671. runtime,
  672. terminal: new FakeTerminal(),
  673. version: "0.1.0",
  674. workspaceDir: directory,
  675. });
  676. try {
  677. await app.ready;
  678. app.editor.setText(
  679. process.platform === "win32"
  680. ? "!Write-Output shell-result"
  681. : "!printf shell-result",
  682. );
  683. app.editor.submit();
  684. await vi.waitFor(
  685. () =>
  686. expect(
  687. app.transcript
  688. .snapshot()
  689. .some(
  690. (cell) =>
  691. cell.id.startsWith("local:bash:") &&
  692. cell.status === "succeeded",
  693. ),
  694. ).toBe(true),
  695. { timeout: 5000 },
  696. );
  697. expect(runtime.sendMessage).not.toHaveBeenCalled();
  698. expect(
  699. app.transcript
  700. .snapshot()
  701. .find((cell) => cell.id.startsWith("local:bash:"))?.content,
  702. ).toContain("shell-result");
  703. expect(stripAnsi(app.tui.render(100).join("\n"))).toContain(
  704. "shell-result",
  705. );
  706. await app.submit("Explain the output");
  707. expect(runtime.sendMessage).toHaveBeenCalledWith(
  708. expect.objectContaining({
  709. content: expect.stringContaining("shell-result"),
  710. }),
  711. expect.anything(),
  712. );
  713. } finally {
  714. await app.stop();
  715. await rm(directory, { recursive: true, force: true });
  716. }
  717. });
  718. it("shows shell output before the command exits and drains it when the app stops", async () => {
  719. const directory = await mkdtemp(join(tmpdir(), "tui-bash-stream-"));
  720. const app = createTuiApp({
  721. runtime: createRuntime(),
  722. terminal: new FakeTerminal(),
  723. version: "0.1.0",
  724. workspaceDir: directory,
  725. });
  726. try {
  727. await app.ready;
  728. const running = app.submit(
  729. process.platform === "win32"
  730. ? "!Write-Output streamed-result; Start-Sleep -Seconds 30"
  731. : "!printf streamed-result; sleep 30",
  732. );
  733. await vi.waitFor(
  734. () =>
  735. expect(
  736. app.transcript
  737. .snapshot()
  738. .some(
  739. (cell) =>
  740. cell.status === "running" &&
  741. cell.content.includes("streamed-result"),
  742. ),
  743. ).toBe(true),
  744. { timeout: 5000 },
  745. );
  746. expect(stripAnsi(app.tui.render(100).join("\n"))).toContain(
  747. "streamed-result",
  748. );
  749. await app.stop();
  750. await running;
  751. expect(
  752. app.transcript
  753. .snapshot()
  754. .find((cell) => cell.id.startsWith("local:bash:"))?.status,
  755. ).toBe("cancelled");
  756. } finally {
  757. await app.stop();
  758. await rm(directory, { recursive: true, force: true });
  759. }
  760. });
  761. it("continues a restored paused Queue from its manager without sending a new message", async () => {
  762. const terminal = new FakeTerminal();
  763. const runtime = createRuntime();
  764. let paused = true;
  765. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  766. {
  767. itemId: "paused-follow-up",
  768. sessionId: "session-1",
  769. status: paused ? "paused" : "queued",
  770. content: "Existing queued work",
  771. },
  772. ]);
  773. vi.mocked(runtime.continueQueue).mockImplementation(async () => {
  774. paused = false;
  775. });
  776. const app = createTuiApp({
  777. runtime,
  778. terminal,
  779. version: "test",
  780. workspaceDir: "/workspace",
  781. productFeatures: { queue: true },
  782. });
  783. app.start();
  784. try {
  785. await app.ready;
  786. await app.openSession("session-1");
  787. await app.submit("/queue");
  788. expect(app.tui.render(120).join("\n")).toContain("c continue queue");
  789. terminal.input?.("c");
  790. await vi.waitFor(() =>
  791. expect(runtime.continueQueue).toHaveBeenCalledWith("session-1"),
  792. );
  793. await vi.waitFor(() =>
  794. expect(app.tui.render(120).join("\n")).toContain("Queue continued."),
  795. );
  796. expect(runtime.sendMessage).not.toHaveBeenCalled();
  797. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  798. expect(runtime.deleteQueuedMessage).not.toHaveBeenCalled();
  799. } finally {
  800. await app.stop();
  801. }
  802. });
  803. it.each(["keep", "clear", "cancel-enter", "cancel-escape"] as const)(
  804. "recovers a restored paused Queue when sending a message: %s",
  805. async (decision) => {
  806. const dataDir = await mkdtemp(join(tmpdir(), "tui-paused-queue-draft-"));
  807. const terminal = new FakeTerminal();
  808. const runtime = createRuntime();
  809. let items: TuiQueuedMessage[] = [
  810. {
  811. itemId: "paused-follow-up",
  812. sessionId: "session-1",
  813. status: "paused",
  814. content: "Existing queued work",
  815. },
  816. ];
  817. let emitQueueChange:
  818. | ((event: TuiRuntimeEvent | undefined) => void)
  819. | undefined;
  820. vi.mocked(runtime.watchEvents).mockImplementation(
  821. async function* (signal) {
  822. const event = await new Promise<TuiRuntimeEvent | undefined>(
  823. (resolve) => {
  824. emitQueueChange = resolve;
  825. signal.addEventListener("abort", () => resolve(undefined), {
  826. once: true,
  827. });
  828. },
  829. );
  830. if (!event || signal.aborted) return;
  831. yield event;
  832. if (!signal.aborted) {
  833. await new Promise<void>((resolve) => {
  834. signal.addEventListener("abort", () => resolve(), { once: true });
  835. });
  836. }
  837. },
  838. );
  839. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  840. ...items,
  841. ]);
  842. vi.mocked(runtime.sendMessage).mockImplementation(
  843. async function* (request, _signal, options) {
  844. if (!options?.pausedQueueAction) {
  845. throw new TuiFailure("runtime", "Queue paused", {
  846. code: "local_session_queue_paused",
  847. });
  848. }
  849. items =
  850. options.pausedQueueAction === "clear"
  851. ? []
  852. : items.map((item) => ({ ...item, status: "queued" }));
  853. emitQueueChange?.({
  854. type: "session.queue.updated",
  855. sessionId: "session-1",
  856. source: "runtime-v2",
  857. timestampMs: Date.now(),
  858. });
  859. yield { type: "done", turnId: request.turnId };
  860. },
  861. );
  862. const appOptions = {
  863. runtime,
  864. terminal,
  865. version: "test",
  866. dataDir,
  867. workspaceDir: "/workspace",
  868. productFeatures: { queue: true },
  869. };
  870. let app = createTuiApp(appOptions);
  871. app.start();
  872. try {
  873. await app.ready;
  874. await app.openSession("session-1");
  875. await vi.waitFor(() => expect(emitQueueChange).toBeTypeOf("function"));
  876. await vi.waitFor(() =>
  877. expect(app.tui.render(120).join("\n")).toContain(
  878. "Existing queued work",
  879. ),
  880. );
  881. terminal.input?.("Resume safely");
  882. terminal.input?.("\r");
  883. await vi.waitFor(() =>
  884. expect(app.tui.render(120).join("\n")).toContain("Keep my draft"),
  885. );
  886. const cancelled = decision.startsWith("cancel");
  887. if (decision === "cancel-escape") terminal.input?.("\u001b");
  888. else {
  889. if (decision === "clear") terminal.input?.("\u001b[B");
  890. if (decision === "cancel-enter") {
  891. terminal.input?.("\u001b[B");
  892. terminal.input?.("\u001b[B");
  893. }
  894. terminal.input?.("\r");
  895. }
  896. await vi.waitFor(() =>
  897. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  898. );
  899. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  900. if (cancelled) {
  901. await vi.waitFor(() =>
  902. expect(app.editor.getText()).toBe("Resume safely"),
  903. );
  904. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  905. expect(runtime.continueQueue).not.toHaveBeenCalled();
  906. expect(runtime.deleteQueuedMessage).not.toHaveBeenCalled();
  907. expect(
  908. app.transcript.snapshot().filter((cell) => cell.kind === "user"),
  909. ).toEqual([]);
  910. expect(
  911. app.transcript.snapshot().filter((cell) => cell.kind === "error"),
  912. ).toEqual([]);
  913. expect(app.tui.render(120).join("\n")).toContain("Queue paused");
  914. expect(app.tui.render(120).join("\n")).not.toContain("Keep my draft");
  915. await vi.waitFor(async () => {
  916. const recovered = await new TuiDraftRecovery({
  917. dataDir,
  918. workspaceDir: "/workspace",
  919. sessionKey: "session-1",
  920. }).load();
  921. expect(recovered?.editor.text).toBe("Resume safely");
  922. expect(recovered?.retrySubmissions ?? []).toEqual([]);
  923. });
  924. app.editor.setText("Edited draft");
  925. await app.stop();
  926. app = createTuiApp(appOptions);
  927. app.start();
  928. await app.ready;
  929. await app.openSession("session-1");
  930. await vi.waitFor(() =>
  931. expect(app.editor.getText()).toBe("Edited draft"),
  932. );
  933. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  934. terminal.input?.("\r");
  935. await vi.waitFor(() =>
  936. expect(app.tui.render(120).join("\n")).toContain("Keep my draft"),
  937. );
  938. terminal.input?.("\r");
  939. await vi.waitFor(() =>
  940. expect(runtime.sendMessage).toHaveBeenCalledTimes(3),
  941. );
  942. await vi.waitFor(() =>
  943. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  944. );
  945. expect(
  946. vi.mocked(runtime.sendMessage).mock.calls[2]?.[0],
  947. ).toMatchObject({
  948. content: "Edited draft",
  949. });
  950. expect(vi.mocked(runtime.sendMessage).mock.calls[2]?.[2]).toEqual({
  951. pausedQueueAction: "keep",
  952. });
  953. await vi.waitFor(() =>
  954. expect(app.tui.render(120).join("\n")).not.toContain(
  955. "Queue paused",
  956. ),
  957. );
  958. expect(app.editor.getText()).toBe("");
  959. expect(app.tui.render(120).join("\n")).toContain(
  960. "Existing queued work",
  961. );
  962. } else {
  963. expect(runtime.sendMessage).toHaveBeenCalledTimes(2);
  964. expect(
  965. vi.mocked(runtime.sendMessage).mock.calls[1]?.[0],
  966. ).toMatchObject({
  967. content: "Resume safely",
  968. });
  969. expect(vi.mocked(runtime.sendMessage).mock.calls[1]?.[2]).toEqual({
  970. pausedQueueAction: decision,
  971. });
  972. await vi.waitFor(() =>
  973. expect(app.tui.render(120).join("\n")).not.toContain(
  974. "Queue paused",
  975. ),
  976. );
  977. const rendered = app.tui.render(120).join("\n");
  978. if (decision === "clear")
  979. expect(rendered).not.toContain("Existing queued work");
  980. else expect(rendered).toContain("Existing queued work");
  981. }
  982. } finally {
  983. await app.stop();
  984. await rm(dataDir, { recursive: true, force: true });
  985. }
  986. },
  987. );
  988. it.each([
  989. ["plan-entry", "keep"],
  990. ["plan-entry", "clear"],
  991. ["plan-entry", "cancel"],
  992. ["plan-entry", "busy"],
  993. ["plan-exit", "keep"],
  994. ["plan-exit", "clear"],
  995. ["plan-exit", "cancel"],
  996. ["plan-exit", "busy"],
  997. ] as const)(
  998. "recovers a paused Queue with %s and decision %s",
  999. async (clientIntent, decision) => {
  1000. const terminal = new FakeTerminal();
  1001. const runtime = createRuntime();
  1002. let interactionMode: "plan" | undefined =
  1003. clientIntent === "plan-exit" ? "plan" : undefined;
  1004. let rejectRecovery = decision === "busy";
  1005. vi.mocked(runtime.getSession).mockImplementation(async () => ({
  1006. sessionId: "session-1",
  1007. interactionMode,
  1008. }));
  1009. vi.mocked(runtime.listQueuedMessages).mockResolvedValue([
  1010. {
  1011. itemId: "paused-work",
  1012. sessionId: "session-1",
  1013. status: "paused",
  1014. content: "Existing work",
  1015. },
  1016. ]);
  1017. vi.mocked(runtime.sendMessage).mockImplementation(
  1018. async function* (request, _signal, options) {
  1019. if (!options?.pausedQueueAction || rejectRecovery) {
  1020. throw new TuiFailure("runtime", "Admission rejected", {
  1021. code: options?.pausedQueueAction
  1022. ? "local_session_busy"
  1023. : "local_session_queue_paused",
  1024. });
  1025. }
  1026. interactionMode =
  1027. request.clientIntent === "plan-entry" ? "plan" : undefined;
  1028. yield { type: "done", turnId: request.turnId };
  1029. },
  1030. );
  1031. const app = createTuiApp({
  1032. runtime,
  1033. terminal,
  1034. version: "test",
  1035. workspaceDir: "/workspace",
  1036. productFeatures: { queue: true },
  1037. });
  1038. app.start();
  1039. try {
  1040. await app.ready;
  1041. await app.openSession("session-1");
  1042. await app.submit(
  1043. clientIntent === "plan-entry" ? "/plan on" : "/plan off",
  1044. );
  1045. terminal.input?.("Change mode and continue");
  1046. terminal.input?.("\r");
  1047. await vi.waitFor(() =>
  1048. expect(app.tui.render(120).join("\n")).toContain("Keep my draft"),
  1049. );
  1050. if (decision === "clear" || decision === "cancel")
  1051. terminal.input?.("\u001b[B");
  1052. if (decision === "cancel") terminal.input?.("\u001b[B");
  1053. terminal.input?.("\r");
  1054. await vi.waitFor(() =>
  1055. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  1056. );
  1057. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  1058. if (decision === "cancel" || decision === "busy") {
  1059. await vi.waitFor(() =>
  1060. expect(app.editor.getText()).toBe("Change mode and continue"),
  1061. );
  1062. expect(interactionMode === "plan").toBe(clientIntent === "plan-exit");
  1063. rejectRecovery = false;
  1064. app.editor.setText("Edited mode instruction");
  1065. terminal.input?.("\r");
  1066. await vi.waitFor(() =>
  1067. expect(app.tui.render(120).join("\n")).toContain("Keep my draft"),
  1068. );
  1069. terminal.input?.("\r");
  1070. await vi.waitFor(() =>
  1071. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  1072. );
  1073. }
  1074. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  1075. expect.objectContaining({ clientIntent }),
  1076. expect.any(AbortSignal),
  1077. { pausedQueueAction: decision === "clear" ? "clear" : "keep" },
  1078. );
  1079. expect(interactionMode === "plan").toBe(clientIntent === "plan-entry");
  1080. expect(app.editor.getText()).toBe("");
  1081. } finally {
  1082. await app.stop();
  1083. }
  1084. },
  1085. );
  1086. it("shows the MCode prompt in an empty Composer and hides it after input", async () => {
  1087. const app = createTuiApp({
  1088. runtime: createRuntime(),
  1089. terminal: new FakeTerminal(),
  1090. version: "0.1.0",
  1091. workspaceDir: "/workspace",
  1092. });
  1093. try {
  1094. app.start();
  1095. await app.ready;
  1096. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  1097. "Ask Mcode to do anything",
  1098. );
  1099. app.editor.handleInput("R");
  1100. expect(stripAnsi(app.tui.render(80).join("\n"))).not.toContain(
  1101. "Ask Mcode to do anything",
  1102. );
  1103. expect(app.editor.getText()).toBe("R");
  1104. } finally {
  1105. await app.stop();
  1106. }
  1107. });
  1108. it("copies the last Assistant reply to the client clipboard over SSH", async () => {
  1109. vi.stubEnv("SSH_CONNECTION", "10.0.0.1 50100 10.0.0.2 22");
  1110. vi.stubEnv("SSH_TTY", "/dev/pts/1");
  1111. Object.defineProperty(process.stdin, "isTTY", {
  1112. configurable: true,
  1113. value: true,
  1114. });
  1115. Object.defineProperty(process.stdout, "isTTY", {
  1116. configurable: true,
  1117. value: true,
  1118. });
  1119. const terminal = new FakeTerminal();
  1120. let app: ReturnType<typeof createTuiApp> | undefined;
  1121. try {
  1122. app = createTuiApp({
  1123. runtime: createRuntime(),
  1124. terminal,
  1125. version: "0.1.0",
  1126. workspaceDir: "/workspace",
  1127. });
  1128. app.start();
  1129. await app.ready;
  1130. await app.submit("Say hello");
  1131. await app.submit("/copy");
  1132. expect(terminal.writes).toContain(
  1133. "\u001B]52;c;SGVsbG8gZnJvbSB0aGUgQWdlbnQ=\u0007",
  1134. );
  1135. } finally {
  1136. await app?.stop();
  1137. Reflect.deleteProperty(process.stdin, "isTTY");
  1138. Reflect.deleteProperty(process.stdout, "isTTY");
  1139. vi.unstubAllEnvs();
  1140. }
  1141. });
  1142. it("runs /goal through Runtime ownership and renders the active Goal above the Composer", async () => {
  1143. const runtime = createRuntime();
  1144. const app = createTuiApp({
  1145. runtime,
  1146. terminal: new FakeTerminal(),
  1147. version: "0.1.0",
  1148. workspaceDir: "/workspace",
  1149. });
  1150. app.start();
  1151. await app.ready;
  1152. await app.submit("/goal Ship TUI Goal support");
  1153. expect(runtime.createSession).toHaveBeenCalledOnce();
  1154. expect(runtime.createGoal).toHaveBeenCalledWith({
  1155. sessionId: "session-1",
  1156. objective: "Ship TUI Goal support",
  1157. });
  1158. expect(runtime.sendMessage).not.toHaveBeenCalled();
  1159. expect(app.surfaceHost.render(100).join("\n")).toContain("Goal · Active");
  1160. expect(app.surfaceHost.render(100).join("\n")).toContain(
  1161. "Ship TUI Goal support",
  1162. );
  1163. await app.submit("/goal pause");
  1164. expect(runtime.patchGoal).toHaveBeenCalledWith("session-1", {
  1165. status: "paused",
  1166. });
  1167. expect(app.surfaceHost.render(100).join("\n")).toContain("Goal · Paused");
  1168. await app.stop();
  1169. });
  1170. it("wires complete chat and autocomplete business events into the TUI surface", async () => {
  1171. const events: McodeBusinessEvent[] = [];
  1172. const businessTelemetry: McodeBusinessTelemetry = {
  1173. track: (event, properties) =>
  1174. events.push({ event, properties } as McodeBusinessEvent),
  1175. flush: async () => undefined,
  1176. };
  1177. const app = createTuiApp({
  1178. runtime: createRuntime(),
  1179. terminal: new FakeTerminal(),
  1180. version: "0.1.0",
  1181. workspaceDir: "/workspace/agent-archon",
  1182. businessTelemetry,
  1183. });
  1184. await app.ready;
  1185. await app.submit("First prompt");
  1186. await app.submit("Second prompt");
  1187. for (const character of "/he") app.editor.handleInput(character);
  1188. await vi.waitFor(() =>
  1189. expect(
  1190. events.some((item) => item.event === "slash_command_menu_view"),
  1191. ).toBe(true),
  1192. );
  1193. app.editor.handleInput("\r");
  1194. expect(events.filter((item) => item.event === "chat_send")).toEqual([
  1195. {
  1196. event: "chat_send",
  1197. properties: {
  1198. chat_type: "chat",
  1199. is_first_message: 1,
  1200. is_attachment: "text",
  1201. },
  1202. },
  1203. {
  1204. event: "chat_send",
  1205. properties: {
  1206. chat_type: "chat",
  1207. is_first_message: 0,
  1208. is_attachment: "text",
  1209. },
  1210. },
  1211. ]);
  1212. expect(events).toContainEqual({
  1213. event: "slash_command_click",
  1214. properties: {
  1215. chat_type: "chat",
  1216. command_type: "other",
  1217. },
  1218. });
  1219. await app.stop();
  1220. });
  1221. it("releases the terminal on suspend and reconciles Runtime state after resume", async () => {
  1222. const terminal = new FakeTerminal();
  1223. const runtime = createRuntime();
  1224. const requestProcessSuspend = vi.fn();
  1225. vi.mocked(runtime.watchEvents).mockImplementation(
  1226. async function* watchEvents(signal) {
  1227. await new Promise<void>((resolve) => {
  1228. signal.addEventListener("abort", resolve, { once: true });
  1229. });
  1230. yield* [];
  1231. },
  1232. );
  1233. const app = createTuiApp({
  1234. runtime,
  1235. terminal,
  1236. version: "0.1.0",
  1237. workspaceDir: "/workspace",
  1238. requestProcessSuspend,
  1239. });
  1240. app.start();
  1241. await app.ready;
  1242. await app.openSession("session-1");
  1243. await vi.waitFor(() => expect(runtime.watchEvents).toHaveBeenCalledOnce());
  1244. terminal.input?.("\x1a");
  1245. expect(requestProcessSuspend).toHaveBeenCalledOnce();
  1246. await app.suspend();
  1247. expect(terminal.stopCount).toBe(1);
  1248. expect(app.controller.snapshot().status).not.toBe("error");
  1249. await app.resume();
  1250. expect(terminal.startCount).toBe(2);
  1251. await vi.waitFor(() =>
  1252. expect(runtime.watchEvents).toHaveBeenCalledTimes(2),
  1253. );
  1254. expect(runtime.getActiveRun).toHaveBeenCalled();
  1255. await app.stop();
  1256. });
  1257. it.each(["regular", "fullscreen"] as const)(
  1258. "restores %s Composer input after Ctrl+G returns from the external editor",
  1259. async (tuiMode) => {
  1260. const terminal = new FakeTerminal();
  1261. const stopTerminal = vi.spyOn(terminal, "stop");
  1262. const startTerminal = vi.spyOn(terminal, "start");
  1263. const editDraftInExternalEditor = vi.fn(
  1264. async () => "edited in the external editor",
  1265. );
  1266. const app = createTuiApp({
  1267. runtime: createRuntime(),
  1268. terminal,
  1269. version: "0.1.0",
  1270. workspaceDir: "/workspace",
  1271. tuiMode,
  1272. externalEditorCommand: "code --wait",
  1273. editDraftInExternalEditor,
  1274. });
  1275. app.start();
  1276. await app.ready;
  1277. const longPaste = Array.from(
  1278. { length: 12 },
  1279. (_, index) => `line ${String(index + 1)}`,
  1280. ).join("\n");
  1281. terminal.input?.(`\x1b[200~${longPaste}\x1b[201~`);
  1282. expect(app.editor.getText()).toBe("[paste #1 +12 lines]");
  1283. terminal.input?.("\x07");
  1284. await vi.waitFor(() =>
  1285. expect(editDraftInExternalEditor).toHaveBeenCalledOnce(),
  1286. );
  1287. expect(editDraftInExternalEditor).toHaveBeenCalledWith({
  1288. command: "code --wait",
  1289. draft: longPaste,
  1290. cwd: "/workspace",
  1291. });
  1292. await vi.waitFor(() =>
  1293. expect(app.editor.getText()).toBe("edited in the external editor"),
  1294. );
  1295. expect(stopTerminal).toHaveBeenCalledOnce();
  1296. expect(startTerminal).toHaveBeenCalledTimes(2);
  1297. terminal.input?.("!");
  1298. expect(app.editor.getText()).toBe("edited in the external editor!");
  1299. await app.stop();
  1300. },
  1301. );
  1302. it("loads Runtime-owned Git context into the status rail without blocking startup", async () => {
  1303. const runtime = createRuntime();
  1304. vi.mocked(runtime.getWorkspaceGitMetadata).mockResolvedValue({
  1305. isGitRepo: true,
  1306. branch: "feat/status-context",
  1307. detached: false,
  1308. isWorktree: true,
  1309. });
  1310. const app = createTuiApp({
  1311. runtime,
  1312. terminal: new FakeTerminal(),
  1313. version: "0.1.0",
  1314. workspaceDir: "/Users/dev/github/agent-archon",
  1315. homeDir: "/Users/dev",
  1316. });
  1317. await app.ready;
  1318. await vi.waitFor(() => {
  1319. expect(runtime.getWorkspaceGitMetadata).toHaveBeenCalledWith(
  1320. "/Users/dev/github/agent-archon",
  1321. );
  1322. const rendered = app.tui.render(120).join("\n");
  1323. expect(rendered).toContain("~/github/agent-archon");
  1324. expect(rendered).toContain("⎇ feat/status-context · worktree");
  1325. });
  1326. await app.stop();
  1327. });
  1328. it("keeps Pi clear-on-shrink disabled for the inline product by default", async () => {
  1329. const app = createTuiApp({
  1330. runtime: createRuntime(),
  1331. terminal: new FakeTerminal(),
  1332. version: "0.1.0",
  1333. workspaceDir: "/workspace",
  1334. });
  1335. expect(app.tui.getClearOnShrink()).toBe(false);
  1336. await app.ready;
  1337. await app.stop();
  1338. });
  1339. it("drains Pi terminal input before restoring the terminal on shutdown", async () => {
  1340. const terminal = new FakeTerminal();
  1341. const drainInput = vi.spyOn(terminal, "drainInput");
  1342. const stopTerminal = vi.spyOn(terminal, "stop");
  1343. const app = createTuiApp({
  1344. runtime: createRuntime(),
  1345. terminal,
  1346. version: "0.1.0",
  1347. workspaceDir: "/workspace",
  1348. });
  1349. app.start();
  1350. await app.ready;
  1351. await app.stop();
  1352. expect(drainInput).toHaveBeenCalledWith(1000);
  1353. expect(stopTerminal).toHaveBeenCalledOnce();
  1354. expect(drainInput.mock.invocationCallOrder[0]).toBeLessThan(
  1355. stopTerminal.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
  1356. );
  1357. });
  1358. it("shows the Runtime initialization error text when the Session catalog is unavailable", async () => {
  1359. const runtime = createRuntime();
  1360. vi.mocked(runtime.listSessions).mockRejectedValue(
  1361. new Error("Unable to connect to the Runtime on port 1234"),
  1362. );
  1363. const app = createTuiApp({
  1364. runtime,
  1365. terminal: new FakeTerminal(),
  1366. version: "0.1.0",
  1367. workspaceDir: "/workspace",
  1368. });
  1369. await app.ready;
  1370. expect(app.controller.snapshot()).toMatchObject({
  1371. status: "error",
  1372. error:
  1373. "Couldn't load sessions: Unable to connect to the Runtime on port 1234. Retry.",
  1374. sessions: [],
  1375. });
  1376. expect(app.tui.render(80).join("\n")).toContain(
  1377. "Error · Couldn't load sessions:",
  1378. );
  1379. await app.stop();
  1380. });
  1381. it("shows an available update as a dedicated startup notice", async () => {
  1382. const terminal = new FakeTerminal();
  1383. const checkForUpdate = vi.fn(async () => ({ latestVersion: "1.2.4" }));
  1384. const app = createTuiApp({
  1385. runtime: createRuntime(),
  1386. terminal,
  1387. version: "1.2.3",
  1388. workspaceDir: "/workspace",
  1389. checkForUpdate,
  1390. });
  1391. app.start();
  1392. await app.ready;
  1393. await vi.waitFor(() => {
  1394. expect(terminal.writes.join("")).toContain(
  1395. "A new version of MCode is available",
  1396. );
  1397. });
  1398. const rendered = terminal.writes.join("");
  1399. expect(checkForUpdate).toHaveBeenCalledTimes(1);
  1400. expect(rendered).toContain("Run '/update' to install MCode 1.2.4");
  1401. await app.submit("Start working");
  1402. expect(app.getSurface()).toBe("conversation");
  1403. expect(app.tui.render(80).join("\n")).not.toContain(
  1404. "A new version of MCode is available",
  1405. );
  1406. await app.submit("/new");
  1407. expect(app.getSurface()).toBe("welcome");
  1408. expect(app.tui.render(80).join("\n")).toContain(
  1409. "A new version of MCode is available",
  1410. );
  1411. await app.stop();
  1412. });
  1413. it("keeps the Welcome handoff out of the primary hint and submits it on Ctrl+U", async () => {
  1414. const terminal = new FakeTerminal();
  1415. const runtime = createRuntime();
  1416. vi.mocked(runtime.listSkills).mockResolvedValue({
  1417. skills: [
  1418. {
  1419. name: "resume-codex",
  1420. displayName: "Resume Codex",
  1421. description: "Continue a Codex session",
  1422. enabled: true,
  1423. sourceKind: "builtin",
  1424. },
  1425. ],
  1426. hasMore: false,
  1427. });
  1428. const sessionId = "01a02373-25ae-76a1-880c-9253ba939cdc";
  1429. const findRecentCodexSession = vi.fn(async () => ({
  1430. sessionId,
  1431. updatedAtMs: Date.now() - 60_000,
  1432. source: "cli" as const,
  1433. }));
  1434. const app = createTuiApp({
  1435. runtime,
  1436. terminal,
  1437. version: "0.1.0",
  1438. workspaceDir: "/workspace",
  1439. findRecentCodexSession,
  1440. });
  1441. app.start();
  1442. await app.ready;
  1443. await vi.waitFor(() =>
  1444. expect(findRecentCodexSession).toHaveBeenCalledOnce(),
  1445. );
  1446. const welcome = app.tui.render(100).join("\n");
  1447. expect(welcome).toContain("Start");
  1448. expect(welcome).not.toContain("Coming from Codex?");
  1449. terminal.input?.("\x15");
  1450. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
  1451. expect(runtime.sendMessage).toHaveBeenCalledWith(
  1452. expect.objectContaining({
  1453. id: "session-1",
  1454. content: `/resume-codex ${sessionId}`,
  1455. }),
  1456. expect.any(AbortSignal),
  1457. );
  1458. expect(app.tui.render(100).join("\n")).not.toContain("Coming from Codex?");
  1459. await app.stop();
  1460. });
  1461. it("invalidates an in-flight Codex handoff scan after the user starts typing", async () => {
  1462. const terminal = new FakeTerminal();
  1463. const runtime = createRuntime();
  1464. vi.mocked(runtime.listSkills).mockResolvedValue({
  1465. skills: [
  1466. {
  1467. name: "resume-codex",
  1468. displayName: "Resume Codex",
  1469. description: "Continue a Codex session",
  1470. enabled: true,
  1471. sourceKind: "builtin",
  1472. },
  1473. ],
  1474. hasMore: false,
  1475. });
  1476. let resolveRecent:
  1477. | ((session: {
  1478. sessionId: string;
  1479. updatedAtMs: number;
  1480. source: "cli";
  1481. }) => void)
  1482. | undefined;
  1483. const findRecentCodexSession = vi.fn(
  1484. async () =>
  1485. await new Promise<{
  1486. sessionId: string;
  1487. updatedAtMs: number;
  1488. source: "cli";
  1489. }>((resolve) => {
  1490. resolveRecent = resolve;
  1491. }),
  1492. );
  1493. const app = createTuiApp({
  1494. runtime,
  1495. terminal,
  1496. version: "0.1.0",
  1497. workspaceDir: "/workspace",
  1498. findRecentCodexSession,
  1499. });
  1500. app.start();
  1501. terminal.input?.("x");
  1502. await vi.waitFor(() =>
  1503. expect(findRecentCodexSession).toHaveBeenCalledOnce(),
  1504. );
  1505. resolveRecent?.({
  1506. sessionId: "01a02373-25ae-76a1-880c-9253ba939cdc",
  1507. updatedAtMs: Date.now(),
  1508. source: "cli",
  1509. });
  1510. await Promise.resolve();
  1511. await Promise.resolve();
  1512. expect(app.editor.getText()).toBe("x");
  1513. expect(app.tui.render(100).join("\n")).not.toContain("Coming from Codex?");
  1514. await app.stop();
  1515. });
  1516. it("does not inspect Codex storage when the resume Skill is unavailable", async () => {
  1517. const runtime = createRuntime();
  1518. const findRecentCodexSession = vi.fn(async () => ({
  1519. sessionId: "01a02373-25ae-76a1-880c-9253ba939cdc",
  1520. updatedAtMs: Date.now(),
  1521. source: "cli" as const,
  1522. }));
  1523. const app = createTuiApp({
  1524. runtime,
  1525. terminal: new FakeTerminal(),
  1526. version: "0.1.0",
  1527. workspaceDir: "/workspace",
  1528. findRecentCodexSession,
  1529. });
  1530. app.start();
  1531. await app.ready;
  1532. await vi.waitFor(() => expect(runtime.listSkills).toHaveBeenCalledOnce());
  1533. await Promise.resolve();
  1534. expect(findRecentCodexSession).not.toHaveBeenCalled();
  1535. expect(app.tui.render(100).join("\n")).not.toContain("Coming from Codex?");
  1536. await app.stop();
  1537. });
  1538. it.each(["unsupported result", "blank version", "rejected check"] as const)(
  1539. "keeps a %s startup update result out of the notice and transcript",
  1540. async (scenario) => {
  1541. const terminal = new FakeTerminal();
  1542. const checkForUpdate = vi.fn(async () => {
  1543. if (scenario === "rejected check")
  1544. throw new Error("registry unavailable");
  1545. if (scenario === "unsupported result") return undefined;
  1546. return { latestVersion: " " };
  1547. });
  1548. const app = createTuiApp({
  1549. runtime: createRuntime(),
  1550. terminal,
  1551. version: "1.2.3",
  1552. workspaceDir: "/workspace",
  1553. checkForUpdate,
  1554. });
  1555. app.start();
  1556. await app.ready;
  1557. await vi.waitFor(() => expect(checkForUpdate).toHaveBeenCalledOnce());
  1558. await app.stop();
  1559. expect(terminal.writes.join("")).not.toContain(
  1560. "A new version of MCode is available",
  1561. );
  1562. expect(
  1563. app.transcript.snapshot().filter((cell) => cell.kind === "error"),
  1564. ).toEqual([]);
  1565. },
  1566. );
  1567. it("routes /update through the in-process update confirmation flow", async () => {
  1568. const plan = {
  1569. kind: "available" as const,
  1570. source: "managed-installer" as const,
  1571. currentVersion: "1.2.3",
  1572. latestVersion: "1.2.4",
  1573. channel: "stable" as const,
  1574. };
  1575. const inspectUpdate = vi.fn(async () => plan);
  1576. const applyUpdate = vi.fn(async () => ({
  1577. applied: true,
  1578. message:
  1579. "MCode 1.2.4 is installed. Restart running MCode sessions to use it.",
  1580. }));
  1581. const app = createTuiApp({
  1582. runtime: createRuntime(),
  1583. terminal: new FakeTerminal(),
  1584. version: "1.2.3",
  1585. workspaceDir: "/workspace",
  1586. inspectUpdate,
  1587. applyUpdate,
  1588. });
  1589. await app.ready;
  1590. await app.submit("/update");
  1591. expect(inspectUpdate).toHaveBeenCalledOnce();
  1592. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  1593. "MCode update",
  1594. );
  1595. app.interaction.current()?.handleInput?.("\r");
  1596. await vi.waitFor(() =>
  1597. expect(applyUpdate).toHaveBeenCalledWith(
  1598. plan,
  1599. expect.objectContaining({
  1600. onOutput: expect.any(Function),
  1601. }),
  1602. ),
  1603. );
  1604. await vi.waitFor(() =>
  1605. expect(
  1606. app.transcript
  1607. .snapshot()
  1608. .some((cell) => cell.content.includes("MCode update completed")),
  1609. ).toBe(true),
  1610. );
  1611. await app.stop();
  1612. });
  1613. it("leaves the current TUI after /update stages an npm-prefix replacement", async () => {
  1614. const plan = {
  1615. kind: "package-manager" as const,
  1616. source: "npm-prefix" as const,
  1617. currentVersion: "1.2.3",
  1618. latestVersion: "1.2.4",
  1619. packageTag: "latest" as const,
  1620. command: {
  1621. executable: "npm",
  1622. args: ["install"],
  1623. display: "npm install",
  1624. },
  1625. };
  1626. const requestRestart = vi.fn();
  1627. const app = createTuiApp({
  1628. runtime: createRuntime(),
  1629. terminal: new FakeTerminal(),
  1630. version: "1.2.3",
  1631. workspaceDir: "/workspace",
  1632. inspectUpdate: async () => plan,
  1633. applyUpdate: async () => ({
  1634. applied: true,
  1635. restartRequired: true,
  1636. message: "MCode 1.2.4 is staged safely.",
  1637. }),
  1638. requestRestart,
  1639. });
  1640. app.start();
  1641. await app.ready;
  1642. await app.submit("/update");
  1643. app.interaction.current()?.handleInput?.("\r");
  1644. await vi.waitFor(() => expect(requestRestart).toHaveBeenCalledOnce());
  1645. await app.stopped;
  1646. });
  1647. it("rechecks local and Runtime work before applying an update", async () => {
  1648. const runtime = createRuntime();
  1649. const applyUpdate = vi.fn(async () => ({
  1650. applied: true,
  1651. message: "updated",
  1652. }));
  1653. const app = createTuiApp({
  1654. runtime,
  1655. terminal: new FakeTerminal(),
  1656. version: "1.2.3",
  1657. workspaceDir: "/workspace",
  1658. inspectUpdate: async () => ({
  1659. kind: "available",
  1660. source: "managed-installer",
  1661. currentVersion: "1.2.3",
  1662. latestVersion: "1.2.4",
  1663. channel: "stable",
  1664. }),
  1665. applyUpdate,
  1666. });
  1667. await app.ready;
  1668. await app.openSession("session-1");
  1669. vi.mocked(runtime.getActiveRun).mockResolvedValue({
  1670. schemaVersion: 1,
  1671. sessionId: "session-1",
  1672. state: "running",
  1673. turnId: "turn-active",
  1674. actions: { steer: true },
  1675. });
  1676. await app.submit("/update");
  1677. app.interaction.current()?.handleInput?.("\r");
  1678. await vi.waitFor(() =>
  1679. expect(
  1680. app.transcript
  1681. .snapshot()
  1682. .some((cell) =>
  1683. cell.content.includes(
  1684. "MCode update failed: Finish or stop the active response before updating.",
  1685. ),
  1686. ),
  1687. ).toBe(true),
  1688. );
  1689. expect(applyUpdate).not.toHaveBeenCalled();
  1690. await app.stop();
  1691. });
  1692. it("fails the update gate closed when Runtime state cannot be verified", async () => {
  1693. const runtime = createRuntime();
  1694. const applyUpdate = vi.fn(async () => ({
  1695. applied: true,
  1696. message: "updated",
  1697. }));
  1698. const app = createTuiApp({
  1699. runtime,
  1700. terminal: new FakeTerminal(),
  1701. version: "1.2.3",
  1702. workspaceDir: "/workspace",
  1703. inspectUpdate: async () => ({
  1704. kind: "available",
  1705. source: "managed-installer",
  1706. currentVersion: "1.2.3",
  1707. latestVersion: "1.2.4",
  1708. channel: "stable",
  1709. }),
  1710. applyUpdate,
  1711. });
  1712. await app.ready;
  1713. await app.openSession("session-1");
  1714. vi.mocked(runtime.getActiveRun).mockRejectedValue(
  1715. new Error("Runtime unavailable"),
  1716. );
  1717. await app.submit("/update");
  1718. app.interaction.current()?.handleInput?.("\r");
  1719. await vi.waitFor(() =>
  1720. expect(
  1721. app.transcript
  1722. .snapshot()
  1723. .some((cell) =>
  1724. cell.content.includes("Unable to verify that this Session is idle"),
  1725. ),
  1726. ).toBe(true),
  1727. );
  1728. expect(applyUpdate).not.toHaveBeenCalled();
  1729. await app.stop();
  1730. });
  1731. it("does not expose the TUI before base hydration has settled", async () => {
  1732. const terminal = new FakeTerminal();
  1733. const runtime = createRuntime();
  1734. let releaseSessions: (() => void) | undefined;
  1735. vi.mocked(runtime.listSessions).mockImplementation(
  1736. async () =>
  1737. await new Promise((resolve) => {
  1738. releaseSessions = () => resolve([]);
  1739. }),
  1740. );
  1741. const app = createTuiApp({
  1742. runtime,
  1743. terminal,
  1744. version: "0.1.0",
  1745. workspaceDir: "/workspace",
  1746. });
  1747. let settled = false;
  1748. void app.ready.then(() => {
  1749. settled = true;
  1750. });
  1751. await Promise.resolve();
  1752. expect(settled).toBe(false);
  1753. releaseSessions?.();
  1754. await app.ready;
  1755. app.start();
  1756. const rendered = app.tui.render(80).join("\n");
  1757. expect(rendered).not.toContain("Starting MiniMax Code");
  1758. expect(rendered).not.toContain("Loading session");
  1759. await app.stop();
  1760. });
  1761. it("renders server startup in the welcome composer header until hydration settles", async () => {
  1762. const runtime = createRuntime();
  1763. let releaseSessions: (() => void) | undefined;
  1764. vi.mocked(runtime.listSessions).mockImplementation(
  1765. async () =>
  1766. await new Promise((resolve) => {
  1767. releaseSessions = () => resolve([]);
  1768. }),
  1769. );
  1770. const app = createTuiApp({
  1771. runtime,
  1772. terminal: new FakeTerminal(),
  1773. version: "0.1.0",
  1774. workspaceDir: "/workspace",
  1775. });
  1776. try {
  1777. app.setStartupStatus("⠋ Starting server...");
  1778. app.start();
  1779. const starting = app.tui.render(80).join("\n");
  1780. expect(starting).toContain("⠋ Starting server...");
  1781. expect(starting).not.toContain("Start · @ file · / autocomplete");
  1782. expect(starting).not.toContain("Loading session");
  1783. releaseSessions?.();
  1784. await app.ready;
  1785. app.setStartupStatus(undefined);
  1786. expect(app.tui.render(80).join("\n")).toContain(
  1787. "Start · @ file · / autocomplete",
  1788. );
  1789. } finally {
  1790. releaseSessions?.();
  1791. await app.stop();
  1792. }
  1793. });
  1794. it("waits for account hydration before allowing the first message", async () => {
  1795. const runtime = createRuntime();
  1796. let resolveAccount!: (
  1797. account: Awaited<ReturnType<typeof runtime.getAccountStatus>>,
  1798. ) => void;
  1799. vi.mocked(runtime.getAccountStatus).mockReturnValue(
  1800. new Promise((resolve) => {
  1801. resolveAccount = resolve;
  1802. }),
  1803. );
  1804. const app = createTuiApp({
  1805. runtime,
  1806. terminal: new FakeTerminal(),
  1807. version: "0.1.0",
  1808. workspaceDir: "/workspace",
  1809. });
  1810. try {
  1811. const readiness = await Promise.race([
  1812. app.ready.then(() => "ready" as const),
  1813. new Promise<"blocked">((resolve) =>
  1814. setTimeout(() => resolve("blocked"), 100),
  1815. ),
  1816. ]);
  1817. expect(readiness).toBe("blocked");
  1818. expect(runtime.createSession).not.toHaveBeenCalled();
  1819. resolveAccount({
  1820. status: "ready",
  1821. defaultModel: "minimax/MiniMax-M2.7",
  1822. managedTokenPresent: true,
  1823. warnings: [],
  1824. });
  1825. await app.ready;
  1826. const submission = app.submit("Send after account hydration");
  1827. await submission;
  1828. expect(runtime.createSession).toHaveBeenCalledWith({
  1829. workspaceDir: "/workspace",
  1830. });
  1831. expect(app.transcript.snapshot()).toEqual(
  1832. expect.arrayContaining([
  1833. expect.objectContaining({
  1834. kind: "user",
  1835. content: "Send after account hydration",
  1836. }),
  1837. expect.objectContaining({
  1838. kind: "assistant",
  1839. content: "Hello from the Agent",
  1840. }),
  1841. ]),
  1842. );
  1843. } finally {
  1844. resolveAccount({
  1845. status: "ready",
  1846. defaultModel: "minimax/MiniMax-M2.7",
  1847. managedTokenPresent: true,
  1848. warnings: [],
  1849. });
  1850. await app.ready;
  1851. await app.stop();
  1852. }
  1853. });
  1854. it("does not wait for Token Plan membership hydration before App readiness", async () => {
  1855. const runtime = createRuntime();
  1856. const baseAccount = {
  1857. status: "ready" as const,
  1858. defaultModel: "minimax/MiniMax-M2.7",
  1859. providerId: "minimax",
  1860. modelId: "MiniMax-M2.7",
  1861. authMode: "managed-login",
  1862. managedTokenPresent: true,
  1863. modelSource: "token-plan" as const,
  1864. warnings: [],
  1865. };
  1866. const hydratedAccount = {
  1867. ...baseAccount,
  1868. tokenPlanQuotaState: "available" as const,
  1869. tokenPlanQuota: {
  1870. fiveHour: { remainingPercent: 90, unlimited: false },
  1871. weekly: { remainingPercent: 80, unlimited: false },
  1872. },
  1873. };
  1874. let resolveMembership!: (account: typeof hydratedAccount) => void;
  1875. vi.mocked(runtime.getAccountStatus).mockImplementation(
  1876. async (_sessionId, options) => {
  1877. if (options?.includeMembership === true) {
  1878. return await new Promise((resolve) => {
  1879. resolveMembership = resolve;
  1880. });
  1881. }
  1882. return baseAccount;
  1883. },
  1884. );
  1885. const app = createTuiApp({
  1886. runtime,
  1887. terminal: new FakeTerminal(),
  1888. version: "0.1.0",
  1889. workspaceDir: "/workspace",
  1890. });
  1891. try {
  1892. await app.ready;
  1893. expect(runtime.getAccountStatus).toHaveBeenCalledWith(undefined, {
  1894. includeMembership: false,
  1895. });
  1896. expect(runtime.getAccountStatus).toHaveBeenCalledWith(undefined, {
  1897. includeMembership: true,
  1898. });
  1899. expect(app.controller.snapshot().account).toMatchObject(baseAccount);
  1900. resolveMembership(hydratedAccount);
  1901. await vi.waitFor(() =>
  1902. expect(app.controller.snapshot().account).toMatchObject({
  1903. tokenPlanQuotaState: "available",
  1904. }),
  1905. );
  1906. } finally {
  1907. resolveMembership(hydratedAccount);
  1908. await app.stop();
  1909. }
  1910. });
  1911. it("waits for permission mode hydration before reporting App readiness", async () => {
  1912. const runtime = createRuntime();
  1913. let resolvePermissionMode!: (mode: "auto") => void;
  1914. vi.mocked(runtime.getPermissionMode).mockReturnValue(
  1915. new Promise((resolve) => {
  1916. resolvePermissionMode = resolve;
  1917. }),
  1918. );
  1919. const app = createTuiApp({
  1920. runtime,
  1921. terminal: new FakeTerminal(),
  1922. version: "0.1.0",
  1923. workspaceDir: "/workspace",
  1924. });
  1925. const readiness = Promise.race([
  1926. app.ready.then(() => "ready" as const),
  1927. new Promise<"blocked">((resolve) =>
  1928. setTimeout(() => resolve("blocked"), 100),
  1929. ),
  1930. ]);
  1931. await expect(readiness).resolves.toBe("blocked");
  1932. resolvePermissionMode("auto");
  1933. await app.ready;
  1934. await app.stop();
  1935. });
  1936. it("accepts modeled account and optional permission degradation at the ready boundary", async () => {
  1937. const runtime = createRuntime();
  1938. vi.mocked(runtime.getAccountStatus).mockRejectedValue(
  1939. new Error("account offline"),
  1940. );
  1941. vi.mocked(runtime.getPermissionMode).mockRejectedValue(
  1942. new Error("config unavailable"),
  1943. );
  1944. const app = createTuiApp({
  1945. runtime,
  1946. terminal: new FakeTerminal(),
  1947. version: "0.1.0",
  1948. workspaceDir: "/workspace",
  1949. });
  1950. await expect(app.ready).resolves.toBeUndefined();
  1951. expect(app.controller.snapshot().account).toEqual({
  1952. status: "unknown",
  1953. warnings: [],
  1954. });
  1955. await app.stop();
  1956. });
  1957. it("hydrates the selected model display name into the status rail on startup", async () => {
  1958. const terminal = new FakeTerminal();
  1959. const runtime = createRuntime();
  1960. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  1961. status: "ready",
  1962. defaultModel: "custom_provider:innerTest/MiniMax-M3",
  1963. providerId: "custom_provider:innerTest",
  1964. modelId: "MiniMax-M3",
  1965. authMode: "byok",
  1966. managedTokenPresent: true,
  1967. warnings: [],
  1968. });
  1969. vi.mocked(runtime.listModels).mockResolvedValue([
  1970. {
  1971. providerId: "custom_provider:innerTest",
  1972. modelId: "MiniMax-M3",
  1973. displayName: "m3.05",
  1974. selected: true,
  1975. },
  1976. ]);
  1977. const app = createTuiApp({
  1978. runtime,
  1979. terminal,
  1980. version: "0.1.0",
  1981. workspaceDir: "/workspace",
  1982. });
  1983. app.start();
  1984. await app.ready;
  1985. await vi.waitFor(() =>
  1986. expect(app.tui.render(120).join("\n")).toContain("✦ m3.05"),
  1987. );
  1988. await app.stop();
  1989. });
  1990. it("restores a managed-login failure to the Composer", async () => {
  1991. const terminal = new FakeTerminal();
  1992. const runtime = createRuntime();
  1993. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  1994. status: "ready",
  1995. defaultModel: "minimax/MiniMax-M2.7",
  1996. authMode: "managed-login",
  1997. modelSource: "token-plan",
  1998. managedTokenPresent: false,
  1999. warnings: [],
  2000. });
  2001. const app = createTuiApp({
  2002. runtime,
  2003. terminal,
  2004. version: "0.1.0",
  2005. workspaceDir: "/workspace",
  2006. });
  2007. app.start();
  2008. await app.ready;
  2009. await vi.waitFor(() =>
  2010. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login"),
  2011. );
  2012. terminal.input?.("Keep this until login");
  2013. terminal.input?.("\r");
  2014. await vi.waitFor(() =>
  2015. expect(app.editor.getText()).toBe("Keep this until login"),
  2016. );
  2017. expect(app.tui.render(80).join("\n")).toContain("Keep this until login");
  2018. expect(app.transcript.snapshot()).toEqual(
  2019. expect.arrayContaining([
  2020. expect.objectContaining({
  2021. kind: "warning",
  2022. content:
  2023. "Sign in to MiniMax to use Agent features. Run /login, then retry.",
  2024. }),
  2025. ]),
  2026. );
  2027. expect(runtime.createSession).not.toHaveBeenCalled();
  2028. expect(runtime.sendMessage).not.toHaveBeenCalled();
  2029. await app.stop();
  2030. });
  2031. it("renders an Enter submission before the asynchronous login preflight settles", async () => {
  2032. const terminal = new FakeTerminal();
  2033. const runtime = createRuntime();
  2034. const app = createTuiApp({
  2035. runtime,
  2036. terminal,
  2037. version: "0.1.0",
  2038. workspaceDir: "/workspace",
  2039. });
  2040. app.start();
  2041. await app.ready;
  2042. let resolveAccount:
  2043. | ((
  2044. account: Awaited<ReturnType<typeof runtime.getAccountStatus>>,
  2045. ) => void)
  2046. | undefined;
  2047. vi.mocked(runtime.getAccountStatus).mockImplementationOnce(
  2048. () =>
  2049. new Promise((resolve) => {
  2050. resolveAccount = resolve;
  2051. }),
  2052. );
  2053. const writesBeforeSubmission = terminal.writes.length;
  2054. terminal.input?.("Show this immediately");
  2055. terminal.input?.("\r");
  2056. expect(app.editor.getText()).toBe("");
  2057. expect(
  2058. app.transcript.snapshot().filter((cell) => cell.kind === "user"),
  2059. ).toEqual([
  2060. expect.objectContaining({
  2061. status: "pending",
  2062. content: "Show this immediately",
  2063. }),
  2064. ]);
  2065. await vi.waitFor(() =>
  2066. expect(terminal.writes.length).toBeGreaterThan(writesBeforeSubmission),
  2067. );
  2068. expect(runtime.createSession).not.toHaveBeenCalled();
  2069. expect(runtime.sendMessage).not.toHaveBeenCalled();
  2070. await vi.waitFor(() => expect(resolveAccount).toBeTypeOf("function"));
  2071. resolveAccount?.({
  2072. status: "ready",
  2073. defaultModel: "minimax/MiniMax-M2.7",
  2074. providerId: "minimax",
  2075. modelId: "MiniMax-M2.7",
  2076. authMode: "managed-login",
  2077. managedTokenPresent: true,
  2078. warnings: [],
  2079. });
  2080. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
  2081. await app.stop();
  2082. });
  2083. it("keeps a login-blocked submission editable after current-region sign-in", async () => {
  2084. const terminal = new FakeTerminal();
  2085. const runtime = createRuntime();
  2086. let authenticated = false;
  2087. vi.mocked(runtime.getAccountStatus).mockImplementation(async () =>
  2088. authenticated
  2089. ? {
  2090. status: "ready",
  2091. defaultModel: "minimax/MiniMax-M2.7",
  2092. providerId: "minimax",
  2093. modelId: "MiniMax-M2.7",
  2094. authMode: "managed-login",
  2095. modelSource: "token-plan",
  2096. managedTokenPresent: true,
  2097. warnings: [],
  2098. }
  2099. : {
  2100. status: "needs-login",
  2101. authMode: "managed-login",
  2102. modelSource: "token-plan",
  2103. managedTokenPresent: false,
  2104. warnings: [],
  2105. },
  2106. );
  2107. const auth = {
  2108. login: vi.fn(async () => {
  2109. authenticated = true;
  2110. return {
  2111. state: "authenticated" as const,
  2112. message: "Signed in with MiniMax.",
  2113. };
  2114. }),
  2115. logout: vi.fn(async () => ({
  2116. state: "signed-out" as const,
  2117. message: "Signed out of MiniMax.",
  2118. })),
  2119. };
  2120. const app = createTuiApp({
  2121. runtime,
  2122. auth,
  2123. terminal,
  2124. version: "0.1.0",
  2125. workspaceDir: "/workspace",
  2126. });
  2127. app.start();
  2128. await app.ready;
  2129. terminal.input?.("Send this after login");
  2130. terminal.input?.("\r");
  2131. await vi.waitFor(() =>
  2132. expect(app.editor.getText()).toBe("Send this after login"),
  2133. );
  2134. await app.submit("/login");
  2135. app.interaction.current()?.handleInput("\r");
  2136. expect(runtime.sendMessage).not.toHaveBeenCalled();
  2137. app.editor.handleInput("\r");
  2138. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
  2139. expect(runtime.sendMessage).toHaveBeenCalledWith(
  2140. expect.objectContaining({
  2141. id: "session-1",
  2142. content: "Send this after login",
  2143. turnId: expect.any(String),
  2144. }),
  2145. expect.any(AbortSignal),
  2146. );
  2147. expect(app.transcript.snapshot()).toEqual(
  2148. expect.arrayContaining([
  2149. expect.objectContaining({
  2150. kind: "user",
  2151. content: "Send this after login",
  2152. }),
  2153. ]),
  2154. );
  2155. await app.stop();
  2156. });
  2157. it("runs /checkin immediately for a signed-in MiniMax account", async () => {
  2158. const runtime = createRuntime();
  2159. const app = createTuiApp({
  2160. runtime,
  2161. terminal: new FakeTerminal(),
  2162. version: "0.1.0",
  2163. workspaceDir: "/workspace",
  2164. });
  2165. app.start();
  2166. await app.ready;
  2167. await app.submit("/checkin");
  2168. expect(runtime.runDailyCheckin).toHaveBeenCalledOnce();
  2169. expect(app.transcript.snapshot()).toEqual(
  2170. expect.arrayContaining([
  2171. expect.objectContaining({
  2172. kind: "final-summary",
  2173. content: expect.stringContaining(
  2174. "Checked in: Cycle day 2, +20 Credits",
  2175. ),
  2176. }),
  2177. ]),
  2178. );
  2179. await app.stop();
  2180. });
  2181. it("shows a generic /checkin failure without backend details", async () => {
  2182. const runtime = createRuntime();
  2183. vi.mocked(runtime.runDailyCheckin).mockRejectedValue(
  2184. new Error("internal signin shard rejected request"),
  2185. );
  2186. const app = createTuiApp({
  2187. runtime,
  2188. terminal: new FakeTerminal(),
  2189. version: "0.1.0",
  2190. workspaceDir: "/workspace",
  2191. });
  2192. app.start();
  2193. await app.ready;
  2194. await app.submit("/checkin");
  2195. const transcript = app.transcript
  2196. .snapshot()
  2197. .map((cell) => cell.content)
  2198. .join("\n");
  2199. expect(transcript).toContain("Couldn't complete daily check-in.");
  2200. expect(transcript).not.toContain("internal signin shard");
  2201. await app.stop();
  2202. });
  2203. it("does not open login when /checkin cannot verify account status", async () => {
  2204. const runtime = createRuntime();
  2205. const auth = {
  2206. login: vi.fn(),
  2207. logout: vi.fn(async () => ({
  2208. state: "signed-out" as const,
  2209. message: "Signed out of MiniMax.",
  2210. })),
  2211. };
  2212. const app = createTuiApp({
  2213. runtime,
  2214. auth,
  2215. terminal: new FakeTerminal(),
  2216. version: "0.1.0",
  2217. workspaceDir: "/workspace",
  2218. });
  2219. app.start();
  2220. await app.ready;
  2221. vi.mocked(runtime.getAccountStatus).mockRejectedValue(
  2222. new Error("status unavailable"),
  2223. );
  2224. await app.submit("/checkin");
  2225. expect(app.interaction.current()).toBeUndefined();
  2226. expect(auth.login).not.toHaveBeenCalled();
  2227. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2228. await app.stop();
  2229. });
  2230. it("starts MiniMax login and resumes /checkin once after authentication", async () => {
  2231. const runtime = createRuntime();
  2232. let authenticated = false;
  2233. vi.mocked(runtime.getAccountStatus).mockImplementation(async () => ({
  2234. status: authenticated ? "ready" : "needs-login",
  2235. authMode: "managed-login",
  2236. modelSource: "byok",
  2237. managedTokenPresent: authenticated,
  2238. warnings: [],
  2239. }));
  2240. const auth = {
  2241. login: vi.fn(async () => {
  2242. authenticated = true;
  2243. return {
  2244. state: "authenticated" as const,
  2245. message: "Signed in with MiniMax.",
  2246. };
  2247. }),
  2248. logout: vi.fn(async () => ({
  2249. state: "signed-out" as const,
  2250. message: "Signed out of MiniMax.",
  2251. })),
  2252. };
  2253. const app = createTuiApp({
  2254. runtime,
  2255. auth,
  2256. terminal: new FakeTerminal(),
  2257. version: "0.1.0",
  2258. workspaceDir: "/workspace",
  2259. });
  2260. app.start();
  2261. await app.ready;
  2262. await app.submit("/checkin");
  2263. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2264. app.interaction.current()?.handleInput("\r");
  2265. await vi.waitFor(() =>
  2266. expect(runtime.runDailyCheckin).toHaveBeenCalledOnce(),
  2267. );
  2268. expect(auth.login).toHaveBeenCalledWith(expect.any(Function), "cn");
  2269. await app.stop();
  2270. });
  2271. it("does not resume /checkin when the login picker is cancelled", async () => {
  2272. const runtime = createRuntime();
  2273. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2274. status: "needs-login",
  2275. authMode: "managed-login",
  2276. modelSource: "byok",
  2277. managedTokenPresent: false,
  2278. warnings: [],
  2279. });
  2280. const auth = {
  2281. login: vi.fn(),
  2282. logout: vi.fn(async () => ({
  2283. state: "signed-out" as const,
  2284. message: "Signed out of MiniMax.",
  2285. })),
  2286. };
  2287. const app = createTuiApp({
  2288. runtime,
  2289. auth,
  2290. terminal: new FakeTerminal(),
  2291. version: "0.1.0",
  2292. workspaceDir: "/workspace",
  2293. });
  2294. app.start();
  2295. await app.ready;
  2296. await app.submit("/checkin");
  2297. app.interaction.current()?.handleInput("\u001b");
  2298. expect(auth.login).not.toHaveBeenCalled();
  2299. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2300. await app.stop();
  2301. });
  2302. it("does not resume /checkin when browser login fails", async () => {
  2303. const runtime = createRuntime();
  2304. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2305. status: "needs-login",
  2306. managedTokenPresent: false,
  2307. warnings: [],
  2308. });
  2309. const auth = {
  2310. login: vi.fn(async () => {
  2311. throw new Error("browser login failed");
  2312. }),
  2313. logout: vi.fn(async () => ({
  2314. state: "signed-out" as const,
  2315. message: "Signed out of MiniMax.",
  2316. })),
  2317. };
  2318. const app = createTuiApp({
  2319. runtime,
  2320. auth,
  2321. terminal: new FakeTerminal(),
  2322. version: "0.1.0",
  2323. workspaceDir: "/workspace",
  2324. });
  2325. app.start();
  2326. await app.ready;
  2327. await app.submit("/checkin");
  2328. app.interaction.current()?.handleInput("\r");
  2329. await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
  2330. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2331. await app.stop();
  2332. });
  2333. it("carries /checkin through a cross-region login restart", async () => {
  2334. const runtime = createRuntime();
  2335. const requestRestart = vi.fn();
  2336. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2337. status: "needs-login",
  2338. managedTokenPresent: false,
  2339. warnings: [],
  2340. });
  2341. const auth = {
  2342. login: vi.fn(async () => ({
  2343. state: "authenticated" as const,
  2344. restartRequired: true,
  2345. message: "Signed in with MiniMax Global.",
  2346. })),
  2347. logout: vi.fn(async () => ({
  2348. state: "signed-out" as const,
  2349. message: "Signed out of MiniMax.",
  2350. })),
  2351. };
  2352. const app = createTuiApp({
  2353. runtime,
  2354. auth,
  2355. terminal: new FakeTerminal(),
  2356. version: "0.1.0",
  2357. workspaceDir: "/workspace",
  2358. requestRestart,
  2359. });
  2360. app.start();
  2361. await app.ready;
  2362. await app.submit("/checkin");
  2363. app.interaction.current()?.handleInput("\u001b[B");
  2364. app.interaction.current()?.handleInput("\r");
  2365. await vi.waitFor(() =>
  2366. expect(requestRestart).toHaveBeenCalledWith("en", "/checkin"),
  2367. );
  2368. expect(runtime.runDailyCheckin).not.toHaveBeenCalled();
  2369. await app.stopped;
  2370. });
  2371. it("restarts after cross-region login while keeping the blocked submission", async () => {
  2372. const terminal = new FakeTerminal();
  2373. const runtime = createRuntime();
  2374. const requestRestart = vi.fn();
  2375. const notifyAuthContextChanged = vi.fn(async () => undefined);
  2376. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2377. status: "needs-login",
  2378. authMode: "managed-login",
  2379. modelSource: "token-plan",
  2380. managedTokenPresent: false,
  2381. warnings: [],
  2382. });
  2383. const auth = {
  2384. login: vi.fn(async () => ({
  2385. state: "authenticated" as const,
  2386. restartRequired: true,
  2387. message: "Signed in with MiniMax Global.",
  2388. })),
  2389. logout: vi.fn(async () => ({
  2390. state: "signed-out" as const,
  2391. message: "Signed out of MiniMax.",
  2392. })),
  2393. };
  2394. const app = createTuiApp({
  2395. runtime,
  2396. auth,
  2397. terminal,
  2398. version: "0.1.0",
  2399. workspaceDir: "/workspace",
  2400. requestRestart,
  2401. notifyAuthContextChanged,
  2402. });
  2403. app.start();
  2404. await app.ready;
  2405. terminal.input?.("Keep this through restart");
  2406. terminal.input?.("\r");
  2407. await vi.waitFor(() =>
  2408. expect(app.editor.getText()).toBe("Keep this through restart"),
  2409. );
  2410. await app.submit("/login");
  2411. app.interaction.current()?.handleInput("\u001b[B");
  2412. app.interaction.current()?.handleInput("\r");
  2413. await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
  2414. expect(auth.login).toHaveBeenCalledWith(expect.any(Function), "en");
  2415. expect(runtime.sendMessage).not.toHaveBeenCalled();
  2416. await vi.waitFor(() => expect(requestRestart).toHaveBeenCalledOnce());
  2417. expect(requestRestart).toHaveBeenCalledWith("en");
  2418. expect(notifyAuthContextChanged).not.toHaveBeenCalled();
  2419. await app.stopped;
  2420. expect(app.editor.getText()).toBe("Keep this through restart");
  2421. });
  2422. it("offers MiniMax login without blocking an unauthenticated builtin BYOK Turn", async () => {
  2423. const runtime = createRuntime();
  2424. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  2425. status: "ready",
  2426. defaultModel: "minimax/MiniMax-M3",
  2427. providerId: "minimax",
  2428. authMode: "managed-login",
  2429. modelSource: "byok",
  2430. managedTokenPresent: false,
  2431. warnings: [],
  2432. });
  2433. const app = createTuiApp({
  2434. runtime,
  2435. terminal: new FakeTerminal(),
  2436. version: "0.1.0",
  2437. workspaceDir: "/workspace",
  2438. });
  2439. app.start();
  2440. await app.ready;
  2441. await vi.waitFor(() =>
  2442. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login"),
  2443. );
  2444. await app.submit("BYOK still runs");
  2445. expect(runtime.createSession).toHaveBeenCalledWith({
  2446. workspaceDir: "/workspace",
  2447. });
  2448. expect(app.transcript.snapshot()).toEqual(
  2449. expect.arrayContaining([
  2450. expect.objectContaining({ kind: "user", content: "BYOK still runs" }),
  2451. expect.objectContaining({
  2452. kind: "assistant",
  2453. content: "Hello from the Agent",
  2454. }),
  2455. ]),
  2456. );
  2457. await app.stop();
  2458. });
  2459. it("starts a terminal-native workbench and submits messages through the Agent runtime", async () => {
  2460. const terminal = new FakeTerminal();
  2461. const runtime = createRuntime();
  2462. const app = createTuiApp({
  2463. runtime,
  2464. terminal,
  2465. version: "0.1.0",
  2466. workspaceDir: "/workspace",
  2467. homeDir: "/home/dev",
  2468. });
  2469. app.start();
  2470. await app.ready;
  2471. expect(app.getSurface()).toBe("welcome");
  2472. await app.submit("Say hello");
  2473. expect(app.getSurface()).toBe("conversation");
  2474. const conversation = app.tui.render(80).join("\n");
  2475. expect(conversation).toContain("Tips for getting started");
  2476. expect(conversation).toContain("Say hello");
  2477. expect(conversation).toContain("Hello from the Agent");
  2478. expect(terminal.started).toBe(true);
  2479. expect(terminal.title).toBe("Minimax Code");
  2480. expect(runtime.createSession).toHaveBeenCalledWith({
  2481. workspaceDir: "/workspace",
  2482. });
  2483. expect(app.transcript.snapshot()).toEqual([
  2484. expect.objectContaining({ kind: "user", content: "Say hello" }),
  2485. expect.objectContaining({
  2486. kind: "assistant",
  2487. status: "succeeded",
  2488. content: "Hello from the Agent",
  2489. }),
  2490. expect.objectContaining({ kind: "turn-duration", status: "succeeded" }),
  2491. ]);
  2492. await app.stop();
  2493. expect(terminal.stopped).toBe(true);
  2494. });
  2495. it("syncs the generated Session title to the terminal without duplicate writes", async () => {
  2496. const terminal = new FakeTerminal();
  2497. const runtime = createRuntime();
  2498. let sessionTitle = "New session";
  2499. let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  2500. vi.mocked(runtime.listSessions).mockImplementation(async () => [
  2501. {
  2502. sessionId: "session-1",
  2503. title: sessionTitle,
  2504. workspaceDir: "/workspace",
  2505. },
  2506. ]);
  2507. vi.mocked(runtime.watchEvents).mockImplementation(
  2508. async function* watchEvents(signal) {
  2509. const event = await new Promise<TuiRuntimeEvent | undefined>(
  2510. (resolve) => {
  2511. emitEvent = resolve;
  2512. signal.addEventListener("abort", () => resolve(undefined), {
  2513. once: true,
  2514. });
  2515. },
  2516. );
  2517. if (event) yield event;
  2518. await new Promise<void>((resolve) => {
  2519. signal.addEventListener("abort", resolve, { once: true });
  2520. });
  2521. },
  2522. );
  2523. const app = createTuiApp({
  2524. runtime,
  2525. terminal,
  2526. version: "0.1.0",
  2527. workspaceDir: "/workspace",
  2528. });
  2529. app.start();
  2530. await app.ready;
  2531. await app.submit("Review uncommitted work");
  2532. await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
  2533. sessionTitle = "Review uncommitted work";
  2534. emitEvent?.(
  2535. runtimeEvent({
  2536. type: "session.title_updated",
  2537. timestamp: Date.now(),
  2538. source: "runtime",
  2539. payload: {
  2540. sessionId: "session-1",
  2541. title: sessionTitle,
  2542. },
  2543. }),
  2544. );
  2545. await vi.waitFor(() => expect(terminal.title).toBe(sessionTitle));
  2546. await app.submit("/status");
  2547. expect(terminal.titleUpdates).toEqual(["Minimax Code", sessionTitle]);
  2548. await app.stop();
  2549. });
  2550. it("keeps chat state alive while a regular feature overlay owns the viewport", async () => {
  2551. const terminal = new FakeTerminal();
  2552. terminal.rows = 6;
  2553. const runtime = createRuntime();
  2554. const app = createTuiApp({
  2555. runtime,
  2556. terminal,
  2557. version: "0.1.0",
  2558. workspaceDir: "/workspace",
  2559. });
  2560. const featureInput = vi.fn();
  2561. const featureContent = {
  2562. render: () => ["feature-header", "feature-body"],
  2563. invalidate: () => undefined,
  2564. };
  2565. const feature = {
  2566. id: "sessions",
  2567. layoutRoot: new VStack([{ component: featureContent }]),
  2568. render: featureContent.render,
  2569. invalidate: () => undefined,
  2570. handleInput: featureInput,
  2571. };
  2572. app.start();
  2573. await app.ready;
  2574. const screen = new VirtualTerminalScreen(terminal.columns, terminal.rows);
  2575. let writeIndex = 0;
  2576. const flushWrites = (): void => {
  2577. for (; writeIndex < terminal.writes.length; writeIndex += 1) {
  2578. screen.feed(terminal.writes[writeIndex] ?? "");
  2579. }
  2580. };
  2581. flushWrites();
  2582. app.editor.setText("preserved draft");
  2583. const handle = app.surfaceHost.pushFeature({ screen: feature });
  2584. app.tui.renderNow();
  2585. flushWrites();
  2586. expect(app.surfaceHost.getActiveSurface()).toEqual({
  2587. kind: "feature",
  2588. id: "sessions",
  2589. });
  2590. expect(app.surfaceHost.render(80).join("\n")).toContain("preserved draft");
  2591. expect(screen.viewportText()).toContain("feature-header");
  2592. expect(screen.viewportText()).toContain("feature-body");
  2593. expect(app.tui.mode).toBe("regular");
  2594. expect(terminal.startCount).toBe(1);
  2595. expect(terminal.stopCount).toBe(0);
  2596. terminal.input?.("j");
  2597. expect(featureInput).toHaveBeenCalledWith("j");
  2598. expect(handle.close()).toBe(true);
  2599. app.tui.renderNow();
  2600. flushWrites();
  2601. expect(app.surfaceHost.getActiveSurface()).toEqual({
  2602. kind: "chat",
  2603. id: "chat",
  2604. });
  2605. expect(app.editor.getText()).toBe("preserved draft");
  2606. expect(app.surfaceHost.render(80).join("\n")).toContain("preserved draft");
  2607. expect(screen.viewportText()).toContain("preserved draft");
  2608. expect(screen.viewportText()).not.toContain("feature-header");
  2609. await app.stop();
  2610. screen.dispose();
  2611. });
  2612. it("switches /settings through explicit choices and closes after applying", async () => {
  2613. const terminal = new FakeTerminal();
  2614. const persistTuiMode = vi.fn();
  2615. const app = createTuiApp({
  2616. runtime: createRuntime(),
  2617. terminal,
  2618. version: "0.2.0",
  2619. workspaceDir: "/workspace",
  2620. tuiMode: "regular",
  2621. persistTuiMode,
  2622. });
  2623. app.start();
  2624. await app.ready;
  2625. expect(app.surfaceHost.getChatMode()).toBe("regular");
  2626. expect(app.tui.mode).toBe("regular");
  2627. await app.submit("/settings");
  2628. const fullscreenSettings = app.interaction.current();
  2629. expect(app.tui.getFocusedComponent()).toBe(fullscreenSettings);
  2630. expect(app.surfaceHost.render(80).join("\n")).toContain(
  2631. "TUI mode · Regular",
  2632. );
  2633. terminal.input?.("\u001b[B");
  2634. terminal.input?.("\r");
  2635. expect(app.surfaceHost.getChatMode()).toBe("fullscreen");
  2636. expect(app.tui.mode).toBe("fullscreen");
  2637. expect(app.interaction.isActive()).toBe(false);
  2638. expect(app.tui.getFocusedComponent()).toBe(app.editor);
  2639. expect(persistTuiMode).toHaveBeenLastCalledWith("fullscreen");
  2640. expect(app.editor.focused).toBe(true);
  2641. terminal.input?.("/");
  2642. await vi.waitFor(() =>
  2643. expect(app.editor.render(60).join("\n")).toContain(
  2644. "Show available commands",
  2645. ),
  2646. );
  2647. terminal.input?.("\u001b");
  2648. app.editor.setText("");
  2649. await app.submit("/settings");
  2650. const regularSettings = app.interaction.current();
  2651. expect(app.tui.getFocusedComponent()).toBe(regularSettings);
  2652. expect(app.surfaceHost.render(80).join("\n")).toContain(
  2653. "TUI mode · Fullscreen",
  2654. );
  2655. terminal.input?.("\u001b[A");
  2656. terminal.input?.("\r");
  2657. expect(app.surfaceHost.getChatMode()).toBe("regular");
  2658. expect(app.tui.mode).toBe("regular");
  2659. expect(app.interaction.isActive()).toBe(false);
  2660. expect(app.tui.getFocusedComponent()).toBe(app.editor);
  2661. expect(persistTuiMode).toHaveBeenLastCalledWith("regular");
  2662. await app.stop();
  2663. });
  2664. it("keeps the Pi Editor and Slash Command autocomplete active in fullscreen chat", async () => {
  2665. const terminal = new FakeTerminal();
  2666. terminal.rows = 8;
  2667. const app = createTuiApp({
  2668. runtime: createRuntime(),
  2669. terminal,
  2670. version: "0.2.0",
  2671. workspaceDir: "/workspace",
  2672. tuiMode: "fullscreen",
  2673. });
  2674. app.start();
  2675. await app.ready;
  2676. terminal.input?.("/");
  2677. await vi.waitFor(() =>
  2678. expect(app.editor.render(60).join("\n")).toContain(
  2679. "Show available commands",
  2680. ),
  2681. );
  2682. expect(app.editor.getText()).toBe("/");
  2683. terminal.input?.("\u001B[B");
  2684. expect(app.editor.getText()).toBe("/");
  2685. terminal.input?.("\u001B");
  2686. expect(app.editor.getText()).toBe("/");
  2687. expect(app.editor.focused).toBe(true);
  2688. await app.stop();
  2689. });
  2690. it("renders regular-mode Slash Command autocomplete on the first keypress and every update", async () => {
  2691. const terminal = new FakeTerminal();
  2692. const app = createTuiApp({
  2693. runtime: createRuntime(),
  2694. terminal,
  2695. version: "0.2.0",
  2696. workspaceDir: "/workspace",
  2697. tuiMode: "regular",
  2698. });
  2699. app.start();
  2700. await app.ready;
  2701. const screen = new VirtualTerminalScreen(terminal.columns, terminal.rows);
  2702. let writeIndex = 0;
  2703. const flushWrites = (): void => {
  2704. for (; writeIndex < terminal.writes.length; writeIndex += 1) {
  2705. screen.feed(terminal.writes[writeIndex] ?? "");
  2706. }
  2707. };
  2708. flushWrites();
  2709. terminal.input?.("/");
  2710. await vi.waitFor(() => {
  2711. flushWrites();
  2712. expect(screen.viewportText()).toContain("Show available commands");
  2713. });
  2714. expect(screen.viewportText()).toContain("/");
  2715. terminal.input?.("m");
  2716. await vi.waitFor(() => {
  2717. flushWrites();
  2718. expect(screen.viewportText()).toContain("Choose a model");
  2719. });
  2720. expect(screen.viewportText()).toContain("/m");
  2721. screen.dispose();
  2722. await app.stop();
  2723. });
  2724. it("resumes fullscreen tail following when submitting from scrolled history", async () => {
  2725. const terminal = new FakeTerminal();
  2726. terminal.rows = 6;
  2727. const app = createTuiApp({
  2728. runtime: createRuntime(),
  2729. terminal,
  2730. version: "0.2.0",
  2731. workspaceDir: "/workspace",
  2732. tuiMode: "fullscreen",
  2733. });
  2734. app.start();
  2735. await app.ready;
  2736. for (let index = 1; index <= 4; index += 1) {
  2737. await app.submit(`Prompt ${String(index)}`);
  2738. }
  2739. app.tui.renderNow();
  2740. terminal.input?.("\u001B[5~");
  2741. expect((app.tui as TuiAltScreen).isFollowingOutput).toBe(false);
  2742. await app.submit("Latest prompt");
  2743. expect((app.tui as TuiAltScreen).isFollowingOutput).toBe(true);
  2744. await app.stop();
  2745. });
  2746. it("stops the terminal without waiting for a stalled Desktop event stream", async () => {
  2747. const terminal = new FakeTerminal();
  2748. const runtime = createRuntime();
  2749. vi.mocked(runtime.watchEvents).mockImplementation(
  2750. async function* watchEvents() {
  2751. await new Promise<void>(() => undefined);
  2752. yield runtimeEvent({
  2753. type: "unreachable",
  2754. timestamp: 0,
  2755. source: "test",
  2756. payload: {},
  2757. });
  2758. },
  2759. );
  2760. const app = createTuiApp({
  2761. runtime,
  2762. terminal,
  2763. version: "0.1.0",
  2764. workspaceDir: "/workspace",
  2765. });
  2766. app.start();
  2767. await app.ready;
  2768. const stopping = app.stop();
  2769. await vi.waitFor(() => expect(terminal.stopped).toBe(true));
  2770. await stopping;
  2771. });
  2772. it("restores the terminal before a stalled remote turn abort finishes", async () => {
  2773. const terminal = new FakeTerminal();
  2774. const runtime = createRuntime();
  2775. let finishRemoteAbort: ((value: boolean) => void) | undefined;
  2776. vi.mocked(runtime.sendMessage).mockImplementation(
  2777. async function* sendMessage(_req: SendMessageReq, signal?: AbortSignal) {
  2778. await new Promise<void>((resolve) => {
  2779. signal?.addEventListener("abort", () => resolve(), { once: true });
  2780. });
  2781. yield { type: "done" };
  2782. },
  2783. );
  2784. vi.mocked(runtime.abortSession).mockImplementation(
  2785. async () =>
  2786. await new Promise<boolean>((resolve) => {
  2787. finishRemoteAbort = resolve;
  2788. }),
  2789. );
  2790. const app = createTuiApp({
  2791. runtime,
  2792. terminal,
  2793. version: "0.1.0",
  2794. workspaceDir: "/workspace",
  2795. });
  2796. app.start();
  2797. await app.ready;
  2798. const submitting = app.submit("Keep running");
  2799. await vi.waitFor(() =>
  2800. expect(app.controller.snapshot().status).toBe("running"),
  2801. );
  2802. const stopping = app.stop();
  2803. await vi.waitFor(() => expect(terminal.stopped).toBe(true));
  2804. finishRemoteAbort?.(true);
  2805. await Promise.all([submitting, stopping]);
  2806. });
  2807. it("stops the active turn before leaving the UI", async () => {
  2808. const terminal = new FakeTerminal();
  2809. const runtime = createRuntime();
  2810. let finishTurn: (() => void) | undefined;
  2811. vi.mocked(runtime.sendMessage).mockImplementation(
  2812. async function* sendMessage() {
  2813. yield {
  2814. type: "delta",
  2815. turnId: "turn-detached",
  2816. role: "assistant",
  2817. content: "Still running",
  2818. };
  2819. await new Promise<void>((resolve) => {
  2820. finishTurn = resolve;
  2821. });
  2822. yield { type: "done", turnId: "turn-detached" };
  2823. },
  2824. );
  2825. const app = createTuiApp({
  2826. runtime,
  2827. terminal,
  2828. version: "0.1.0",
  2829. workspaceDir: "/workspace",
  2830. });
  2831. app.start();
  2832. await app.ready;
  2833. const submitting = app.submit("Keep running after the UI leaves");
  2834. await vi.waitFor(() =>
  2835. expect(app.controller.snapshot().status).toBe("running"),
  2836. );
  2837. await app.leaveUi();
  2838. expect(terminal.stopped).toBe(true);
  2839. expect(runtime.abortSession).toHaveBeenCalledWith(
  2840. expect.objectContaining({ id: "session-1" }),
  2841. );
  2842. finishTurn?.();
  2843. await submitting;
  2844. });
  2845. it("resumes a launcher-selected Session and exposes its ID for the exit hint", async () => {
  2846. const terminal = new FakeTerminal();
  2847. const runtime = createRuntime();
  2848. const app = createTuiApp({
  2849. runtime,
  2850. terminal,
  2851. version: "0.1.0",
  2852. workspaceDir: "/workspace",
  2853. });
  2854. app.start();
  2855. await app.ready;
  2856. expect(app.controller.snapshot().session?.sessionId).toBeUndefined();
  2857. await app.openSession("session-existing");
  2858. expect(runtime.getSession).toHaveBeenCalledWith("session-existing");
  2859. expect(runtime.getMessages).toHaveBeenCalledWith("session-existing");
  2860. expect(app.controller.snapshot().session?.sessionId).toBe(
  2861. "session-existing",
  2862. );
  2863. await app.leaveUi();
  2864. });
  2865. it("reports a launcher continue hydration failure in the Transcript", async () => {
  2866. const terminal = new FakeTerminal();
  2867. const runtime = createRuntime();
  2868. vi.mocked(runtime.listSessions).mockResolvedValue([
  2869. {
  2870. sessionId: "session-existing",
  2871. title: "Existing session",
  2872. workspaceDir: "/workspace",
  2873. },
  2874. ]);
  2875. vi.mocked(runtime.getSession).mockRejectedValue(
  2876. new Error("Session hydration failed"),
  2877. );
  2878. const app = createTuiApp({
  2879. runtime,
  2880. terminal,
  2881. version: "0.1.0",
  2882. workspaceDir: "/workspace",
  2883. });
  2884. await app.ready;
  2885. await expect(app.continueLatestSession()).rejects.toThrow(
  2886. "Session hydration failed",
  2887. );
  2888. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  2889. kind: "error",
  2890. content:
  2891. "Couldn't continue the latest conversation: Session hydration failed. Retry after the connection recovers.",
  2892. });
  2893. await app.leaveUi();
  2894. });
  2895. it("can disable queue UI and preserve the next draft while a turn is running", async () => {
  2896. const terminal = new FakeTerminal();
  2897. const runtime = createRuntime();
  2898. let finishTool: (() => void) | undefined;
  2899. vi.mocked(runtime.sendMessage).mockImplementation(
  2900. async function* sendMessage() {
  2901. yield {
  2902. type: "delta",
  2903. turnId: "turn-running-tool",
  2904. toolCalls: [
  2905. {
  2906. id: "read-1",
  2907. name: "read",
  2908. status: "running",
  2909. input: { path: "src/cart/price.ts" },
  2910. },
  2911. ],
  2912. };
  2913. await new Promise<void>((resolve) => {
  2914. finishTool = resolve;
  2915. });
  2916. yield { type: "done", turnId: "turn-running-tool" };
  2917. },
  2918. );
  2919. const app = createTuiApp({
  2920. runtime,
  2921. terminal,
  2922. version: "0.1.0",
  2923. workspaceDir: "/workspace",
  2924. productFeatures: { queue: false },
  2925. });
  2926. await app.ready;
  2927. const submission = app.submit("Inspect the pricing logic");
  2928. await vi.waitFor(() => {
  2929. const rendered = app.tui.render(80).join("\n");
  2930. expect(rendered).toContain("Reading (src/cart/price.ts)");
  2931. expect(rendered).toContain("Running");
  2932. expect(rendered).not.toContain("Running · 0s");
  2933. expect(rendered).not.toContain("Running · Read");
  2934. expect(rendered).not.toContain("MCode · Running");
  2935. expect(rendered).toContain("Ctrl+O details");
  2936. expect(rendered).toContain("Esc stop");
  2937. expect(rendered).not.toContain("Enter run next");
  2938. expect(rendered).not.toContain("Message · Enter send");
  2939. expect(rendered).not.toContain("Follow-up");
  2940. expect(rendered).not.toContain("waiting");
  2941. });
  2942. await app.submit("Review the tests next");
  2943. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  2944. expect(app.editor.getText()).toBe("Review the tests next");
  2945. expect(app.tui.render(80).join("\n")).toContain("Esc to interrupt");
  2946. finishTool?.();
  2947. await submission;
  2948. });
  2949. it("refreshes the running queue hint from the same bindings as the hotkeys panel", async () => {
  2950. const keybindings = createTuiHostKeybindings({
  2951. platform: "linux",
  2952. suspendSupported: true,
  2953. });
  2954. const runtime = createRuntime();
  2955. let finishTurn: (() => void) | undefined;
  2956. vi.mocked(runtime.sendMessage).mockImplementation(
  2957. async function* sendMessage() {
  2958. yield {
  2959. type: "delta",
  2960. turnId: "turn-custom-queue",
  2961. thinking: "Inspecting the repository",
  2962. };
  2963. await new Promise<void>((resolve) => {
  2964. finishTurn = resolve;
  2965. });
  2966. yield { type: "done", turnId: "turn-custom-queue" };
  2967. },
  2968. );
  2969. const app = createTuiApp({
  2970. runtime,
  2971. terminal: new FakeTerminal(),
  2972. version: "0.1.0",
  2973. workspaceDir: "/workspace",
  2974. keybindings: keybindings.registry,
  2975. });
  2976. await app.ready;
  2977. keybindings.manager.setUserBindings({ "run.queue-draft": "ctrl+enter" });
  2978. const submission = app.submit("Inspect the repository");
  2979. try {
  2980. await vi.waitFor(() => {
  2981. const rendered = stripAnsi(app.tui.render(100).join("\n"));
  2982. expect(rendered).toContain("Running");
  2983. expect(rendered).toContain("Ctrl+Enter queue");
  2984. expect(rendered).not.toContain("Alt+Enter queue");
  2985. expect(
  2986. keybindings.registry
  2987. .helpRows()
  2988. .find((row) => row.ids.includes("run.queue-draft"))?.keys,
  2989. ).toBe("Ctrl+Enter");
  2990. });
  2991. } finally {
  2992. finishTurn?.();
  2993. await submission;
  2994. await app.stop();
  2995. }
  2996. });
  2997. it("shows running Thinking in chat and opens the full Transcript with /transcript", async () => {
  2998. const terminal = new FakeTerminal();
  2999. const runtime = createRuntime();
  3000. let finishThinking: (() => void) | undefined;
  3001. vi.mocked(runtime.sendMessage).mockImplementation(
  3002. async function* sendMessage() {
  3003. yield {
  3004. type: "delta",
  3005. turnId: "turn-running-thinking",
  3006. thinking: "Inspecting the repository",
  3007. };
  3008. await new Promise<void>((resolve) => {
  3009. finishThinking = resolve;
  3010. });
  3011. yield { type: "done", turnId: "turn-running-thinking" };
  3012. },
  3013. );
  3014. const app = createTuiApp({
  3015. runtime,
  3016. terminal,
  3017. version: "0.1.0",
  3018. workspaceDir: "/workspace",
  3019. });
  3020. app.start();
  3021. await app.ready;
  3022. const submission = app.submit("Inspect the repository");
  3023. const countThinkingBodyRows = (rendered: string): number =>
  3024. rendered
  3025. .split("\n")
  3026. .filter(
  3027. (line) =>
  3028. line.includes("Inspecting the repository") &&
  3029. !line.includes("MCode"),
  3030. ).length;
  3031. let expandedThinkingRows = 0;
  3032. try {
  3033. await vi.waitFor(() => {
  3034. const thinking = app.transcript
  3035. .snapshot()
  3036. .find((cell) => cell.kind === "thinking");
  3037. expect(thinking?.content).toBe("Inspecting the repository");
  3038. expect(thinking?.expanded).toBeUndefined();
  3039. const rendered = app.tui.render(80).join("\n");
  3040. expect(rendered).toContain("Running");
  3041. expect(rendered).not.toContain("Running · 0s");
  3042. expect(rendered).toContain(`${formatTuiShortcut("alt+enter")} queue`);
  3043. expect(rendered).toContain("Enter steer");
  3044. expect(rendered).not.toContain(`${formatTuiShortcut("ctrl+x")} steer`);
  3045. expect(rendered).toContain("Ctrl+O details");
  3046. expect(rendered).toContain("Esc stop");
  3047. expect(rendered).toContain("Thinking…");
  3048. expect(rendered).not.toContain("MCode ·");
  3049. expect(rendered).not.toContain("Thinking · Inspecting the repository");
  3050. expandedThinkingRows = countThinkingBodyRows(rendered);
  3051. expect(expandedThinkingRows).toBeGreaterThan(0);
  3052. });
  3053. await app.submit("/transcript");
  3054. await vi.waitFor(() => {
  3055. const rendered = renderTerminalViewport(app, terminal);
  3056. expect(app.surfaceHost.getActiveSurface()).toEqual({
  3057. kind: "feature",
  3058. id: "transcript",
  3059. });
  3060. expect(rendered).toContain("Transcript");
  3061. expect(rendered).not.toContain("Inspecting the repository");
  3062. expect(countThinkingBodyRows(rendered)).toBeLessThan(
  3063. expandedThinkingRows,
  3064. );
  3065. });
  3066. terminal.input?.("\x14");
  3067. expect(app.surfaceHost.getActiveSurface()).toEqual({
  3068. kind: "feature",
  3069. id: "transcript",
  3070. });
  3071. finishThinking?.();
  3072. finishThinking = undefined;
  3073. await submission;
  3074. expect(app.surfaceHost.getActiveSurface()).toEqual({
  3075. kind: "feature",
  3076. id: "transcript",
  3077. });
  3078. expect(app.controller.snapshot().activeTurnId).toBeUndefined();
  3079. expect(
  3080. app.transcript.snapshot().find((cell) => cell.kind === "thinking"),
  3081. ).toMatchObject({
  3082. status: "succeeded",
  3083. });
  3084. terminal.input?.("\u001B");
  3085. await vi.waitFor(() => {
  3086. const rendered = app.tui.render(80).join("\n");
  3087. expect(app.surfaceHost.getActiveSurface()).toEqual({
  3088. kind: "chat",
  3089. id: "chat",
  3090. });
  3091. expect(rendered).toContain("Message · Enter send");
  3092. expect(rendered).not.toContain("Running");
  3093. });
  3094. } finally {
  3095. finishThinking?.();
  3096. await submission;
  3097. await app.stop();
  3098. }
  3099. });
  3100. it("toggles hidden and full inline Tool output with Ctrl+O", async () => {
  3101. const terminal = new FakeTerminal();
  3102. const app = createTuiApp({
  3103. runtime: createRuntime(),
  3104. terminal,
  3105. version: "0.1.0",
  3106. workspaceDir: "/workspace",
  3107. });
  3108. app.start();
  3109. await app.ready;
  3110. app.transcript.upsert({
  3111. id: "tool-detail-toggle",
  3112. kind: "tool",
  3113. status: "succeeded",
  3114. title: "bash",
  3115. content: '{"command":"pnpm test"}',
  3116. detail: [
  3117. "result line 1",
  3118. "result line 2",
  3119. "result line 3",
  3120. "result line 4",
  3121. ].join("\n"),
  3122. createdAtMs: 1,
  3123. });
  3124. expect(app.tui.render(80).join("\n")).not.toContain("result line 1");
  3125. expect(app.tui.render(80).join("\n")).not.toContain("result line 4");
  3126. terminal.input?.("\x0f");
  3127. const detailed = app.tui.render(80).join("\n");
  3128. expect(detailed).toContain("result line 1");
  3129. expect(detailed).toContain("result line 3");
  3130. expect(detailed).toContain("result line 4");
  3131. expect(detailed).not.toContain("Details expanded");
  3132. terminal.input?.("\x0f");
  3133. const compact = app.tui.render(80).join("\n");
  3134. expect(compact).not.toContain("result line 1");
  3135. expect(compact).not.toContain("result line 3");
  3136. expect(compact).not.toContain("result line 4");
  3137. expect(compact).not.toContain("Details collapsed");
  3138. await app.stop();
  3139. });
  3140. it("uses Ctrl+T for tasks while Ctrl+O remains scoped to transcript details", async () => {
  3141. const terminal = new FakeTerminal();
  3142. const app = createTuiApp({
  3143. runtime: createRuntime(),
  3144. terminal,
  3145. version: "0.1.0",
  3146. workspaceDir: "/workspace",
  3147. });
  3148. app.start();
  3149. await app.ready;
  3150. app.controller.applyRuntimeTurnEvent("turn-todo", {
  3151. type: "generic",
  3152. eventType: "todo_updated",
  3153. turnId: "turn-todo",
  3154. data: {
  3155. todos: [
  3156. { content: "Inspect Desktop behavior", status: "completed" },
  3157. { content: "Polish the task rail", status: "in_progress" },
  3158. { content: "Run focused tests", status: "pending" },
  3159. { content: "Review narrow layouts", status: "pending" },
  3160. { content: "Update user documentation", status: "pending" },
  3161. { content: "Publish the test package", status: "pending" },
  3162. ],
  3163. },
  3164. });
  3165. const compact = app.tui.render(80).join("\n");
  3166. expect(compact).toContain("✓ Inspect Desktop behavior");
  3167. expect(compact).toContain("● Polish the task rail");
  3168. expect(compact).toContain("Ctrl+T expand");
  3169. expect(compact).not.toContain("Publish the test package");
  3170. expect(compact).not.toContain("todo_updated");
  3171. terminal.input?.("\x0f");
  3172. const transcriptDetailed = app.tui.render(80).join("\n");
  3173. expect(transcriptDetailed).toContain("Ctrl+T expand");
  3174. expect(transcriptDetailed).not.toContain("Publish the test package");
  3175. terminal.input?.("\x14");
  3176. const tasksExpanded = app.tui.render(80).join("\n");
  3177. expect(tasksExpanded).toContain(
  3178. "Todo list 1/6 · 5 remaining · Ctrl+T compact",
  3179. );
  3180. expect(tasksExpanded).toContain("Publish the test package");
  3181. terminal.input?.("\x0f");
  3182. expect(app.tui.render(80).join("\n")).toContain("Publish the test package");
  3183. app.controller.applyRuntimeTurnEvent("turn-todo", {
  3184. type: "generic",
  3185. eventType: "todo_updated",
  3186. turnId: "turn-todo",
  3187. data: {
  3188. todos: [
  3189. { content: "Inspect Desktop behavior", status: "completed" },
  3190. { content: "Polish the task rail", status: "completed" },
  3191. { content: "Run focused tests", status: "completed" },
  3192. { content: "Review narrow layouts", status: "completed" },
  3193. { content: "Update user documentation", status: "completed" },
  3194. { content: "Publish the test package", status: "completed" },
  3195. ],
  3196. },
  3197. });
  3198. expect(app.tui.render(80).join("\n")).toContain(
  3199. "✓ Todo list 6/6 completed",
  3200. );
  3201. await app.stop();
  3202. });
  3203. it("keeps settled Thinking hidden until Ctrl+O requests transcript details", async () => {
  3204. const terminal = new FakeTerminal();
  3205. const app = createTuiApp({
  3206. runtime: createRuntime(),
  3207. terminal,
  3208. version: "0.1.0",
  3209. workspaceDir: "/workspace",
  3210. });
  3211. app.start();
  3212. await app.ready;
  3213. app.transcript.upsert({
  3214. id: "thinking-detail-toggle",
  3215. kind: "thinking",
  3216. status: "succeeded",
  3217. content: "Private settled reasoning",
  3218. durationMs: 3_200,
  3219. createdAtMs: 1,
  3220. updatedAtMs: 3_201,
  3221. });
  3222. const compact = app.tui.render(80).join("\n");
  3223. expect(compact).toContain("Thought for 3.2s");
  3224. expect(compact).not.toContain("Private settled reasoning");
  3225. terminal.input?.("\x0f");
  3226. expect(app.tui.render(80).join("\n")).toContain(
  3227. "Private settled reasoning",
  3228. );
  3229. terminal.input?.("\x0f");
  3230. expect(app.tui.render(80).join("\n")).not.toContain(
  3231. "Private settled reasoning",
  3232. );
  3233. await app.stop();
  3234. });
  3235. it("returns from the conversation surface to Welcome after /new", async () => {
  3236. const terminal = new FakeTerminal();
  3237. const runtime = createRuntime();
  3238. const app = createTuiApp({
  3239. runtime,
  3240. terminal,
  3241. version: "0.1.0",
  3242. workspaceDir: "/workspace",
  3243. });
  3244. await app.ready;
  3245. await app.submit("Start a conversation");
  3246. expect(app.getSurface()).toBe("conversation");
  3247. await app.submit("/new");
  3248. expect(app.getSurface()).toBe("welcome");
  3249. expect(app.transcript.snapshot()).toEqual([]);
  3250. });
  3251. it("clears into a fresh conversation while keeping the previous session resumable", async () => {
  3252. const terminal = new FakeTerminal();
  3253. const runtime = createRuntime();
  3254. const app = createTuiApp({
  3255. runtime,
  3256. terminal,
  3257. version: "0.1.0",
  3258. workspaceDir: "/workspace",
  3259. });
  3260. await app.ready;
  3261. await app.submit("Keep this conversation");
  3262. expect(app.controller.snapshot().session?.sessionId).toBe("session-1");
  3263. await app.submit("/clear");
  3264. expect(app.getSurface()).toBe("welcome");
  3265. expect(app.transcript.snapshot()).toEqual([]);
  3266. expect(app.controller.snapshot()).toMatchObject({
  3267. status: "idle",
  3268. session: undefined,
  3269. sessions: [expect.objectContaining({ sessionId: "session-1" })],
  3270. });
  3271. expect(runtime.archiveSession).not.toHaveBeenCalled();
  3272. });
  3273. it("opens read-only Help above the Composer without using a TUI overlay", async () => {
  3274. const terminal = new FakeTerminal();
  3275. const runtime = createRuntime();
  3276. const app = createTuiApp({
  3277. runtime,
  3278. terminal,
  3279. version: "0.1.0",
  3280. workspaceDir: "/workspace",
  3281. });
  3282. const showOverlay = vi.spyOn(app.tui, "showOverlay");
  3283. app.start();
  3284. await app.ready;
  3285. const modelRequestsBeforeHelp = vi.mocked(runtime.listModels).mock.calls
  3286. .length;
  3287. const activeRunRequestsBeforeHelp = vi.mocked(runtime.getActiveRun).mock
  3288. .calls.length;
  3289. await app.submit("/help");
  3290. expect(runtime.sendMessage).not.toHaveBeenCalled();
  3291. expect(app.transcript.snapshot()).toEqual([]);
  3292. expect(app.tui.hasOverlay()).toBe(false);
  3293. expect(app.interaction.isActive()).toBe(true);
  3294. expect(terminal.mouseTracking).toBe(false);
  3295. terminal.input?.("m");
  3296. terminal.input?.("\r");
  3297. expect(app.tui.hasOverlay()).toBe(false);
  3298. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  3299. expect(app.editor.getText()).toBe("");
  3300. expect(runtime.listModels).toHaveBeenCalledTimes(modelRequestsBeforeHelp);
  3301. expect(runtime.getActiveRun).toHaveBeenCalledTimes(
  3302. activeRunRequestsBeforeHelp,
  3303. );
  3304. expect(showOverlay).not.toHaveBeenCalled();
  3305. await app.stop();
  3306. });
  3307. it("lets Help use the available terminal height instead of capping it at twelve rows", async () => {
  3308. const terminal = new FakeTerminal();
  3309. terminal.rows = 30;
  3310. const app = createTuiApp({
  3311. runtime: createRuntime(),
  3312. terminal,
  3313. version: "0.1.0",
  3314. workspaceDir: "/workspace",
  3315. });
  3316. app.start();
  3317. await app.submit("/help");
  3318. expect(app.interaction.current()?.render?.(terminal.columns)).toHaveLength(
  3319. 24,
  3320. );
  3321. terminal.rows = 18;
  3322. expect(app.interaction.current()?.render?.(terminal.columns)).toHaveLength(
  3323. 12,
  3324. );
  3325. await app.stop();
  3326. });
  3327. it("keeps steer executable and exposes it in slash-command discovery", async () => {
  3328. const terminal = new FakeTerminal();
  3329. const runtime = createRuntime();
  3330. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
  3331. schemaVersion: 1,
  3332. sessionId,
  3333. state: "running",
  3334. turnId: "turn-active",
  3335. actions: { steer: true },
  3336. }));
  3337. vi.mocked(runtime.steer).mockResolvedValue({
  3338. turnId: "turn-active",
  3339. mode: "steered",
  3340. });
  3341. const app = createTuiApp({
  3342. runtime,
  3343. terminal,
  3344. version: "0.1.0",
  3345. workspaceDir: "/workspace",
  3346. });
  3347. app.start();
  3348. await app.submit("Create session");
  3349. await app.submit("/help");
  3350. const helpPanel = app.interaction.current();
  3351. expect(helpPanel).toBeDefined();
  3352. expect(app.tui.hasOverlay()).toBe(false);
  3353. const helpPages: string[] = [];
  3354. for (let page = 0; page < 20; page += 1) {
  3355. const current = helpPanel?.render?.(100).join("\n") ?? "";
  3356. if (current === helpPages.at(-1)) break;
  3357. helpPages.push(current);
  3358. helpPanel?.handleInput?.("\x1b[6~");
  3359. }
  3360. const help = helpPages.join("\n");
  3361. expect(help).toContain("/steer <message>");
  3362. expect(help).not.toContain("/send-now");
  3363. expect(help).not.toContain("/retry");
  3364. helpPanel?.handleInput?.("\x1b");
  3365. await app.submit("/steer focus on the failing test");
  3366. expect(runtime.steer).toHaveBeenCalledWith(
  3367. expect.objectContaining({
  3368. sessionId: "session-1",
  3369. source: "api",
  3370. message: { content: "focus on the failing test" },
  3371. producerId: "mcode",
  3372. idempotencyKey: expect.stringMatching(/^run_action_/u),
  3373. }),
  3374. );
  3375. await app.stop();
  3376. });
  3377. it("refreshes Runtime steer capability before Enter submits the active Draft", async () => {
  3378. const terminal = new FakeTerminal();
  3379. const runtime = createRuntime();
  3380. let finishTurn: (() => void) | undefined;
  3381. let consumeSteer: (() => void) | undefined;
  3382. const steerConsumptionReady = new Promise<void>((resolve) => {
  3383. consumeSteer = resolve;
  3384. });
  3385. let steerAvailable = false;
  3386. vi.mocked(runtime.sendMessage).mockImplementation(
  3387. async function* sendMessage() {
  3388. yield {
  3389. type: "delta",
  3390. turnId: "turn-active",
  3391. content: "Working on it",
  3392. };
  3393. await steerConsumptionReady;
  3394. yield {
  3395. type: "message",
  3396. message: {
  3397. id: "message-steer",
  3398. turnId: "turn-active",
  3399. role: "user",
  3400. content: "focus on the failing test",
  3401. },
  3402. };
  3403. await new Promise<void>((resolve) => {
  3404. finishTurn = resolve;
  3405. });
  3406. yield { type: "done", turnId: "turn-active" };
  3407. },
  3408. );
  3409. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) =>
  3410. steerAvailable
  3411. ? {
  3412. schemaVersion: 1,
  3413. sessionId,
  3414. state: "running",
  3415. turnId: "turn-active",
  3416. actions: { steer: true },
  3417. }
  3418. : {
  3419. schemaVersion: 1,
  3420. sessionId,
  3421. state: "idle",
  3422. actions: { steer: false },
  3423. },
  3424. );
  3425. vi.mocked(runtime.steer).mockResolvedValue({
  3426. turnId: "turn-active",
  3427. mode: "steered",
  3428. });
  3429. const app = createTuiApp({
  3430. runtime,
  3431. terminal,
  3432. version: "0.1.0",
  3433. workspaceDir: "/workspace",
  3434. });
  3435. app.start();
  3436. await app.ready;
  3437. const submission = app.submit("Inspect the failure");
  3438. try {
  3439. await vi.waitFor(() =>
  3440. expect(app.tui.render(80).join("\n")).toContain("Running"),
  3441. );
  3442. steerAvailable = true;
  3443. terminal.input?.("focus on the failing test");
  3444. terminal.input?.("\r");
  3445. expect(app.editor.getText()).toBe("");
  3446. await vi.waitFor(() =>
  3447. expect(runtime.steer).toHaveBeenCalledWith(
  3448. expect.objectContaining({
  3449. sessionId: "session-1",
  3450. source: "api",
  3451. message: { content: "focus on the failing test" },
  3452. producerId: "mcode",
  3453. idempotencyKey: expect.stringMatching(/^run_action_/u),
  3454. requestedTurnId: "turn-active",
  3455. }),
  3456. ),
  3457. );
  3458. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  3459. kind: "user",
  3460. status: "pending",
  3461. content: "focus on the failing test",
  3462. userPresentation: "pending-steer",
  3463. });
  3464. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  3465. "↳ Next · focus on the failing test",
  3466. );
  3467. consumeSteer?.();
  3468. await vi.waitFor(() =>
  3469. expect(
  3470. app.transcript.snapshot().filter((cell) => cell.kind === "user"),
  3471. ).toEqual([
  3472. expect.objectContaining({ content: "Inspect the failure" }),
  3473. expect.objectContaining({
  3474. status: "succeeded",
  3475. content: "focus on the failing test",
  3476. sourceMessageId: "message-steer",
  3477. userPresentation: undefined,
  3478. }),
  3479. ]),
  3480. );
  3481. const rendered = app.tui.render(80).join("\n");
  3482. expect(rendered).toContain("Inspect the failure");
  3483. expect(rendered).toContain("focus on the failing test");
  3484. expect(stripAnsi(rendered)).not.toContain("↳ Next ·");
  3485. expect(app.editor.getText()).toBe("");
  3486. } finally {
  3487. consumeSteer?.();
  3488. await vi.waitFor(() => expect(finishTurn).toEqual(expect.any(Function)));
  3489. finishTurn?.();
  3490. await submission;
  3491. await app.stop();
  3492. }
  3493. });
  3494. it("queues with Alt+Enter, restores with Option+Up, then steers with Enter", async () => {
  3495. const terminal = new FakeTerminal();
  3496. const runtime = createRuntime();
  3497. const queuedItems: TuiQueuedMessage[] = [];
  3498. let finishTurn: (() => void) | undefined;
  3499. vi.mocked(runtime.sendMessage).mockImplementation(
  3500. async function* sendMessage() {
  3501. yield {
  3502. type: "delta",
  3503. turnId: "turn-active",
  3504. content: "Working on it",
  3505. };
  3506. await new Promise<void>((resolve) => {
  3507. finishTurn = resolve;
  3508. });
  3509. yield { type: "done", turnId: "turn-active" };
  3510. },
  3511. );
  3512. vi.mocked(runtime.enqueueMessage).mockImplementation(
  3513. async (sessionId, content) => {
  3514. const item: TuiQueuedMessage = {
  3515. itemId: "queue-guidance",
  3516. sessionId,
  3517. status: "queued",
  3518. source: "api",
  3519. content,
  3520. };
  3521. queuedItems.push(item);
  3522. return {
  3523. itemId: item.itemId,
  3524. status: item.status,
  3525. position: queuedItems.length,
  3526. };
  3527. },
  3528. );
  3529. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  3530. ...queuedItems,
  3531. ]);
  3532. vi.mocked(runtime.deleteQueuedMessage).mockImplementation(
  3533. async (_sessionId, itemId) => {
  3534. const index = queuedItems.findIndex((item) => item.itemId === itemId);
  3535. return index >= 0 ? queuedItems.splice(index, 1)[0] : undefined;
  3536. },
  3537. );
  3538. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
  3539. schemaVersion: 1,
  3540. sessionId,
  3541. state: "running",
  3542. turnId: "turn-active",
  3543. actions: { steer: true },
  3544. }));
  3545. const app = createTuiApp({
  3546. runtime,
  3547. terminal,
  3548. version: "0.1.0",
  3549. workspaceDir: "/workspace",
  3550. });
  3551. app.start();
  3552. await app.ready;
  3553. const submission = app.submit("Inspect the failure");
  3554. try {
  3555. await vi.waitFor(() =>
  3556. expect(app.tui.render(80).join("\n")).toContain("Running"),
  3557. );
  3558. terminal.input?.("Use the preview branch directly");
  3559. terminal.input?.("\x1b\r");
  3560. await vi.waitFor(() =>
  3561. expect(app.tui.render(80).join("\n")).toContain(
  3562. "Use the preview branch directly",
  3563. ),
  3564. );
  3565. await vi.waitFor(() =>
  3566. expect(runtime.listQueuedMessages).toHaveBeenCalledWith("session-1"),
  3567. );
  3568. expect(app.editor.getText()).toBe("");
  3569. terminal.input?.("\x1b[1;3A");
  3570. await vi.waitFor(() =>
  3571. expect(app.editor.getText()).toBe("Use the preview branch directly"),
  3572. );
  3573. expect(runtime.deleteQueuedMessage).toHaveBeenCalledWith(
  3574. "session-1",
  3575. "queue-guidance",
  3576. );
  3577. expect(runtime.steerQueuedMessage).not.toHaveBeenCalled();
  3578. await vi.waitFor(() =>
  3579. expect(app.tui.render(80).join("\n")).not.toContain("Queued ·"),
  3580. );
  3581. terminal.input?.("\r");
  3582. await vi.waitFor(() =>
  3583. expect(runtime.steer).toHaveBeenCalledWith(
  3584. expect.objectContaining({
  3585. sessionId: "session-1",
  3586. message: { content: "Use the preview branch directly" },
  3587. requestedTurnId: "turn-active",
  3588. }),
  3589. ),
  3590. );
  3591. expect(app.editor.getText()).toBe("");
  3592. } finally {
  3593. finishTurn?.();
  3594. await submission;
  3595. await app.stop();
  3596. }
  3597. });
  3598. it("renders /context from the Runtime-owned persisted context usage", async () => {
  3599. const runtime = createRuntime();
  3600. vi.mocked(runtime.getContextSnapshot).mockResolvedValue({
  3601. status: "live",
  3602. model: { provider: "minimax", id: "MiniMax-M3", contextWindow: 10_000 },
  3603. contextUsage: {
  3604. contextWindowTokens: 10_000,
  3605. usedTokens: 3_000,
  3606. totalCountSource: "PROVIDER_USAGE_ANCHORED",
  3607. components: [
  3608. { kind: "SYSTEM_PROMPT", tokens: 1_000 },
  3609. { kind: "MEMORY", tokens: 0 },
  3610. { kind: "TOOLS", tokens: 0 },
  3611. { kind: "SKILLS", tokens: 0 },
  3612. { kind: "MESSAGES", tokens: 2_000 },
  3613. { kind: "OTHER", tokens: 0 },
  3614. ],
  3615. },
  3616. });
  3617. const app = createTuiApp({
  3618. runtime,
  3619. terminal: new FakeTerminal(),
  3620. version: "0.1.0",
  3621. workspaceDir: "/workspace",
  3622. });
  3623. await app.submit("Create session");
  3624. const transcriptBeforeContext = app.transcript.snapshot();
  3625. await app.submit("/context");
  3626. expect(app.transcript.snapshot()).toEqual(transcriptBeforeContext);
  3627. expect(app.interaction.current()).toBeDefined();
  3628. const rendered = app.tui.render(80).join("\n");
  3629. expect(rendered).toContain("Context");
  3630. expect(rendered).toContain("3k/10k tokens (30% used)");
  3631. expect(rendered).toContain("Usage by category");
  3632. expect(rendered).toContain("Messages");
  3633. expect(rendered).toMatch(/[⛁⛀⛶]/u);
  3634. app.interaction.current()?.handleInput?.("\x1b");
  3635. expect(app.interaction.current()).toBeUndefined();
  3636. expect(app.transcript.snapshot()).toEqual(transcriptBeforeContext);
  3637. });
  3638. it("routes /init through the Runtime-owned init Skill and the normal Agent turn", async () => {
  3639. const terminal = new FakeTerminal();
  3640. const runtime = createRuntime();
  3641. vi.mocked(runtime.listSkills).mockResolvedValue({
  3642. skills: [
  3643. {
  3644. name: "init",
  3645. displayName: "Init",
  3646. description: "Analyze the codebase and generate AGENTS.md",
  3647. enabled: true,
  3648. sourceKind: "builtin",
  3649. },
  3650. ],
  3651. hasMore: false,
  3652. });
  3653. const app = createTuiApp({
  3654. runtime,
  3655. terminal,
  3656. version: "0.1.0",
  3657. workspaceDir: "/workspace",
  3658. });
  3659. app.start();
  3660. await app.ready;
  3661. await vi.waitFor(() => expect(runtime.listSkills).toHaveBeenCalled());
  3662. await app.submit("/init");
  3663. expect(runtime.sendMessage).toHaveBeenCalledWith(
  3664. expect.objectContaining({ id: "session-1", content: "/init" }),
  3665. expect.any(AbortSignal),
  3666. );
  3667. });
  3668. it("forwards literal slash-prefixed prompts without invoking local commands", async () => {
  3669. const runtime = createRuntime();
  3670. const app = createTuiApp({
  3671. runtime,
  3672. terminal: new FakeTerminal(),
  3673. version: "0.1.0",
  3674. workspaceDir: "/workspace",
  3675. });
  3676. const prompts = [
  3677. "/commands",
  3678. "/diff",
  3679. "/tool",
  3680. "/tools",
  3681. "/resumex",
  3682. "/renamex Renamed by a typo",
  3683. "/clearx",
  3684. "/tmp/sample-photo.JPG 用 read 工具直接读这个图片,告诉我是什么",
  3685. "/not-a-command explain what this text means",
  3686. "/context 这样还是会显示上下文信息",
  3687. ];
  3688. try {
  3689. app.start();
  3690. await app.ready;
  3691. for (const prompt of prompts) {
  3692. await app.submit(prompt);
  3693. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  3694. expect.objectContaining({ id: "session-1", content: prompt }),
  3695. expect.any(AbortSignal),
  3696. );
  3697. expect(app.interaction.current()).toBeUndefined();
  3698. expect(app.tui.hasOverlay()).toBe(false);
  3699. }
  3700. expect(runtime.sendMessage).toHaveBeenCalledTimes(prompts.length);
  3701. expect(runtime.renameSession).not.toHaveBeenCalled();
  3702. // Context metrics refresh independently; the overlay assertions above verify no local command ran.
  3703. expect(app.transcript.snapshot()).not.toContainEqual(
  3704. expect.objectContaining({ content: "Unknown command. Use /help." }),
  3705. );
  3706. } finally {
  3707. await app.stop();
  3708. }
  3709. });
  3710. it("keeps contextual commands local and submits other legacy names as prompts", async () => {
  3711. const terminal = new FakeTerminal();
  3712. const runtime = createRuntime();
  3713. const app = createTuiApp({
  3714. runtime,
  3715. terminal,
  3716. version: "0.1.0",
  3717. workspaceDir: "/workspace",
  3718. });
  3719. await app.submit("/queue");
  3720. expect(runtime.listQueuedMessages).not.toHaveBeenCalled();
  3721. expect(app.transcript.snapshot()).toEqual([]);
  3722. expect(app.tui.render(80).join("\n")).toContain(
  3723. "No messages are waiting and no response is currently running.",
  3724. );
  3725. await app.submit("/queue-clear");
  3726. expect(runtime.deleteQueuedMessage).not.toHaveBeenCalled();
  3727. await app.submit("/send-now do this first");
  3728. await app.submit("/retry");
  3729. expect(
  3730. vi
  3731. .mocked(runtime.sendMessage)
  3732. .mock.calls.map(([request]) => request.content),
  3733. ).toEqual(["/queue-clear", "/send-now do this first"]);
  3734. expect(app.tui.render(80).join("\n")).toContain(
  3735. "There is no failed response to retry in this Session.",
  3736. );
  3737. });
  3738. it("resends the failed user submission through /retry instead of sending the command as text", async () => {
  3739. const terminal = new FakeTerminal();
  3740. const runtime = createRuntime();
  3741. let attempt = 0;
  3742. vi.mocked(runtime.sendMessage).mockImplementation(
  3743. async function* sendMessage() {
  3744. attempt += 1;
  3745. if (attempt === 1) {
  3746. yield { type: "error", message: "terminated" };
  3747. return;
  3748. }
  3749. yield { type: "delta", content: "Recovered response" };
  3750. yield { type: "done" };
  3751. },
  3752. );
  3753. const app = createTuiApp({
  3754. runtime,
  3755. terminal,
  3756. version: "0.1.0",
  3757. workspaceDir: "/workspace",
  3758. });
  3759. await app.submit("Explain this failure");
  3760. expect(app.tui.render(100).join("\n")).toContain(
  3761. "The model connection ended before the response was completed.",
  3762. );
  3763. expect(app.tui.render(100).join("\n")).toContain(
  3764. "Run /retry to resend your last message.",
  3765. );
  3766. await app.submit("/retry");
  3767. expect(
  3768. vi
  3769. .mocked(runtime.sendMessage)
  3770. .mock.calls.map(([request]) => request.content),
  3771. ).toEqual(["Explain this failure", "Explain this failure"]);
  3772. expect(
  3773. vi
  3774. .mocked(runtime.sendMessage)
  3775. .mock.calls.some(([request]) => request.content === "/retry"),
  3776. ).toBe(false);
  3777. expect(app.transcript.snapshot()).toContainEqual(
  3778. expect.objectContaining({
  3779. kind: "assistant",
  3780. content: "Recovered response",
  3781. }),
  3782. );
  3783. await app.stop();
  3784. });
  3785. it("uses Runtime retry-continuation when a terminal failure has no local submission snapshot", async () => {
  3786. const terminal = new FakeTerminal();
  3787. const runtime = createRuntime();
  3788. const restoredSession = {
  3789. sessionId: "session-1",
  3790. title: "Restored session",
  3791. workspaceDir: "/workspace",
  3792. status: "error",
  3793. errorMessage: "terminated",
  3794. };
  3795. vi.mocked(runtime.listSessions).mockResolvedValue([restoredSession]);
  3796. vi.mocked(runtime.getSession).mockResolvedValue(restoredSession);
  3797. const app = createTuiApp({
  3798. runtime,
  3799. terminal,
  3800. version: "0.1.0",
  3801. workspaceDir: "/workspace",
  3802. });
  3803. app.start();
  3804. await app.ready;
  3805. await app.submit("/resume session-1");
  3806. expect(app.tui.render(100).join("\n")).toContain(
  3807. "The model connection ended before the response was completed.",
  3808. );
  3809. await app.submit("/retry");
  3810. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  3811. expect.objectContaining({
  3812. id: "session-1",
  3813. content: "",
  3814. clientIntent: "retry-continuation",
  3815. }),
  3816. expect.any(AbortSignal),
  3817. );
  3818. await app.stop();
  3819. });
  3820. it("reports service authentication failures without assuming the user needs to sign in", async () => {
  3821. const runtime = createRuntime();
  3822. vi.mocked(runtime.sendMessage).mockImplementation(
  3823. async function* sendMessage() {
  3824. yield { type: "error", message: "authentication failed" };
  3825. },
  3826. );
  3827. const app = createTuiApp({
  3828. runtime,
  3829. terminal: new FakeTerminal(),
  3830. version: "0.1.0",
  3831. workspaceDir: "/workspace",
  3832. });
  3833. await app.submit("Use the protected model");
  3834. expect(app.tui.render(100).join("\n")).toContain(
  3835. "The service rejected request authentication.",
  3836. );
  3837. expect(app.tui.render(100).join("\n")).not.toContain("Run /login");
  3838. expect(app.tui.render(100).join("\n")).not.toContain("Run /retry");
  3839. await app.submit("/retry");
  3840. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  3841. await app.stop();
  3842. });
  3843. it("cycles the shared permission mode with Alt+M without repeating the shortcut", async () => {
  3844. const terminal = new FakeTerminal();
  3845. const runtime = createRuntime();
  3846. const app = createTuiApp({
  3847. runtime,
  3848. terminal,
  3849. version: "0.1.0",
  3850. workspaceDir: "/workspace",
  3851. });
  3852. app.start();
  3853. await app.ready;
  3854. expect(app.tui.render(80).join("\n")).toContain("Auto");
  3855. expect(app.tui.render(80).join("\n")).not.toContain("Shift+Tab");
  3856. expect(app.tui.render(80).join("\n")).not.toContain(
  3857. "Shift+Tab switch mode",
  3858. );
  3859. terminal.input?.("\x1bm");
  3860. await vi.waitFor(() => {
  3861. expect(runtime.setPermissionMode).toHaveBeenCalledWith(
  3862. "bypassPermissions",
  3863. );
  3864. const rendered = app.tui.render(80).join("\n");
  3865. expect(rendered).toContain("Full access");
  3866. expect(rendered).not.toContain("Shift+Tab");
  3867. expect(rendered.match(/Full access/g)).toHaveLength(1);
  3868. expect(rendered).not.toContain("Desktop permissions:");
  3869. });
  3870. await app.stop();
  3871. });
  3872. it("projects Token Plan warnings into the status rail", async () => {
  3873. const terminal = new FakeTerminal();
  3874. const runtime = createRuntime();
  3875. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  3876. status: "ready",
  3877. defaultModel: "minimax/MiniMax-M2.7",
  3878. providerId: "minimax",
  3879. modelId: "MiniMax-M2.7",
  3880. authMode: "managed-login",
  3881. managedTokenPresent: true,
  3882. modelSource: "token-plan",
  3883. tokenPlanQuotaState: "available",
  3884. tokenPlanQuota: {
  3885. fiveHour: { remainingPercent: 30, unlimited: false },
  3886. weekly: { remainingPercent: 64, unlimited: false },
  3887. },
  3888. warnings: [],
  3889. });
  3890. const app = createTuiApp({
  3891. runtime,
  3892. terminal,
  3893. version: "0.1.0",
  3894. workspaceDir: "/workspace",
  3895. });
  3896. app.start();
  3897. await app.ready;
  3898. await app.submit("Measure this turn");
  3899. await vi.waitFor(() => {
  3900. const rendered = app.tui.render(120).join("\n");
  3901. expect(rendered).toContain("5h 30%");
  3902. expect(rendered).not.toContain("Week 64%");
  3903. });
  3904. await app.stop();
  3905. });
  3906. it("keeps Token Plan subscription state out of the status rail when no quota exists", async () => {
  3907. const terminal = new FakeTerminal();
  3908. const runtime = createRuntime();
  3909. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  3910. status: "ready",
  3911. defaultModel: "minimax/MiniMax-M3",
  3912. providerId: "minimax",
  3913. modelId: "MiniMax-M3",
  3914. authMode: "managed-login",
  3915. managedTokenPresent: true,
  3916. modelSource: "token-plan",
  3917. tokenPlanQuotaState: "not-subscribed",
  3918. warnings: [],
  3919. });
  3920. const app = createTuiApp({
  3921. runtime,
  3922. terminal,
  3923. version: "0.1.0",
  3924. workspaceDir: "/workspace",
  3925. });
  3926. app.start();
  3927. await app.ready;
  3928. await app.submit("Measure this turn");
  3929. await vi.waitFor(() => {
  3930. const rendered = app.tui.render(120).join("\n");
  3931. expect(rendered).toContain("✦ MiniMax M2.7");
  3932. expect(rendered).not.toMatch(/Context 5%|Quota|Plan|5h|Week/u);
  3933. });
  3934. await app.stop();
  3935. });
  3936. it("keeps the current permission mode when an Alt+M update fails", async () => {
  3937. const terminal = new FakeTerminal();
  3938. const runtime = createRuntime();
  3939. vi.mocked(runtime.setPermissionMode).mockRejectedValueOnce(
  3940. new Error("config is read-only"),
  3941. );
  3942. const app = createTuiApp({
  3943. runtime,
  3944. terminal,
  3945. version: "0.1.0",
  3946. workspaceDir: "/workspace",
  3947. });
  3948. app.start();
  3949. await app.ready;
  3950. terminal.input?.("\x1bm");
  3951. await vi.waitFor(() => {
  3952. expect(app.tui.render(80).join("\n")).toContain("Auto");
  3953. expect(app.tui.render(80).join("\n")).not.toContain("FULL");
  3954. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  3955. kind: "warning",
  3956. content:
  3957. "Permission mode was not changed: config is read-only. Retry /permission or Alt+M.",
  3958. });
  3959. });
  3960. await app.stop();
  3961. });
  3962. it("arms Plan with Shift+Tab and sends the one-shot Runtime intent", async () => {
  3963. const terminal = new FakeTerminal();
  3964. const runtime = createRuntime();
  3965. const app = createTuiApp({
  3966. runtime,
  3967. terminal,
  3968. version: "0.1.0",
  3969. workspaceDir: "/workspace",
  3970. });
  3971. app.start();
  3972. await app.ready;
  3973. terminal.input?.("\x1b[Z");
  3974. expect(app.tui.render(100).join("\n")).toContain("PLAN next");
  3975. expect(app.tui.render(100).join("\n")).toContain(
  3976. "Plan Mode · next message enters Plan",
  3977. );
  3978. terminal.input?.("计");
  3979. expect(app.tui.render(100).join("\n")).toContain(
  3980. "Plan Mode · next message enters Plan",
  3981. );
  3982. expect(app.tui.render(32).join("\n")).toContain("Plan Mode");
  3983. terminal.input?.("\x7f");
  3984. expect(app.editor.getText()).toBe("");
  3985. expect(app.tui.render(100).join("\n")).toContain(
  3986. "Plan Mode · next message enters Plan",
  3987. );
  3988. terminal.input?.("计");
  3989. terminal.input?.("划");
  3990. expect(app.editor.getText()).toBe("计划");
  3991. expect(app.tui.render(100).join("\n")).toContain("PLAN next");
  3992. expect(app.tui.render(100).join("\n")).toContain(
  3993. "Plan Mode · next message enters Plan",
  3994. );
  3995. terminal.input?.("\r");
  3996. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
  3997. await app.controller.whenIdle();
  3998. expect(runtime.sendMessage).toHaveBeenCalledWith(
  3999. expect.objectContaining({
  4000. content: "计划",
  4001. clientIntent: "plan-entry",
  4002. }),
  4003. expect.any(AbortSignal),
  4004. );
  4005. expect(app.tui.render(100).join("\n")).toContain("PLAN");
  4006. expect(app.tui.render(100).join("\n")).toContain("Auto");
  4007. await app.stop();
  4008. });
  4009. it("keeps ordinary messages in Plan and exits only with an explicit one-shot intent", async () => {
  4010. const runtime = createRuntime();
  4011. const app = createTuiApp({
  4012. runtime,
  4013. terminal: new FakeTerminal(),
  4014. version: "0.1.0",
  4015. workspaceDir: "/workspace",
  4016. });
  4017. app.start();
  4018. await app.ready;
  4019. await app.submit("/plan on");
  4020. await app.submit("Draft the implementation plan");
  4021. await app.submit("Refine the verification section");
  4022. expect(runtime.sendMessage).toHaveBeenNthCalledWith(
  4023. 2,
  4024. expect.not.objectContaining({ clientIntent: expect.anything() }),
  4025. expect.any(AbortSignal),
  4026. );
  4027. expect(app.tui.render(100).join("\n")).toContain(
  4028. "/workspace │ PLAN │ Auto",
  4029. );
  4030. await app.submit("/plan off");
  4031. await app.submit("Implement the approved direction");
  4032. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  4033. expect.objectContaining({ clientIntent: "plan-exit" }),
  4034. expect.any(AbortSignal),
  4035. );
  4036. expect(app.tui.render(100).join("\n")).not.toContain("PLAN");
  4037. await app.stop();
  4038. });
  4039. it("keeps the one-shot Plan intent armed when direct admission rejects it", async () => {
  4040. const runtime = createRuntime();
  4041. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  4042. async function* rejectedAdmission() {
  4043. yield* [] as TuiStreamEvent[];
  4044. throw Object.assign(new Error("Plan entry is disabled"), {
  4045. code: "local_plan_entry_disabled",
  4046. });
  4047. },
  4048. );
  4049. const app = createTuiApp({
  4050. runtime,
  4051. terminal: new FakeTerminal(),
  4052. version: "0.1.0",
  4053. workspaceDir: "/workspace",
  4054. });
  4055. app.start();
  4056. await app.ready;
  4057. await app.submit("/plan on");
  4058. await app.submit("Plan this after the feature is enabled");
  4059. expect(app.tui.render(100).join("\n")).toContain("PLAN next");
  4060. await app.submit("Retry the same Plan intent");
  4061. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  4062. expect.objectContaining({ clientIntent: "plan-entry" }),
  4063. expect.any(AbortSignal),
  4064. );
  4065. await app.stop();
  4066. });
  4067. it("settles a Plan transition from authoritative Session metadata when the stream is empty", async () => {
  4068. const runtime = createRuntime();
  4069. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  4070. async function* emptyAcceptedStream() {
  4071. yield* [] as TuiStreamEvent[];
  4072. },
  4073. );
  4074. vi.mocked(runtime.getSession).mockResolvedValue({
  4075. sessionId: "session-1",
  4076. workspace: "/workspace",
  4077. interactionMode: "plan",
  4078. });
  4079. const app = createTuiApp({
  4080. runtime,
  4081. terminal: new FakeTerminal(),
  4082. version: "0.1.0",
  4083. workspaceDir: "/workspace",
  4084. });
  4085. app.start();
  4086. await app.ready;
  4087. await app.submit("/plan on");
  4088. await app.submit("Plan without emitting a stream event");
  4089. expect(runtime.getSession).toHaveBeenCalledWith("session-1");
  4090. expect(app.tui.render(100).join("\n")).toContain(
  4091. "/workspace │ PLAN │ Auto",
  4092. );
  4093. expect(app.tui.render(100).join("\n")).not.toContain("PLAN next");
  4094. await app.stop();
  4095. });
  4096. it("clears accepted Plan entry while authoritative metadata refresh is unavailable", async () => {
  4097. const runtime = createRuntime();
  4098. vi.mocked(runtime.getSession).mockRejectedValue(
  4099. new Error("metadata temporarily unavailable"),
  4100. );
  4101. const app = createTuiApp({
  4102. runtime,
  4103. terminal: new FakeTerminal(),
  4104. version: "0.1.0",
  4105. workspaceDir: "/workspace",
  4106. });
  4107. app.start();
  4108. await app.ready;
  4109. await app.submit("/plan on");
  4110. await app.submit("OK");
  4111. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4112. expect.objectContaining({ content: "OK", clientIntent: "plan-entry" }),
  4113. expect.any(AbortSignal),
  4114. );
  4115. expect(app.tui.render(100).join("\n")).not.toContain("/workspace │ PLAN");
  4116. expect(app.tui.render(100).join("\n")).not.toContain("DEFAULT next");
  4117. await app.stop();
  4118. });
  4119. it("preserves Plan intent through direct busy fallback into the Runtime Queue", async () => {
  4120. const runtime = createRuntime();
  4121. vi.mocked(runtime.listModels).mockResolvedValue([
  4122. {
  4123. providerId: "minimax",
  4124. modelId: "MiniMax-M2.7",
  4125. selected: true,
  4126. variant: "",
  4127. },
  4128. ]);
  4129. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  4130. async function* busyAdmission() {
  4131. yield* [] as TuiStreamEvent[];
  4132. throw Object.assign(new Error("Session is busy"), {
  4133. code: "local_session_busy",
  4134. });
  4135. },
  4136. );
  4137. const app = createTuiApp({
  4138. runtime,
  4139. terminal: new FakeTerminal(),
  4140. version: "0.1.0",
  4141. workspaceDir: "/workspace",
  4142. });
  4143. app.start();
  4144. await app.ready;
  4145. await app.submit("/plan on");
  4146. await app.submit("Queue this Plan request");
  4147. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  4148. "session-1",
  4149. "Queue this Plan request",
  4150. {
  4151. attachments: [],
  4152. clientIntent: "plan-entry",
  4153. model: { providerId: "minimax", modelId: "MiniMax-M2.7", variant: "" },
  4154. },
  4155. );
  4156. expect(app.tui.render(100).join("\n")).not.toContain("PLAN queued");
  4157. await app.stop();
  4158. });
  4159. it("binds a one-shot Plan intent to only the first concurrent submission", async () => {
  4160. let releaseFirstEvent: (() => void) | undefined;
  4161. const firstEventGate = new Promise<void>((resolve) => {
  4162. releaseFirstEvent = resolve;
  4163. });
  4164. const runtime = createRuntime();
  4165. vi.mocked(runtime.sendMessage).mockImplementation(
  4166. async function* delayedAdmission() {
  4167. await firstEventGate;
  4168. yield { type: "delta", content: "Planning" };
  4169. yield { type: "done" };
  4170. },
  4171. );
  4172. const app = createTuiApp({
  4173. runtime,
  4174. terminal: new FakeTerminal(),
  4175. version: "0.1.0",
  4176. workspaceDir: "/workspace",
  4177. });
  4178. app.start();
  4179. await app.ready;
  4180. await app.submit("/plan on");
  4181. const first = app.submit("Plan the implementation");
  4182. await vi.waitFor(() =>
  4183. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  4184. );
  4185. await app.submit("Queue a follow-up while admission is quiet");
  4186. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4187. expect.objectContaining({ clientIntent: "plan-entry" }),
  4188. expect.any(AbortSignal),
  4189. );
  4190. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  4191. "session-1",
  4192. "Queue a follow-up while admission is quiet",
  4193. {
  4194. attachments: [],
  4195. model: { providerId: "minimax", modelId: "MiniMax-M2.7" },
  4196. },
  4197. );
  4198. releaseFirstEvent?.();
  4199. await first;
  4200. await app.stop();
  4201. });
  4202. it("shows the Desktop-aligned confirmation when the Agent calls EnterPlanMode", async () => {
  4203. let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  4204. const runtime = createRuntime();
  4205. vi.mocked(runtime.watchEvents).mockImplementation(
  4206. async function* watchEvents(signal) {
  4207. const event = await new Promise<TuiRuntimeEvent | undefined>(
  4208. (resolve) => {
  4209. emitEvent = resolve;
  4210. signal.addEventListener("abort", () => resolve(undefined), {
  4211. once: true,
  4212. });
  4213. },
  4214. );
  4215. if (event) yield event;
  4216. await new Promise<void>((resolve) => {
  4217. signal.addEventListener("abort", resolve, { once: true });
  4218. });
  4219. },
  4220. );
  4221. const app = createTuiApp({
  4222. runtime,
  4223. terminal: new FakeTerminal(),
  4224. version: "0.1.0",
  4225. workspaceDir: "/workspace",
  4226. });
  4227. app.start();
  4228. await app.ready;
  4229. await app.submit("Plan a complex change");
  4230. await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
  4231. const askEvent = runtimeEvent({
  4232. type: "questionnaire.ask",
  4233. timestamp: Date.now(),
  4234. source: "runtime",
  4235. payload: {
  4236. sessionId: "session-1",
  4237. agentName: "mavis",
  4238. request: planEntryEventRequest("plan-entry-agent-tool"),
  4239. },
  4240. });
  4241. expect(askEvent).toMatchObject({
  4242. type: "questionnaire.ask",
  4243. sessionId: "session-1",
  4244. request: { id: "plan-entry-agent-tool", mode: "plan" },
  4245. });
  4246. emitEvent?.(askEvent);
  4247. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  4248. const panel = app.interaction.current();
  4249. const rendered = panel?.render?.(100).join("\n") ?? "";
  4250. expect(rendered).toContain("Use Plan mode?");
  4251. expect(rendered).toContain(
  4252. "Plan mode structures complex tasks before execution.",
  4253. );
  4254. expect(rendered).toContain("Continue with plan");
  4255. expect(rendered).toContain("Deny");
  4256. panel?.handleInput?.("\r");
  4257. await vi.waitFor(() =>
  4258. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  4259. "mavis",
  4260. "plan-entry-agent-tool",
  4261. [
  4262. {
  4263. stepId: "plan-enter",
  4264. selectedOptionIds: ["confirm"],
  4265. selectedOther: false,
  4266. },
  4267. ],
  4268. ),
  4269. );
  4270. await app.stop();
  4271. });
  4272. it("keeps a pending Plan exit armed when steer guides the current Plan Turn", async () => {
  4273. let finishTurn: (() => void) | undefined;
  4274. let interactionMode: "plan" | undefined;
  4275. const runtime = createRuntime();
  4276. vi.mocked(runtime.getSession).mockImplementation(async () => ({
  4277. sessionId: "session-1",
  4278. workspace: "/workspace",
  4279. ...(interactionMode ? { interactionMode } : {}),
  4280. }));
  4281. vi.mocked(runtime.sendMessage).mockImplementation(
  4282. async function* activePlanTurn() {
  4283. interactionMode = "plan";
  4284. yield { type: "delta", content: "Drafting the plan" };
  4285. await new Promise<void>((resolve) => {
  4286. finishTurn = resolve;
  4287. });
  4288. yield { type: "done" };
  4289. },
  4290. );
  4291. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
  4292. schemaVersion: 1,
  4293. sessionId,
  4294. state: "running",
  4295. turnId: "turn-plan",
  4296. actions: { steer: true },
  4297. }));
  4298. vi.mocked(runtime.steer).mockResolvedValue({
  4299. turnId: "turn-plan",
  4300. mode: "steered",
  4301. });
  4302. const app = createTuiApp({
  4303. runtime,
  4304. terminal: new FakeTerminal(),
  4305. version: "0.1.0",
  4306. workspaceDir: "/workspace",
  4307. });
  4308. app.start();
  4309. await app.ready;
  4310. await app.submit("/plan on");
  4311. const planTurn = app.submit("Draft a plan");
  4312. await vi.waitFor(() =>
  4313. expect(app.tui.render(100).join("\n")).toContain(
  4314. "/workspace │ PLAN │ Auto",
  4315. ),
  4316. );
  4317. await app.submit("/plan off");
  4318. await app.submit("/steer include rollback checks");
  4319. expect(runtime.steer).toHaveBeenCalledWith(
  4320. expect.objectContaining({
  4321. sessionId: "session-1",
  4322. message: { content: "include rollback checks" },
  4323. }),
  4324. );
  4325. expect(app.tui.render(100).join("\n")).toContain("DEFAULT next");
  4326. finishTurn?.();
  4327. await planTurn;
  4328. await app.stop();
  4329. });
  4330. it("does not arm a mode transition while a Plan Review is pending", async () => {
  4331. let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  4332. const runtime = createRuntime();
  4333. vi.mocked(runtime.watchEvents).mockImplementation(
  4334. async function* watchEvents(signal) {
  4335. const event = await new Promise<TuiRuntimeEvent | undefined>(
  4336. (resolve) => {
  4337. emitEvent = resolve;
  4338. signal.addEventListener("abort", () => resolve(undefined), {
  4339. once: true,
  4340. });
  4341. },
  4342. );
  4343. if (event) yield event;
  4344. await new Promise<void>((resolve) => {
  4345. signal.addEventListener("abort", resolve, { once: true });
  4346. });
  4347. },
  4348. );
  4349. const terminal = new FakeTerminal();
  4350. const app = createTuiApp({
  4351. runtime,
  4352. terminal,
  4353. version: "0.1.0",
  4354. workspaceDir: "/workspace",
  4355. });
  4356. app.start();
  4357. await app.ready;
  4358. await app.submit("/plan on");
  4359. await app.submit("Draft a plan");
  4360. await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
  4361. emitEvent?.(
  4362. runtimeEvent({
  4363. type: "questionnaire.ask",
  4364. timestamp: Date.now(),
  4365. source: "runtime",
  4366. payload: {
  4367. sessionId: "session-1",
  4368. agentName: "mavis",
  4369. request: planReviewEventRequest("plan-review-mode-guard"),
  4370. },
  4371. }),
  4372. );
  4373. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  4374. // The compact panel owns the decision; the frozen plan is projected to the Transcript.
  4375. expect(app.interaction.current()?.render?.(100).join("\n")).toContain(
  4376. "Plan complete. What would you like to do?",
  4377. );
  4378. expect(app.tui.render(100).join("\n")).toContain("Frozen plan");
  4379. terminal.input?.("\x1b[Z");
  4380. expect(app.interaction.isActive()).toBe(true);
  4381. expect(app.tui.render(100).join("\n")).toContain(
  4382. "/workspace │ PLAN │ Auto",
  4383. );
  4384. expect(app.tui.render(100).join("\n")).not.toContain("DEFAULT next");
  4385. await app.submit("/plan off");
  4386. expect(app.interaction.isActive()).toBe(true);
  4387. expect(app.tui.render(100).join("\n")).toContain(
  4388. "/workspace │ PLAN │ Auto",
  4389. );
  4390. expect(app.tui.render(100).join("\n")).not.toContain("DEFAULT next");
  4391. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  4392. await app.submit("/steer bypass the review");
  4393. expect(app.interaction.isActive()).toBe(true);
  4394. expect(runtime.steer).not.toHaveBeenCalled();
  4395. app.interaction.current()?.handleInput?.("\u001b");
  4396. await vi.waitFor(() =>
  4397. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  4398. "mavis",
  4399. "plan-review-mode-guard",
  4400. [expect.objectContaining({ skipped: true })],
  4401. ),
  4402. );
  4403. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  4404. expect(app.tui.render(100).join("\n")).toContain(
  4405. "/workspace │ PLAN │ Auto",
  4406. );
  4407. await app.stop();
  4408. });
  4409. it("streams Plan feedback and replaces it with the revised Plan Review", async () => {
  4410. let emitReview: ((event: TuiRuntimeEvent) => void) | undefined;
  4411. let releaseContinuation: (() => void) | undefined;
  4412. let finishReply: ((value: boolean) => void) | undefined;
  4413. const runtime = createRuntime();
  4414. vi.mocked(runtime.replyQuestionnaire).mockImplementation(
  4415. async () =>
  4416. await new Promise<boolean>((resolve) => {
  4417. finishReply = resolve;
  4418. }),
  4419. );
  4420. vi.mocked(runtime.watchEvents).mockImplementation(
  4421. async function* watchEvents(signal) {
  4422. const review = await new Promise<TuiRuntimeEvent | undefined>(
  4423. (resolve) => {
  4424. emitReview = resolve;
  4425. signal.addEventListener("abort", () => resolve(undefined), {
  4426. once: true,
  4427. });
  4428. },
  4429. );
  4430. if (!review || signal.aborted) return;
  4431. yield review;
  4432. await new Promise<void>((resolve) => {
  4433. releaseContinuation = resolve;
  4434. signal.addEventListener("abort", resolve, { once: true });
  4435. });
  4436. if (signal.aborted) return;
  4437. const turnId = "turn-runtime-plan-feedback";
  4438. yield runtimeEvent({
  4439. type: "session.start",
  4440. timestamp: Date.now(),
  4441. source: "runtime",
  4442. payload: { sessionId: "session-1", turnId },
  4443. });
  4444. vi.mocked(runtime.getMessages).mockResolvedValue([
  4445. {
  4446. id: "assistant-revised-plan",
  4447. role: "assistant",
  4448. content: "I revised the plan with rollback coverage.",
  4449. },
  4450. ]);
  4451. yield runtimeEvent({
  4452. type: "questionnaire.ask",
  4453. timestamp: Date.now(),
  4454. source: "runtime",
  4455. payload: {
  4456. sessionId: "session-1",
  4457. agentName: "mavis",
  4458. request: {
  4459. ...planReviewEventRequest("plan-review-feedback-revised"),
  4460. modePayload: {
  4461. planReview: {
  4462. markdown:
  4463. "# Revised frozen plan\n\nIncludes rollback coverage.",
  4464. path: "/history/session-1/artifacts/plan.md",
  4465. },
  4466. },
  4467. },
  4468. },
  4469. });
  4470. yield runtimeEvent({
  4471. type: "session.finish",
  4472. timestamp: Date.now(),
  4473. source: "runtime",
  4474. payload: { sessionId: "session-1", turnId },
  4475. });
  4476. finishReply?.(true);
  4477. await new Promise<void>((resolve) => {
  4478. signal.addEventListener("abort", resolve, { once: true });
  4479. });
  4480. },
  4481. );
  4482. const terminal = new FakeTerminal();
  4483. const app = createTuiApp({
  4484. runtime,
  4485. terminal,
  4486. version: "0.1.0",
  4487. workspaceDir: "/workspace",
  4488. });
  4489. app.start();
  4490. await app.ready;
  4491. await app.submit("/plan on");
  4492. await app.submit("Draft a plan");
  4493. await vi.waitFor(() => expect(emitReview).toBeTypeOf("function"));
  4494. emitReview?.(
  4495. runtimeEvent({
  4496. type: "questionnaire.ask",
  4497. timestamp: Date.now(),
  4498. source: "runtime",
  4499. payload: {
  4500. sessionId: "session-1",
  4501. agentName: "mavis",
  4502. request: planReviewEventRequest("plan-review-feedback-live"),
  4503. },
  4504. }),
  4505. );
  4506. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  4507. terminal.input?.("\u001b[B");
  4508. terminal.input?.("\u001b[B");
  4509. terminal.input?.("\r");
  4510. for (const character of "Add rollback coverage")
  4511. terminal.input?.(character);
  4512. terminal.input?.("\r");
  4513. await vi.waitFor(() => expect(finishReply).toBeTypeOf("function"));
  4514. releaseContinuation?.();
  4515. await vi.waitFor(() =>
  4516. expect(
  4517. app.transcript
  4518. .snapshot()
  4519. .map((cell) => cell.content)
  4520. .join("\n"),
  4521. ).toContain("I revised the plan with rollback coverage."),
  4522. );
  4523. expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
  4524. "session-1",
  4525. "turn-runtime-plan-feedback",
  4526. expect.any(AbortSignal),
  4527. );
  4528. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  4529. // The revised plan is projected to the Transcript; the panel stays the compact decision.
  4530. expect(app.interaction.current()?.render?.(100).join("\n")).toContain(
  4531. "Plan complete. What would you like to do?",
  4532. );
  4533. expect(app.tui.render(100).join("\n")).toContain("Revised frozen plan");
  4534. expect(app.tui.render(100).join("\n")).not.toContain(
  4535. "Message · Enter send",
  4536. );
  4537. await app.stop();
  4538. });
  4539. it("supports explicit /plan and /permission mode commands", async () => {
  4540. const runtime = createRuntime();
  4541. const app = createTuiApp({
  4542. runtime,
  4543. terminal: new FakeTerminal(),
  4544. version: "0.1.0",
  4545. workspaceDir: "/workspace",
  4546. });
  4547. app.start();
  4548. await app.ready;
  4549. await app.submit("/plan on");
  4550. expect(app.tui.render(100).join("\n")).toContain("PLAN next");
  4551. await app.submit("/permission full");
  4552. expect(runtime.setPermissionMode).toHaveBeenCalledWith("bypassPermissions");
  4553. expect(app.tui.render(100).join("\n")).toContain("Full access");
  4554. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4555. await app.submit("Plan with Full access");
  4556. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4557. expect.objectContaining({ clientIntent: "plan-entry" }),
  4558. expect.any(AbortSignal),
  4559. );
  4560. expect(app.tui.render(100).join("\n")).toContain("PLAN");
  4561. expect(app.tui.render(100).join("\n")).toContain("Full access");
  4562. await app.stop();
  4563. });
  4564. it("opens a permission mode selector for bare /permission", async () => {
  4565. const runtime = createRuntime();
  4566. const terminal = new FakeTerminal();
  4567. const app = createTuiApp({
  4568. runtime,
  4569. terminal,
  4570. version: "0.1.0",
  4571. workspaceDir: "/workspace",
  4572. });
  4573. app.start();
  4574. await app.ready;
  4575. await app.submit("/permission");
  4576. expect(app.interaction.isActive()).toBe(true);
  4577. const rendered = app.interaction.current()?.render?.(100).join("\n") ?? "";
  4578. expect(rendered).toContain("╭─ Permission");
  4579. expect(rendered).toContain("Current · Auto");
  4580. expect(rendered).toContain("ASK");
  4581. expect(rendered).toContain("› AUTO");
  4582. expect(rendered).toContain("FULL");
  4583. expect(runtime.setPermissionMode).not.toHaveBeenCalled();
  4584. terminal.input?.("\u001b[B");
  4585. terminal.input?.("\r");
  4586. await vi.waitFor(() =>
  4587. expect(runtime.setPermissionMode).toHaveBeenCalledWith(
  4588. "bypassPermissions",
  4589. ),
  4590. );
  4591. expect(app.interaction.isActive()).toBe(false);
  4592. expect(app.tui.render(100).join("\n")).toContain("Full access");
  4593. await app.submit("/permission status");
  4594. expect(app.interaction.isActive()).toBe(false);
  4595. expect(
  4596. app.transcript
  4597. .snapshot()
  4598. .map((cell) => cell.content)
  4599. .join("\n"),
  4600. ).toContain("Permission mode: Full access.");
  4601. await app.stop();
  4602. });
  4603. it("opens the latest settled Plan as a read-only full snapshot", async () => {
  4604. const runtime = createRuntime();
  4605. vi.mocked(runtime.getLatestPlanReview).mockResolvedValue(
  4606. planReviewEventRequest("plan-review-settled"),
  4607. );
  4608. const app = createTuiApp({
  4609. runtime,
  4610. terminal: new FakeTerminal(),
  4611. version: "0.1.0",
  4612. workspaceDir: "/workspace",
  4613. });
  4614. app.start();
  4615. await app.ready;
  4616. await app.openSession("session-1");
  4617. await app.submit("/plan view");
  4618. expect(runtime.getLatestPlanReview).toHaveBeenCalledWith(
  4619. "mavis",
  4620. "session-1",
  4621. );
  4622. const rendered = app.interaction.current()?.render?.(100).join("\n") ?? "";
  4623. expect(rendered).toContain("Frozen plan");
  4624. expect(rendered).toContain("/history/session-1/artifacts/plan.md");
  4625. expect(rendered).not.toContain("Agree and start implementation");
  4626. app.interaction.current()?.handleInput?.("\u001b");
  4627. expect(app.interaction.isActive()).toBe(false);
  4628. await app.stop();
  4629. });
  4630. it("does not open a settled Plan after the active Session changes", async () => {
  4631. let resolveReview:
  4632. | ((request: TuiQuestionnaireRequest | undefined) => void)
  4633. | undefined;
  4634. const runtime = createRuntime();
  4635. vi.mocked(runtime.getLatestPlanReview).mockImplementation(
  4636. async () =>
  4637. await new Promise<TuiQuestionnaireRequest | undefined>((resolve) => {
  4638. resolveReview = resolve;
  4639. }),
  4640. );
  4641. const app = createTuiApp({
  4642. runtime,
  4643. terminal: new FakeTerminal(),
  4644. version: "0.1.0",
  4645. workspaceDir: "/workspace",
  4646. });
  4647. app.start();
  4648. await app.ready;
  4649. await app.openSession("session-1");
  4650. const viewing = app.submit("/plan view");
  4651. await vi.waitFor(() => expect(resolveReview).toBeTypeOf("function"));
  4652. await app.openSession("session-2");
  4653. resolveReview?.(planReviewEventRequest("stale-plan-review"));
  4654. await viewing;
  4655. expect(app.interaction.isActive()).toBe(false);
  4656. expect(app.tui.render(100).join("\n")).not.toContain("Frozen plan");
  4657. await app.stop();
  4658. });
  4659. it("blocks Plan entry but still allows Plan exit when the Runtime capability is disabled", async () => {
  4660. const runtime = createRuntime();
  4661. vi.mocked(runtime.getPlanModeCapabilities).mockResolvedValue({
  4662. entryEnabled: false,
  4663. });
  4664. const terminal = new FakeTerminal();
  4665. const app = createTuiApp({
  4666. runtime,
  4667. terminal,
  4668. version: "0.1.0",
  4669. workspaceDir: "/workspace",
  4670. });
  4671. app.start();
  4672. await app.ready;
  4673. await app.openSession("session-1");
  4674. terminal.input?.("\x1b[Z");
  4675. await app.submit("/plan on");
  4676. expect(app.tui.render(100).join("\n")).not.toContain("PLAN next");
  4677. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4678. vi.mocked(runtime.getSession).mockResolvedValue({
  4679. sessionId: "session-1",
  4680. workspace: "/workspace",
  4681. interactionMode: "plan",
  4682. });
  4683. await app.controller.refreshSessionMetadata("session-1");
  4684. terminal.input?.("\x1b[Z");
  4685. expect(app.tui.render(100).join("\n")).toContain("DEFAULT next");
  4686. await app.stop();
  4687. });
  4688. it("fails closed when the Runtime Plan capability cannot be loaded", async () => {
  4689. const runtime = createRuntime();
  4690. vi.mocked(runtime.getPlanModeCapabilities).mockRejectedValue(
  4691. new Error("Runtime unavailable"),
  4692. );
  4693. const terminal = new FakeTerminal();
  4694. const app = createTuiApp({
  4695. runtime,
  4696. terminal,
  4697. version: "0.1.0",
  4698. workspaceDir: "/workspace",
  4699. });
  4700. app.start();
  4701. await app.ready;
  4702. terminal.input?.("\x1b[Z");
  4703. await app.submit("/plan on");
  4704. expect(app.tui.render(100).join("\n")).not.toContain("PLAN next");
  4705. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4706. await app.stop();
  4707. });
  4708. it("submits the hidden Runtime engineering log command name as an ordinary prompt", async () => {
  4709. const terminal = new FakeTerminal();
  4710. const runtime = createRuntime();
  4711. const app = createTuiApp({
  4712. runtime,
  4713. terminal,
  4714. version: "0.1.0",
  4715. workspaceDir: "/workspace",
  4716. runtimeLogDirectory: "/home/dev/.minimax/v2/observability/logs",
  4717. });
  4718. await app.submit("/logs");
  4719. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4720. expect.objectContaining({ id: "session-1", content: "/logs" }),
  4721. expect.any(AbortSignal),
  4722. );
  4723. });
  4724. it("exposes sanitized checks and submits the hidden /config name as ordinary text", async () => {
  4725. const terminal = new FakeTerminal();
  4726. const runtime = createRuntime();
  4727. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  4728. {
  4729. requestId: "permission-1",
  4730. sessionId: "session-1",
  4731. toolName: "bash",
  4732. toolDescription: "Run tests",
  4733. },
  4734. ]);
  4735. const app = createTuiApp({
  4736. runtime,
  4737. terminal,
  4738. version: "0.1.0",
  4739. workspaceDir: "/workspace",
  4740. });
  4741. await app.submit("/doctor");
  4742. const doctorOutput = app.transcript.snapshot().at(-1)?.content ?? "";
  4743. expect(app.interaction.current()).toBeUndefined();
  4744. await app.submit("/config");
  4745. expect(app.interaction.current()).toBeUndefined();
  4746. await app.submit("/skills docs");
  4747. const skillsPanel = app.interaction.current();
  4748. const skillsOutput = skillsPanel?.render(80).join("\n") ?? "";
  4749. expect(app.tui.render(80).join("\n")).not.toContain("Message · Enter");
  4750. skillsPanel?.handleInput?.("\x1b");
  4751. await app.submit("/mcp browser");
  4752. const mcpPanel = app.interaction.current();
  4753. const mcpOutput = mcpPanel?.render(80).join("\n") ?? "";
  4754. expect(app.tui.render(80).join("\n")).not.toContain("Message · Enter");
  4755. mcpPanel?.handleInput?.("\x1b");
  4756. await app.submit("/permissions");
  4757. const output = app.transcript
  4758. .snapshot()
  4759. .map((cell) => cell.content)
  4760. .join("\n");
  4761. expect(runtime.getRuntimeDiagnostics).toHaveBeenCalledTimes(1);
  4762. expect(runtime.listSkills).toHaveBeenCalledWith("mavis", "docs");
  4763. expect(runtime.listMcpServers).toHaveBeenCalledWith("browser", "session-1");
  4764. expect(runtime.listPendingPermissions).toHaveBeenCalled();
  4765. expect(doctorOutput).toContain("Configuration check");
  4766. expect(doctorOutput).toContain("Status: Valid");
  4767. expect(doctorOutput).not.toContain("/doctor");
  4768. expect(output).toContain("Configuration check");
  4769. expect(output).not.toContain("Effective configuration");
  4770. expect(skillsOutput).toContain("Skills");
  4771. expect(skillsOutput).toContain("Built-in · 1");
  4772. expect(skillsOutput).toContain("Docs");
  4773. expect(skillsOutput).toContain("● available · builtin");
  4774. expect(mcpOutput).toContain("MCP servers");
  4775. expect(mcpOutput).toContain("browser");
  4776. expect(mcpOutput).toContain("◆ configured · stdio");
  4777. expect(output).toContain("bash · Run tests");
  4778. expect(output).not.toContain("TOKEN");
  4779. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  4780. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4781. expect.objectContaining({ id: "session-1", content: "/config" }),
  4782. expect.any(AbortSignal),
  4783. );
  4784. });
  4785. it("previews /feedback without uploading until Enter confirms the Runtime draft", async () => {
  4786. const terminal = new FakeTerminal();
  4787. terminal.rows = 30;
  4788. const runtime = createRuntime();
  4789. const app = createTuiApp({
  4790. runtime,
  4791. terminal,
  4792. version: "0.1.0",
  4793. workspaceDir: "/workspace",
  4794. });
  4795. app.start();
  4796. await app.ready;
  4797. await app.submit("/feedback Upload failed token=****");
  4798. expect(runtime.prepareFeedback).toHaveBeenCalledWith({
  4799. description: "Upload failed token=****",
  4800. });
  4801. expect(runtime.submitFeedback).not.toHaveBeenCalled();
  4802. expect(app.tui.hasOverlay()).toBe(false);
  4803. expect(app.interaction.isActive()).toBe(true);
  4804. const panel = app.interaction.current();
  4805. expect(panel?.render(80).join("\n")).toContain("Review feedback");
  4806. panel?.handleInput?.("d");
  4807. expect(panel?.render(80).join("\n")).toContain("Client mcode 0.1.0");
  4808. terminal.input?.("\r");
  4809. await vi.waitFor(() =>
  4810. expect(runtime.submitFeedback).toHaveBeenCalledWith(
  4811. "feedback-draft-1",
  4812. expect.objectContaining({ onPhase: expect.any(Function) }),
  4813. ),
  4814. );
  4815. expect(panel?.render(80).join("\n")).toContain("ticket-1");
  4816. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4817. terminal.input?.("\x1b");
  4818. expect(app.interaction.isActive()).toBe(false);
  4819. await app.stop();
  4820. });
  4821. it("cancels /feedback without uploading and keeps missing descriptions out of the Agent", async () => {
  4822. const terminal = new FakeTerminal();
  4823. const runtime = createRuntime();
  4824. const app = createTuiApp({
  4825. runtime,
  4826. terminal,
  4827. version: "0.1.0",
  4828. workspaceDir: "/workspace",
  4829. });
  4830. app.start();
  4831. await app.ready;
  4832. await app.submit("/feedback");
  4833. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  4834. kind: "final-summary",
  4835. content: "Usage: /feedback <message>",
  4836. });
  4837. expect(runtime.prepareFeedback).not.toHaveBeenCalled();
  4838. await app.submit("/feedback Cancel this report");
  4839. terminal.input?.("\x1b");
  4840. await vi.waitFor(() =>
  4841. expect(runtime.cancelFeedback).toHaveBeenCalledWith("feedback-draft-1"),
  4842. );
  4843. expect(runtime.submitFeedback).not.toHaveBeenCalled();
  4844. expect(runtime.sendMessage).not.toHaveBeenCalled();
  4845. await app.stop();
  4846. });
  4847. it("keeps the status report local and submits the hidden /config name as text", async () => {
  4848. const terminal = new FakeTerminal();
  4849. terminal.rows = 24;
  4850. const runtime = createRuntime();
  4851. const app = createTuiApp({
  4852. runtime,
  4853. terminal,
  4854. version: "0.1.0",
  4855. workspaceDir: "/workspace",
  4856. });
  4857. app.start();
  4858. await app.ready;
  4859. const transcriptBeforeStatus = app.transcript.snapshot();
  4860. await app.submit("/status");
  4861. expect(app.tui.hasOverlay()).toBe(false);
  4862. expect(app.interaction.isActive()).toBe(true);
  4863. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  4864. const statusOutput = app.tui.render(80).join("\n");
  4865. expect(statusOutput).toContain("MCode status");
  4866. expect(statusOutput).toContain("Model");
  4867. expect(statusOutput).not.toContain("/status");
  4868. expect(statusOutput).toContain("/workspace");
  4869. expect(statusOutput).toMatch(/Branch:\s+Not a Git repository/u);
  4870. expect(statusOutput).toContain("Not applicable");
  4871. expect(statusOutput).toContain("Session");
  4872. expect(statusOutput).toContain("Permissions");
  4873. expect(statusOutput).toContain("Auto");
  4874. app.interaction.current()?.handleInput?.("\x1b");
  4875. expect(app.interaction.isActive()).toBe(false);
  4876. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  4877. await app.submit("/config");
  4878. expect(app.tui.hasOverlay()).toBe(false);
  4879. expect(app.interaction.isActive()).toBe(false);
  4880. expect(runtime.sendMessage).toHaveBeenCalledWith(
  4881. expect.objectContaining({ id: "session-1", content: "/config" }),
  4882. expect.any(AbortSignal),
  4883. );
  4884. expect(runtime.getRuntimeDiagnostics).not.toHaveBeenCalled();
  4885. await app.stop();
  4886. });
  4887. it("commits the first frame immediately when the Pi renderer starts", async () => {
  4888. const terminal = new FakeTerminal();
  4889. const app = createTuiApp({
  4890. runtime: createRuntime(),
  4891. terminal,
  4892. version: "0.1.0",
  4893. workspaceDir: "/workspace",
  4894. });
  4895. let firstFrameCommitted = false;
  4896. void app.firstFrame.then(() => {
  4897. firstFrameCommitted = true;
  4898. });
  4899. app.start();
  4900. await app.firstFrame;
  4901. expect(terminal.started).toBe(true);
  4902. expect(firstFrameCommitted).toBe(true);
  4903. expect(terminal.writes.join("")).toContain("Tips for getting started");
  4904. await app.stop();
  4905. });
  4906. it("chooses the account region before routing login through the auth application", async () => {
  4907. const runtime = createRuntime();
  4908. const openedTargets: string[] = [];
  4909. const logoutUrl =
  4910. "https://agent.minimax.io/auth/logout?logout_redirect_uri=https%3A%2F%2Fagent.minimax.io";
  4911. let authenticated = false;
  4912. vi.mocked(runtime.getAccountStatus).mockImplementation(async () =>
  4913. authenticated
  4914. ? {
  4915. status: "ready",
  4916. defaultModel: "minimax/MiniMax-M2.7",
  4917. providerId: "minimax",
  4918. modelId: "MiniMax-M2.7",
  4919. authMode: "managed-login",
  4920. managedTokenPresent: true,
  4921. warnings: [],
  4922. }
  4923. : {
  4924. status: "needs-login",
  4925. authMode: "managed-login",
  4926. managedTokenPresent: false,
  4927. warnings: [],
  4928. },
  4929. );
  4930. const auth = {
  4931. login: vi.fn(
  4932. async (
  4933. onProgress?: (progress: McodeAuthProgress) => void,
  4934. _region?: "cn" | "en",
  4935. ) => {
  4936. authenticated = true;
  4937. onProgress?.({
  4938. state: "device-authorization",
  4939. userCode: "ABCD-EFGH",
  4940. verificationUri: "https://account.example.test/device",
  4941. expiresInSec: 300,
  4942. });
  4943. return {
  4944. state: "authenticated" as const,
  4945. message:
  4946. _region === "en"
  4947. ? "Signed in with MiniMax Global. Restart MCode to use this account region."
  4948. : "Signed in with MiniMax.",
  4949. };
  4950. },
  4951. ),
  4952. logout: vi.fn(async () => {
  4953. authenticated = false;
  4954. return {
  4955. state: "signed-out" as const,
  4956. message: "Signed out of MiniMax.",
  4957. logoutUrl,
  4958. };
  4959. }),
  4960. };
  4961. const notifyAuthContextChanged = vi.fn(async () => {
  4962. throw new Error("Hook lifecycle cleanup failed");
  4963. });
  4964. const app = createTuiApp({
  4965. runtime,
  4966. auth,
  4967. terminal: new FakeTerminal(),
  4968. version: "0.1.0",
  4969. workspaceDir: "/workspace",
  4970. openExternalTarget: async (target) => {
  4971. openedTargets.push(target);
  4972. throw new Error("no desktop session");
  4973. },
  4974. notifyAuthContextChanged,
  4975. });
  4976. app.start();
  4977. await app.ready;
  4978. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login");
  4979. await app.submit("/login");
  4980. expect(auth.login).not.toHaveBeenCalled();
  4981. expect(app.interaction.render(80).join("\n")).toContain("China (CN)");
  4982. expect(app.interaction.render(80).join("\n")).toContain("Global");
  4983. app.interaction.current()?.handleInput("\u001b[B");
  4984. app.interaction.current()?.handleInput("\r");
  4985. await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
  4986. await vi.waitFor(() =>
  4987. expect(app.controller.snapshot().account?.managedTokenPresent).toBe(true),
  4988. );
  4989. expect(app.getSurface()).toBe("conversation");
  4990. expect(app.tui.render(80).join("\n")).not.toContain("Sign in with /login");
  4991. expect(app.tui.render(80).join("\n")).not.toContain("Login required");
  4992. await app.submit("/logout");
  4993. await vi.waitFor(() =>
  4994. expect(app.controller.snapshot().account?.managedTokenPresent).toBe(
  4995. false,
  4996. ),
  4997. );
  4998. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login");
  4999. expect(auth.login).toHaveBeenCalledWith(expect.any(Function), "en");
  5000. expect(openedTargets).toEqual([
  5001. "https://account.example.test/device?client_surface=tui&download_source=mcode-internal",
  5002. logoutUrl,
  5003. ]);
  5004. await vi.waitFor(() =>
  5005. expect(app.transcript.snapshot()).toEqual(
  5006. expect.arrayContaining([
  5007. expect.objectContaining({
  5008. kind: "warning",
  5009. content:
  5010. "Couldn't open the default browser. Open the authorization URL above manually.",
  5011. }),
  5012. expect.objectContaining({
  5013. kind: "warning",
  5014. content:
  5015. "Couldn't open the default browser. Open the sign-out URL above manually.",
  5016. }),
  5017. ]),
  5018. ),
  5019. );
  5020. expect(app.transcript.snapshot().slice(-6)).toMatchObject([
  5021. {
  5022. kind: "final-summary",
  5023. content:
  5024. "Complete MiniMax login in your browser:\nhttps://account.example.test/device?client_surface=tui&download_source=mcode-internal\nCode: ABCD-EFGH",
  5025. },
  5026. {
  5027. kind: "warning",
  5028. content:
  5029. "Couldn't open the default browser. Open the authorization URL above manually.",
  5030. },
  5031. {
  5032. kind: "final-summary",
  5033. content:
  5034. "Signed in with MiniMax Global. Restart MCode to use this account region.",
  5035. },
  5036. {
  5037. kind: "final-summary",
  5038. content: "Signed out of MiniMax.",
  5039. },
  5040. {
  5041. kind: "final-summary",
  5042. content: `Finish signing out in your browser:\n${logoutUrl}`,
  5043. },
  5044. {
  5045. kind: "warning",
  5046. content:
  5047. "Couldn't open the default browser. Open the sign-out URL above manually.",
  5048. },
  5049. ]);
  5050. expect(auth.login).toHaveBeenCalledOnce();
  5051. expect(auth.logout).toHaveBeenCalledOnce();
  5052. expect(notifyAuthContextChanged.mock.calls).toEqual([
  5053. ["authenticated"],
  5054. ["logged_out"],
  5055. ]);
  5056. expect(
  5057. app.transcript
  5058. .snapshot()
  5059. .map((cell) => cell.content)
  5060. .join("\n"),
  5061. ).not.toContain("Sign-in wasn't completed");
  5062. expect(
  5063. app.transcript
  5064. .snapshot()
  5065. .map((cell) => cell.content)
  5066. .join("\n"),
  5067. ).not.toContain("Couldn't sign out");
  5068. expect(runtime.sendMessage).not.toHaveBeenCalled();
  5069. await app.stop();
  5070. });
  5071. it("clears Runtime auth context when the shared account is already signed out", async () => {
  5072. const notifyAuthContextChanged = vi.fn(async () => undefined);
  5073. const logoutUrl =
  5074. "https://agent.minimax.cn/auth/logout?logout_redirect_uri=https%3A%2F%2Fagent.minimax.cn";
  5075. const openExternalTarget = vi.fn(() => new Promise<void>(() => {}));
  5076. const app = createTuiApp({
  5077. runtime: createRuntime(),
  5078. auth: {
  5079. login: vi.fn(),
  5080. logout: vi.fn(async () => ({
  5081. state: "already-signed-out" as const,
  5082. message: "Already signed out of MiniMax.",
  5083. logoutUrl,
  5084. })),
  5085. },
  5086. terminal: new FakeTerminal(),
  5087. version: "0.1.0",
  5088. workspaceDir: "/workspace",
  5089. notifyAuthContextChanged,
  5090. openExternalTarget,
  5091. });
  5092. app.start();
  5093. await app.ready;
  5094. await app.submit("/logout");
  5095. expect(notifyAuthContextChanged).toHaveBeenCalledOnce();
  5096. expect(notifyAuthContextChanged).toHaveBeenCalledWith("logged_out");
  5097. expect(openExternalTarget).toHaveBeenCalledWith(logoutUrl);
  5098. expect(app.transcript.snapshot()).toEqual(
  5099. expect.arrayContaining([
  5100. expect.objectContaining({
  5101. content: `Finish signing out in your browser:\n${logoutUrl}`,
  5102. }),
  5103. ]),
  5104. );
  5105. await app.stop();
  5106. });
  5107. it("refreshes Runtime auth context when login renews an existing account", async () => {
  5108. const runtime = createRuntime();
  5109. let authenticated = false;
  5110. vi.mocked(runtime.getAccountStatus).mockImplementation(async () =>
  5111. authenticated
  5112. ? {
  5113. status: "ready",
  5114. defaultModel: "minimax/MiniMax-M2.7",
  5115. providerId: "minimax",
  5116. modelId: "MiniMax-M2.7",
  5117. authMode: "managed-login",
  5118. managedTokenPresent: true,
  5119. warnings: [],
  5120. }
  5121. : {
  5122. status: "needs-login",
  5123. authMode: "managed-login",
  5124. managedTokenPresent: false,
  5125. warnings: [],
  5126. },
  5127. );
  5128. const notifyAuthContextChanged = vi.fn(async () => undefined);
  5129. const auth = {
  5130. login: vi.fn(async () => {
  5131. authenticated = true;
  5132. return {
  5133. state: "already-authenticated" as const,
  5134. message: "Already signed in with MiniMax.",
  5135. };
  5136. }),
  5137. logout: vi.fn(async () => ({
  5138. state: "signed-out" as const,
  5139. message: "Signed out of MiniMax.",
  5140. })),
  5141. };
  5142. const app = createTuiApp({
  5143. runtime,
  5144. auth,
  5145. notifyAuthContextChanged,
  5146. terminal: new FakeTerminal(),
  5147. version: "0.1.0",
  5148. workspaceDir: "/workspace",
  5149. });
  5150. app.start();
  5151. await app.ready;
  5152. expect(app.tui.render(80).join("\n")).toContain("Sign in with /login");
  5153. await app.submit("/login");
  5154. app.interaction.current()?.handleInput("\u001b[B");
  5155. app.interaction.current()?.handleInput("\r");
  5156. await vi.waitFor(() => expect(auth.login).toHaveBeenCalledOnce());
  5157. expect(notifyAuthContextChanged).toHaveBeenCalledOnce();
  5158. expect(notifyAuthContextChanged).toHaveBeenCalledWith("authenticated");
  5159. await vi.waitFor(() =>
  5160. expect(app.controller.snapshot().account?.managedTokenPresent).toBe(true),
  5161. );
  5162. expect(app.getSurface()).toBe("conversation");
  5163. expect(app.tui.render(80).join("\n")).not.toContain("Sign in with /login");
  5164. expect(app.tui.render(80).join("\n")).not.toContain("Login required");
  5165. await app.stop();
  5166. });
  5167. it("exits immediately through /quit without aborting the shared Runtime turn", async () => {
  5168. const terminal = new FakeTerminal();
  5169. const runtime = createRuntime();
  5170. const abortSession = vi.spyOn(runtime, "abortSession");
  5171. const app = createTuiApp({
  5172. runtime,
  5173. terminal,
  5174. version: "0.1.0",
  5175. workspaceDir: "/workspace",
  5176. });
  5177. app.start();
  5178. await app.ready;
  5179. await app.submit("/quit");
  5180. await app.stopped;
  5181. expect(terminal.stopped).toBe(true);
  5182. expect(abortSession).not.toHaveBeenCalled();
  5183. });
  5184. it("does not restore /quit after reopening the exited Session", async () => {
  5185. const dataDir = await mkdtemp(join(tmpdir(), "mcode-quit-draft-"));
  5186. try {
  5187. const first = createTuiApp({
  5188. runtime: createRuntime(),
  5189. terminal: new FakeTerminal(),
  5190. version: "0.1.0",
  5191. dataDir,
  5192. workspaceDir: "/workspace",
  5193. });
  5194. await first.ready;
  5195. await first.openSession("session-1");
  5196. first.editor.setText("/quit");
  5197. first.editor.handleInput("\r");
  5198. await first.stopped;
  5199. const restored = createTuiApp({
  5200. runtime: createRuntime(),
  5201. terminal: new FakeTerminal(),
  5202. version: "0.1.0",
  5203. dataDir,
  5204. workspaceDir: "/workspace",
  5205. });
  5206. await restored.ready;
  5207. await restored.openSession("session-1");
  5208. expect(restored.editor.getText()).toBe("");
  5209. await restored.stop();
  5210. } finally {
  5211. await rm(dataDir, { recursive: true, force: true });
  5212. }
  5213. });
  5214. it("keeps warning status details visible until the local panel closes", async () => {
  5215. const terminal = new FakeTerminal();
  5216. terminal.rows = 40;
  5217. const runtime = createRuntime();
  5218. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  5219. status: "warning",
  5220. defaultModel: "minimax/MiniMax-M2.7",
  5221. providerId: "minimax",
  5222. modelId: "MiniMax-M2.7",
  5223. authMode: "managed-login",
  5224. managedTokenPresent: true,
  5225. warnings: ["Desktop login should be refreshed soon."],
  5226. });
  5227. const app = createTuiApp({
  5228. runtime,
  5229. terminal,
  5230. version: "0.1.0",
  5231. workspaceDir: "/workspace",
  5232. });
  5233. app.start();
  5234. await app.ready;
  5235. const transcriptBeforeStatus = app.transcript.snapshot();
  5236. await app.submit("/status");
  5237. const rendered = app.tui.render(80).join("\n");
  5238. expect(app.interaction.current()).toBeDefined();
  5239. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  5240. expect(rendered).toContain("Needs attention");
  5241. expect(rendered).toContain("Connected with warnings");
  5242. expect(rendered).toContain("Model");
  5243. expect(rendered).toContain("Desktop login should be refreshed");
  5244. expect(rendered).toContain("soon.");
  5245. app.interaction.current()?.handleInput?.("\x1b");
  5246. expect(app.interaction.current()).toBeUndefined();
  5247. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  5248. expect(app.tui.render(80).join("\n")).not.toContain(
  5249. "Desktop login should be refreshed",
  5250. );
  5251. await app.stop();
  5252. });
  5253. it("reports doctor failures and submits the hidden /config name as text", async () => {
  5254. const runtime = createRuntime();
  5255. vi.mocked(runtime.getRuntimeDiagnostics).mockRejectedValue(
  5256. new Error("Diagnostics unavailable"),
  5257. );
  5258. const app = createTuiApp({
  5259. runtime,
  5260. terminal: new FakeTerminal(),
  5261. version: "0.1.0",
  5262. workspaceDir: "/workspace",
  5263. });
  5264. await app.submit("/doctor");
  5265. expect(app.tui.hasOverlay()).toBe(false);
  5266. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  5267. kind: "error",
  5268. content:
  5269. "Couldn't load configuration check: Diagnostics unavailable. Retry.",
  5270. });
  5271. await app.submit("/config");
  5272. expect(app.tui.hasOverlay()).toBe(false);
  5273. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5274. expect.objectContaining({ id: "session-1", content: "/config" }),
  5275. expect.any(AbortSignal),
  5276. );
  5277. expect(runtime.getRuntimeDiagnostics).toHaveBeenCalledTimes(1);
  5278. });
  5279. it("lets an async Session card replace a local status panel", async () => {
  5280. const terminal = new FakeTerminal();
  5281. const runtime = createRuntime();
  5282. let resolveSessionPage:
  5283. | ((page: {
  5284. sessions: Array<{
  5285. sessionId: string;
  5286. title: string;
  5287. workspaceDir: string;
  5288. updatedAt: number;
  5289. }>;
  5290. hasMore: boolean;
  5291. }) => void)
  5292. | undefined;
  5293. vi.mocked(runtime.listSessionPage).mockImplementationOnce(
  5294. async () =>
  5295. await new Promise((resolve) => {
  5296. resolveSessionPage = resolve;
  5297. }),
  5298. );
  5299. const app = createTuiApp({
  5300. runtime,
  5301. terminal,
  5302. version: "0.1.0",
  5303. workspaceDir: "/workspace",
  5304. });
  5305. await app.ready;
  5306. const transcriptBeforeStatus = app.transcript.snapshot();
  5307. const sessionCard = app.submit("/sessions");
  5308. await vi.waitFor(() =>
  5309. expect(runtime.listSessionPage).toHaveBeenCalledOnce(),
  5310. );
  5311. await app.submit("/status");
  5312. expect(app.tui.hasOverlay()).toBe(false);
  5313. expect(app.interaction.isActive()).toBe(true);
  5314. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  5315. expect(app.tui.render(80).join("\n")).toContain("MCode status");
  5316. resolveSessionPage?.({
  5317. sessions: [
  5318. {
  5319. sessionId: "session-race",
  5320. title: "Session opened after status",
  5321. workspaceDir: "/workspace",
  5322. updatedAt: Date.now(),
  5323. },
  5324. ],
  5325. hasMore: false,
  5326. });
  5327. await sessionCard;
  5328. expect(app.tui.hasOverlay()).toBe(false);
  5329. expect(app.interaction.isActive()).toBe(true);
  5330. app.interaction.current()?.handleInput?.("\x03");
  5331. expect(runtime.getSession).not.toHaveBeenCalled();
  5332. expect(app.interaction.isActive()).toBe(false);
  5333. expect(app.tui.hasOverlay()).toBe(false);
  5334. await app.stop();
  5335. });
  5336. it("keeps unsupported standalone MCP inspection concise and recoverable", async () => {
  5337. const runtime = createRuntime();
  5338. vi.mocked(runtime.listMcpServers).mockRejectedValue(
  5339. Object.assign(new Error("DesktopService implementation detail"), {
  5340. status: 501,
  5341. code: "NOT_IMPLEMENTED",
  5342. }),
  5343. );
  5344. const app = createTuiApp({
  5345. runtime,
  5346. terminal: new FakeTerminal(),
  5347. version: "0.1.0",
  5348. workspaceDir: "/workspace",
  5349. });
  5350. await app.submit("/mcp");
  5351. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  5352. kind: "warning",
  5353. content:
  5354. "MCP status is not available in this build. Configured MCP tools remain available.",
  5355. });
  5356. });
  5357. it("registers enabled Skills as discoverable slash commands without shadowing built-ins", async () => {
  5358. const terminal = new FakeTerminal();
  5359. const runtime = createRuntime();
  5360. vi.mocked(runtime.listSkills).mockResolvedValue({
  5361. skills: [
  5362. {
  5363. name: "docs",
  5364. displayName: "Docs",
  5365. description: "Read project docs",
  5366. enabled: true,
  5367. sourceKind: "builtin",
  5368. },
  5369. {
  5370. name: "disabled-skill",
  5371. enabled: false,
  5372. },
  5373. {
  5374. name: "help",
  5375. enabled: true,
  5376. },
  5377. ...Array.from({ length: 14 }, (_, index) => ({
  5378. name: `skill-${index}`,
  5379. description: `Generated skill ${index}`,
  5380. enabled: true,
  5381. })),
  5382. ],
  5383. hasMore: false,
  5384. });
  5385. const app = createTuiApp({
  5386. runtime,
  5387. terminal,
  5388. version: "0.1.0",
  5389. workspaceDir: "/workspace",
  5390. });
  5391. app.start();
  5392. await app.ready;
  5393. app.editor.setText("/docs summarize this repository");
  5394. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5395. "Skill · instructions · Enter invoke",
  5396. );
  5397. app.editor.setText("/context");
  5398. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5399. "Command · Enter run",
  5400. );
  5401. app.editor.setText("/context explain this repository");
  5402. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5403. "Prompt · Enter send",
  5404. );
  5405. app.editor.setText("/stop");
  5406. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5407. "Command · Enter run",
  5408. );
  5409. app.editor.setText("/config");
  5410. expect(stripAnsi(app.tui.render(80).join("\n"))).toContain(
  5411. "Prompt · Enter send",
  5412. );
  5413. app.editor.setText("");
  5414. await app.submit("/help");
  5415. expect(app.transcript.snapshot()).toEqual([]);
  5416. expect(app.tui.hasOverlay()).toBe(false);
  5417. expect(app.interaction.isActive()).toBe(true);
  5418. for (const character of "docs") terminal.input?.(character);
  5419. terminal.input?.("\r");
  5420. expect(app.tui.hasOverlay()).toBe(false);
  5421. expect(app.interaction.isActive()).toBe(false);
  5422. expect(app.editor.getText()).toBe("");
  5423. await app.submit("/docs summarize this repository");
  5424. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5425. expect.objectContaining({
  5426. id: "session-1",
  5427. content: "/docs summarize this repository",
  5428. }),
  5429. expect.any(AbortSignal),
  5430. );
  5431. vi.mocked(runtime.sendMessage).mockClear();
  5432. await app.submit("/disabled-skill");
  5433. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5434. expect.objectContaining({ id: "session-1", content: "/disabled-skill" }),
  5435. expect.any(AbortSignal),
  5436. );
  5437. await app.stop();
  5438. });
  5439. it("deduplicates configured Skills case-insensitively and reserves built-in names", async () => {
  5440. const terminal = new FakeTerminal();
  5441. const runtime = createRuntime();
  5442. vi.mocked(runtime.listSkills).mockResolvedValue({
  5443. skills: [
  5444. {
  5445. name: "HELP",
  5446. description: "A Skill that must not shadow /help",
  5447. enabled: true,
  5448. },
  5449. {
  5450. name: "Docs",
  5451. description: "Read project docs",
  5452. enabled: true,
  5453. },
  5454. {
  5455. name: "docs",
  5456. description: "Duplicate project docs command",
  5457. enabled: true,
  5458. },
  5459. ],
  5460. hasMore: false,
  5461. });
  5462. const app = createTuiApp({
  5463. runtime,
  5464. terminal,
  5465. version: "0.1.0",
  5466. workspaceDir: "/workspace",
  5467. });
  5468. app.start();
  5469. await app.ready;
  5470. await app.submit("/help");
  5471. const helpPanel = app.interaction.current();
  5472. expect(helpPanel).toBeDefined();
  5473. helpPanel?.handleInput?.("\x1b");
  5474. await app.submit("/help [arguments]");
  5475. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5476. expect.objectContaining({
  5477. id: "session-1",
  5478. content: "/help [arguments]",
  5479. }),
  5480. expect.any(AbortSignal),
  5481. );
  5482. vi.mocked(runtime.sendMessage).mockClear();
  5483. await app.submit("/docs explain this repository");
  5484. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5485. expect.objectContaining({
  5486. id: "session-1",
  5487. content: "/docs explain this repository",
  5488. }),
  5489. expect.any(AbortSignal),
  5490. );
  5491. await app.stop();
  5492. });
  5493. it("uses public Runtime owners for Session inspection commands", async () => {
  5494. const terminal = new FakeTerminal();
  5495. terminal.rows = 40;
  5496. const runtime = createRuntime();
  5497. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  5498. status: "ready",
  5499. defaultModel: "minimax/MiniMax-M3",
  5500. providerId: "minimax-cn-coding-plan",
  5501. authMode: "managed-login",
  5502. managedTokenPresent: true,
  5503. modelSource: "token-plan",
  5504. tokenPlanQuotaState: "available",
  5505. tokenPlanSummary: { tier: "Ultra Plan", creditBalance: "0" },
  5506. tokenPlanQuota: {
  5507. fiveHour: { remainingPercent: 100, unlimited: false },
  5508. weekly: { remainingPercent: 99, unlimited: false },
  5509. video: { remainingCount: 5, totalCount: 5, unlimited: false },
  5510. },
  5511. warnings: [],
  5512. });
  5513. const app = createTuiApp({
  5514. runtime,
  5515. terminal,
  5516. version: "0.1.0",
  5517. workspaceDir: "/workspace",
  5518. });
  5519. await app.submit("Create a session");
  5520. vi.mocked(runtime.sendMessage).mockClear();
  5521. vi.mocked(runtime.getSessionUsage).mockClear();
  5522. vi.mocked(runtime.getContextSnapshot).mockResolvedValueOnce({
  5523. status: "live",
  5524. contextUsage: {
  5525. contextWindowTokens: 10_000,
  5526. usedTokens: 3_000,
  5527. totalCountSource: "PROVIDER_USAGE_ANCHORED",
  5528. components: [],
  5529. },
  5530. });
  5531. const transcriptBeforeUsage = app.transcript.snapshot();
  5532. await app.submit("/usage");
  5533. const usageOutput = app.tui.render(80).join("\n");
  5534. expect(app.interaction.current()).toBeDefined();
  5535. expect(app.transcript.snapshot()).toEqual(transcriptBeforeUsage);
  5536. expect(usageOutput).toContain("Usage");
  5537. expect(usageOutput).toContain("120 total");
  5538. expect(usageOutput).toContain("30% used · 70% free");
  5539. expect(usageOutput).toContain("Ultra Plan");
  5540. expect(usageOutput).toContain("100% left");
  5541. app.interaction.current()?.handleInput?.("\x1b");
  5542. expect(app.interaction.current()).toBeUndefined();
  5543. expect(app.transcript.snapshot()).toEqual(transcriptBeforeUsage);
  5544. await app.submit("/compact keep test evidence");
  5545. expect(runtime.getSessionUsage).toHaveBeenCalledWith("session-1");
  5546. expect(runtime.getContextSnapshot).toHaveBeenCalledWith("session-1");
  5547. expect(runtime.getAccountStatus).toHaveBeenCalledWith("session-1", {
  5548. includeMembership: true,
  5549. forceRefresh: true,
  5550. });
  5551. expect(runtime.requestCompaction).toHaveBeenCalledWith(
  5552. "session-1",
  5553. "mavis",
  5554. "keep test evidence",
  5555. );
  5556. expect(runtime.sendMessage).not.toHaveBeenCalled();
  5557. const output = app.transcript
  5558. .snapshot()
  5559. .map((cell) => cell.content)
  5560. .join("\n");
  5561. expect(output).not.toContain("Session usage");
  5562. expect(output).not.toMatch(
  5563. /Turns|Total tokens|Cost|Reasoning|Cache|Runtime|source|compaction|snapshot/i,
  5564. );
  5565. expect(output).not.toContain("Compaction completed");
  5566. expect(output).not.toContain("4,000 → 1,200 tokens");
  5567. expect(output).not.toContain("compact-1");
  5568. });
  5569. it("shows compaction as live activity until the Runtime request settles", async () => {
  5570. const runtime = createRuntime();
  5571. let resolveCompaction:
  5572. | ((result: {
  5573. success: true;
  5574. sessionId: string;
  5575. compactionId: string;
  5576. }) => void)
  5577. | undefined;
  5578. vi.mocked(runtime.requestCompaction).mockImplementationOnce(
  5579. async () =>
  5580. await new Promise((resolve) => {
  5581. resolveCompaction = resolve;
  5582. }),
  5583. );
  5584. const app = createTuiApp({
  5585. runtime,
  5586. terminal: new FakeTerminal(),
  5587. version: "0.1.0",
  5588. workspaceDir: "/workspace",
  5589. });
  5590. await app.submit("Create a session");
  5591. const pending = app.submit("/compact keep decisions");
  5592. await vi.waitFor(() =>
  5593. expect(app.tui.render(80).join("\n")).toContain("Compacting context"),
  5594. );
  5595. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
  5596. resolveCompaction?.({
  5597. success: true,
  5598. sessionId: "session-1",
  5599. compactionId: "compact-1",
  5600. });
  5601. await pending;
  5602. expect(app.tui.render(80).join("\n")).not.toContain("Compacting context");
  5603. });
  5604. it("treats Runtime NOTHING_TO_COMPACT as a recoverable Session state", async () => {
  5605. const runtime = createRuntime();
  5606. vi.mocked(runtime.requestCompaction).mockRejectedValue(
  5607. Object.assign(new Error("HTTP 400 implementation detail"), {
  5608. status: 400,
  5609. code: "NOTHING_TO_COMPACT",
  5610. }),
  5611. );
  5612. const app = createTuiApp({
  5613. runtime,
  5614. terminal: new FakeTerminal(),
  5615. version: "0.1.0",
  5616. workspaceDir: "/workspace",
  5617. });
  5618. await app.submit("Create a session");
  5619. await app.submit("/compact");
  5620. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  5621. kind: "final-summary",
  5622. content: "No compaction is needed for this conversation yet.",
  5623. });
  5624. });
  5625. it("shows account usage before a Session exists and keeps Session-only inspection recoverable", async () => {
  5626. const runtime = createRuntime();
  5627. vi.mocked(runtime.getAccountStatus).mockResolvedValue({
  5628. status: "ready",
  5629. authMode: "byok",
  5630. managedTokenPresent: false,
  5631. modelSource: "byok",
  5632. tokenPlanQuotaState: "available",
  5633. tokenPlanSummary: { tier: "Pro Plan" },
  5634. tokenPlanQuota: {
  5635. fiveHour: { remainingPercent: 75, unlimited: false },
  5636. weekly: { remainingPercent: 50, unlimited: false },
  5637. },
  5638. warnings: [],
  5639. });
  5640. const terminal = new FakeTerminal();
  5641. terminal.rows = 40;
  5642. const app = createTuiApp({
  5643. runtime,
  5644. terminal,
  5645. version: "0.1.0",
  5646. workspaceDir: "/workspace",
  5647. });
  5648. await app.submit("/usage");
  5649. const usageOutput = app.tui.render(80).join("\n");
  5650. expect(app.interaction.current()).toBeDefined();
  5651. expect(app.transcript.snapshot()).toEqual([]);
  5652. expect(usageOutput).toContain("Usage");
  5653. expect(usageOutput).toContain("Account only");
  5654. expect(usageOutput).toContain("Pro Plan");
  5655. expect(usageOutput).toContain("75% left");
  5656. app.interaction.current()?.handleInput?.("\x1b");
  5657. expect(app.interaction.current()).toBeUndefined();
  5658. expect(app.transcript.snapshot()).toEqual([]);
  5659. await app.submit("/compact");
  5660. expect(runtime.getSessionUsage).not.toHaveBeenCalled();
  5661. expect(runtime.getContextSnapshot).not.toHaveBeenCalled();
  5662. expect(runtime.getAccountStatus).toHaveBeenCalledWith(undefined, {
  5663. includeMembership: true,
  5664. forceRefresh: true,
  5665. });
  5666. expect(app.transcript.snapshot()).toEqual([]);
  5667. expect(app.tui.render(80).join("\n")).toContain(
  5668. "Start or resume a Session before compacting it.",
  5669. );
  5670. });
  5671. it("keeps prompt history and long bracketed paste intact in the Composer", async () => {
  5672. const terminal = new FakeTerminal();
  5673. const runtime = createRuntime();
  5674. const app = createTuiApp({
  5675. runtime,
  5676. terminal,
  5677. version: "0.1.0",
  5678. workspaceDir: "/workspace",
  5679. });
  5680. app.start();
  5681. await app.ready;
  5682. terminal.input?.("first prompt");
  5683. terminal.input?.("\r");
  5684. await vi.waitFor(() =>
  5685. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  5686. );
  5687. terminal.input?.("second prompt");
  5688. terminal.input?.("\r");
  5689. await vi.waitFor(() =>
  5690. expect(runtime.sendMessage).toHaveBeenCalledTimes(2),
  5691. );
  5692. terminal.input?.("\x1b[A");
  5693. expect(app.editor.getText()).toBe("second prompt");
  5694. terminal.input?.("\x1b[A");
  5695. expect(app.editor.getText()).toBe("first prompt");
  5696. terminal.input?.("\x1b[B");
  5697. expect(app.editor.getText()).toBe("second prompt");
  5698. app.editor.setText("");
  5699. const pasted = `Explain this payload:\n${"x".repeat(1_200)}`;
  5700. terminal.input?.(`\x1b[200~${pasted}\x1b[201~`);
  5701. expect(app.editor.getText()).toContain("[paste #");
  5702. expect(app.editor.getExpandedText()).toBe(pasted);
  5703. terminal.input?.("\r");
  5704. await vi.waitFor(() =>
  5705. expect(runtime.sendMessage).toHaveBeenCalledTimes(3),
  5706. );
  5707. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  5708. expect.objectContaining({ id: "session-1", content: pasted }),
  5709. expect.any(AbortSignal),
  5710. );
  5711. await app.stop();
  5712. });
  5713. it("trusts bracketed paste and submits dense typed input without a false newline", async () => {
  5714. const terminal = new FakeTerminal();
  5715. Object.defineProperty(terminal, "capabilities", {
  5716. value: {
  5717. terminalId: "unknown",
  5718. platform: "linux",
  5719. isTTY: true,
  5720. transport: "local",
  5721. multiplexer: "none",
  5722. color: true,
  5723. colorLevel: 3,
  5724. } satisfies TerminalCapabilities,
  5725. });
  5726. const runtime = createRuntime();
  5727. const app = createTuiApp({
  5728. runtime,
  5729. terminal,
  5730. version: "0.1.0",
  5731. workspaceDir: "/workspace",
  5732. });
  5733. app.start();
  5734. await app.ready;
  5735. for (const character of "abcdefgh") terminal.input?.(character);
  5736. terminal.input?.("\r");
  5737. await vi.waitFor(() =>
  5738. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  5739. );
  5740. expect(app.editor.getText()).toBe("");
  5741. await app.stop();
  5742. });
  5743. it("projects an otty image paste as an inline editor placeholder", async () => {
  5744. const terminal = new FakeTerminal();
  5745. const resolveAttachment = vi.fn(async () => ({
  5746. type: "image" as const,
  5747. filePath: "/tmp/otty-paste/image-123.png",
  5748. fileName: "image-123.png",
  5749. mimeType: "image/png",
  5750. sizeBytes: 1_024,
  5751. }));
  5752. const app = createTuiApp({
  5753. runtime: createRuntime(),
  5754. terminal,
  5755. version: "0.1.0",
  5756. workspaceDir: "/workspace",
  5757. resolveAttachment,
  5758. });
  5759. app.start();
  5760. await app.ready;
  5761. terminal.input?.("\x1b[200~/tmp/otty-paste/image-123.png\x1b[201~");
  5762. await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledTimes(1));
  5763. const rendered = app.tui.render(80).join("\n");
  5764. expect(app.editor.getText()).toBe("[Image #1] ");
  5765. expect(rendered).toContain("[Image #1]");
  5766. expect(rendered).not.toContain("/tmp/otty-paste/");
  5767. await app.stop();
  5768. });
  5769. it.each(["regular", "fullscreen"] as const)(
  5770. "keeps image preview controls separate from Enter submission in %s mode",
  5771. async (tuiMode) => {
  5772. const terminal = new FakeTerminal();
  5773. terminal.rows = 40;
  5774. const runtime = createRuntime();
  5775. const app = createTuiApp({
  5776. runtime,
  5777. terminal,
  5778. tuiMode,
  5779. version: "0.1.0",
  5780. workspaceDir: "/workspace",
  5781. resolveAttachment: async () => ({
  5782. type: "image",
  5783. filePath: "/tmp/image-preview-missing.png",
  5784. fileName: "preview.png",
  5785. mimeType: "image/png",
  5786. sizeBytes: 32768,
  5787. }),
  5788. });
  5789. app.start();
  5790. await app.ready;
  5791. terminal.input?.("\x1b[200~/tmp/image-preview-missing.png\x1b[201~");
  5792. await vi.waitFor(() =>
  5793. expect(app.editor.getAttachmentPreview()?.id).toBe(
  5794. "/tmp/image-preview-missing.png",
  5795. ),
  5796. );
  5797. expect(app.editor.getText()).toBe("[Image #1] ");
  5798. expect(app.tui.render(80).join("\n")).toContain("preview.png");
  5799. expect(app.tui.render(80).join("\n")).toContain("32 KB");
  5800. expect(app.tui.render(80).join("\n")).not.toMatch(/Option\+I|Alt\+I/);
  5801. expect(runtime.sendMessage).not.toHaveBeenCalled();
  5802. terminal.input?.("\x1b");
  5803. expect(app.editor.getAttachmentPreview()).toBeUndefined();
  5804. terminal.input?.("\x1b[D");
  5805. expect(app.editor.getAttachmentPreview()?.id).toBe(
  5806. "/tmp/image-preview-missing.png",
  5807. );
  5808. terminal.input?.("\r");
  5809. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalled());
  5810. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5811. expect.objectContaining({
  5812. content: "",
  5813. attachments: [
  5814. expect.objectContaining({
  5815. local: { filePath: "/tmp/image-preview-missing.png" },
  5816. }),
  5817. ],
  5818. }),
  5819. expect.any(AbortSignal),
  5820. );
  5821. expect(app.editor.getAttachmentPreview()).toBeUndefined();
  5822. await app.stop();
  5823. },
  5824. );
  5825. it("projects a pasted absolute WeChat image path as a short inline placeholder", async () => {
  5826. const terminal = new FakeTerminal();
  5827. const runtime = createRuntime();
  5828. const wechatImagePath =
  5829. "D:\\Yingyong\\social\\wechat\\xwechat_files\\wxid_demo\\temp\\RWTemp\\2026-08\\3336519cd4d5351f4bc5a5a68c7fea75.png";
  5830. const resolveAttachment = vi.fn(async () => ({
  5831. type: "image" as const,
  5832. filePath: wechatImagePath,
  5833. fileName: "3336519cd4d5351f4bc5a5a68c7fea75.png",
  5834. mimeType: "image/png",
  5835. sizeBytes: 1_024,
  5836. }));
  5837. const app = createTuiApp({
  5838. runtime,
  5839. terminal,
  5840. version: "0.1.0",
  5841. workspaceDir: "D:\\workspace",
  5842. resolveAttachment,
  5843. });
  5844. app.start();
  5845. await app.ready;
  5846. terminal.input?.(`\x1b[200~'${wechatImagePath}'\x1b[201~`);
  5847. await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledOnce());
  5848. expect(resolveAttachment).toHaveBeenCalledWith(`'${wechatImagePath}'`, {
  5849. source: "terminal-paste",
  5850. workspaceDir: "D:\\workspace",
  5851. });
  5852. expect(app.editor.getText()).toBe("[Image #1] ");
  5853. expect(app.tui.render(80).join("\n")).not.toContain("xwechat_files");
  5854. await app.submit("Inspect this image");
  5855. expect(runtime.sendMessage).toHaveBeenCalledWith(
  5856. expect.objectContaining({
  5857. content: "Inspect this image",
  5858. attachments: [
  5859. expect.objectContaining({
  5860. local: { filePath: wechatImagePath },
  5861. }),
  5862. ],
  5863. }),
  5864. expect.any(AbortSignal),
  5865. );
  5866. await app.stop();
  5867. });
  5868. it("keeps an image placeholder visible before a long CJK prompt", async () => {
  5869. const terminal = new FakeTerminal();
  5870. const resolveAttachment = vi.fn(async () => ({
  5871. type: "image" as const,
  5872. filePath: "/tmp/otty-paste/logo.png",
  5873. fileName: "logo.png",
  5874. mimeType: "image/png",
  5875. sizeBytes: 1_024,
  5876. }));
  5877. const app = createTuiApp({
  5878. runtime: createRuntime(),
  5879. terminal,
  5880. version: "0.1.0",
  5881. workspaceDir: "/workspace",
  5882. resolveAttachment,
  5883. });
  5884. app.start();
  5885. await app.ready;
  5886. terminal.input?.("\x1b[200~/tmp/otty-paste/logo.png\x1b[201~");
  5887. await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledTimes(1));
  5888. app.editor.insertTextAtCursor(
  5889. "logo 不太对还是,还出现了奇怪的--; logo你自己截取把:",
  5890. );
  5891. const rendered = app.tui.render(80).join("\n");
  5892. expect(rendered).toContain("[Image #1]");
  5893. await app.stop();
  5894. });
  5895. it("removes an inline image placeholder and its attachment with Backspace", async () => {
  5896. const terminal = new FakeTerminal();
  5897. const resolveAttachment = vi.fn(async () => ({
  5898. type: "image" as const,
  5899. filePath: "/tmp/otty-paste/image-123.png",
  5900. fileName: "image-123.png",
  5901. mimeType: "image/png",
  5902. sizeBytes: 1_024,
  5903. }));
  5904. const app = createTuiApp({
  5905. runtime: createRuntime(),
  5906. terminal,
  5907. version: "0.1.0",
  5908. workspaceDir: "/workspace",
  5909. resolveAttachment,
  5910. });
  5911. app.start();
  5912. await app.ready;
  5913. app.editor.setText("first line\nsecond line");
  5914. terminal.input?.("\x1b[200~/tmp/otty-paste/image-123.png\x1b[201~");
  5915. await vi.waitFor(() => expect(resolveAttachment).toHaveBeenCalledTimes(1));
  5916. expect(app.editor.getText()).toBe("first line\nsecond line [Image #1] ");
  5917. expect(app.tui.render(80).join("\n")).toContain("[Image #1]");
  5918. terminal.input?.("\x7f");
  5919. await vi.waitFor(() =>
  5920. expect(app.editor.getText().trimEnd()).toBe("first line\nsecond line"),
  5921. );
  5922. expect(app.tui.render(80).join("\n")).not.toContain("[Image #1]");
  5923. await app.stop();
  5924. });
  5925. it("resumes Desktop history, supports rename, and executes the files-unchanged fork flow", async () => {
  5926. const terminal = new FakeTerminal();
  5927. const runtime = createRuntime();
  5928. vi.mocked(runtime.listSessions).mockResolvedValue([
  5929. {
  5930. sessionId: "session-existing",
  5931. title: "Existing session",
  5932. workspaceDir: "/workspace",
  5933. updatedAt: 200,
  5934. },
  5935. ]);
  5936. const history = [
  5937. {
  5938. id: "msg-user-v1-fork-source",
  5939. turnId: "turn-history",
  5940. role: "user" as const,
  5941. content: "Try the original approach",
  5942. timestamp: 90,
  5943. },
  5944. {
  5945. id: "assistant-fork-source",
  5946. turnId: "turn-history",
  5947. role: "assistant" as const,
  5948. content: "Recovered answer",
  5949. timestamp: 100,
  5950. actions: { fork: true },
  5951. },
  5952. ];
  5953. const forkRuntime = runtime as TuiRuntime & TuiSessionForkPort;
  5954. vi.mocked(runtime.getMessages).mockResolvedValue(history);
  5955. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  5956. messages: history,
  5957. hasMore: false,
  5958. });
  5959. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  5960. sessionId === "session-fork"
  5961. ? {
  5962. sessionId,
  5963. parentSessionId: "session-existing",
  5964. title: "Existing session (fork 1)",
  5965. workspaceDir: "/workspace",
  5966. }
  5967. : {
  5968. sessionId,
  5969. title: "Existing session",
  5970. workspaceDir: "/workspace",
  5971. },
  5972. );
  5973. vi.mocked(forkRuntime.getSessionForkOptions).mockResolvedValue({
  5974. canFork: true,
  5975. suggestedTitle: "Existing session (fork 1)",
  5976. worktreeVisible: false,
  5977. worktreeEligible: false,
  5978. });
  5979. vi.mocked(forkRuntime.forkSession).mockResolvedValue({
  5980. session: {
  5981. sessionId: "session-fork",
  5982. parentSessionId: "session-existing",
  5983. title: "Existing session (fork 1)",
  5984. workspaceDir: "/workspace",
  5985. },
  5986. });
  5987. const app = createTuiApp({
  5988. runtime,
  5989. terminal,
  5990. version: "0.1.0",
  5991. workspaceDir: "/workspace",
  5992. });
  5993. app.start();
  5994. await app.ready;
  5995. await app.submit("/sessions");
  5996. expect(app.tui.hasOverlay()).toBe(false);
  5997. expect(app.interaction.isActive()).toBe(true);
  5998. app.interaction.current()?.handleInput?.("\x1b");
  5999. expect(app.interaction.isActive()).toBe(false);
  6000. await app.submit("/resume 1");
  6001. expect(app.getSurface()).toBe("conversation");
  6002. vi.mocked(runtime.renameSession).mockClear();
  6003. await app.submit("/rename");
  6004. expect(runtime.renameSession).not.toHaveBeenCalled();
  6005. expect(app.interaction.isActive()).toBe(true);
  6006. expect(app.tui.render(100).join("\n")).toContain(
  6007. "Sessions / Rename session",
  6008. );
  6009. app.interaction.current()?.handleInput?.("\x1b");
  6010. expect(app.tui.render(100).join("\n")).toContain("Sessions");
  6011. app.interaction.current()?.handleInput?.("\x1b");
  6012. expect(app.interaction.isActive()).toBe(false);
  6013. await app.submit("/rename Renamed session");
  6014. vi.mocked(runtime.createSession).mockClear();
  6015. await app.submit("/fork");
  6016. await vi.waitFor(() =>
  6017. expect(runtime.listSessionInputSummaries).toHaveBeenCalledWith(
  6018. "session-existing",
  6019. {
  6020. limit: 100,
  6021. },
  6022. ),
  6023. );
  6024. // The new fork flow owns the surface with the history picker, not the
  6025. // generic transcript panel.
  6026. expect(renderTerminalViewport(app, terminal)).toContain(
  6027. "Fork from a previous message",
  6028. );
  6029. expect(renderTerminalViewport(app, terminal)).not.toContain("Transcript");
  6030. // Esc cancels without calling the fork Runtime API.
  6031. const beforeForkCalls = vi.mocked(runtime.forkSession).mock.calls.length;
  6032. app.surfaceHost.popFeature();
  6033. expect(vi.mocked(runtime.forkSession).mock.calls.length).toBe(
  6034. beforeForkCalls,
  6035. );
  6036. const transcriptBeforeStatus = app.transcript.snapshot();
  6037. await app.submit("/status");
  6038. expect(runtime.getSession).toHaveBeenCalledWith("session-existing");
  6039. expect(app.interaction.current()).toBeDefined();
  6040. expect(app.transcript.snapshot()).toEqual(transcriptBeforeStatus);
  6041. expect(app.tui.render(100).join("\n")).toContain("MCode status");
  6042. expect(runtime.renameSession).toHaveBeenCalledWith(
  6043. "session-existing",
  6044. "Renamed session",
  6045. );
  6046. expect(runtime.createSession).not.toHaveBeenCalled();
  6047. expect(app.transcript.snapshot()).not.toEqual(
  6048. expect.arrayContaining([
  6049. expect.objectContaining({ content: "Unknown command. Use /help." }),
  6050. ]),
  6051. );
  6052. app.interaction.current()?.handleInput?.("\x1b");
  6053. await app.stop();
  6054. });
  6055. it.each(["regular", "fullscreen"] as const)(
  6056. "presents /history in %s mode and returns to chat on cancel",
  6057. async (tuiMode) => {
  6058. const terminal = new FakeTerminal();
  6059. const runtime = createRuntime();
  6060. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6061. {
  6062. userMessageId: "msg-user-history",
  6063. assistantMessageId: "msg-assistant-history",
  6064. contentHead: "Inspect the Session UI",
  6065. timestamp: 1_700_000_000_000,
  6066. fileChangeCount: 1,
  6067. },
  6068. ]);
  6069. const app = createTuiApp({
  6070. runtime,
  6071. terminal,
  6072. version: "0.1.0",
  6073. workspaceDir: "/workspace",
  6074. tuiMode,
  6075. });
  6076. app.start();
  6077. await app.ready;
  6078. await app.submit("Seed the session");
  6079. await app.submit("/history");
  6080. await vi.waitFor(() =>
  6081. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6082. kind: "feature",
  6083. id: "session-history:explorer",
  6084. }),
  6085. );
  6086. expect(renderTerminalViewport(app, terminal)).toContain(
  6087. "Inspect the Session UI",
  6088. );
  6089. expect(renderTerminalViewport(app, terminal)).toContain("Search:");
  6090. expect(renderTerminalViewport(app, terminal)).toContain("Enter actions");
  6091. terminal.input?.("\u001b");
  6092. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6093. kind: "chat",
  6094. id: "chat",
  6095. });
  6096. await app.stop();
  6097. },
  6098. );
  6099. it("forks with the assistant boundary and starts a new operation after a terminal failure", async () => {
  6100. const terminal = new FakeTerminal();
  6101. const runtime = createRuntime();
  6102. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6103. {
  6104. userMessageId: "msg-user-1",
  6105. assistantMessageId: "msg-assistant-1",
  6106. contentHead: "Investigate flaky login tests",
  6107. timestamp: 1_700_000_000_000,
  6108. fileChangeCount: 2,
  6109. },
  6110. {
  6111. userMessageId: "msg-user-2",
  6112. assistantMessageId: "msg-assistant-2",
  6113. contentHead: "Draft a new CLI handler",
  6114. timestamp: 1_699_999_000_000,
  6115. fileChangeCount: 0,
  6116. },
  6117. ]);
  6118. vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
  6119. canFork: true,
  6120. worktreeVisible: false,
  6121. worktreeEligible: false,
  6122. });
  6123. vi.mocked(runtime.forkSession).mockRejectedValueOnce(
  6124. Object.assign(new Error("persisted fork recovery failed"), {
  6125. key: "FORK_RECOVERY_FAILED",
  6126. }),
  6127. );
  6128. const app = createTuiApp({
  6129. runtime,
  6130. terminal,
  6131. version: "0.1.0",
  6132. workspaceDir: "/workspace",
  6133. });
  6134. app.start();
  6135. await app.ready;
  6136. // Submit a message so the controller has an active session id.
  6137. await app.submit("Seed the session");
  6138. await vi.waitFor(() =>
  6139. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6140. );
  6141. const sourceSessionId = app.controller.snapshot().session?.sessionId;
  6142. expect(sourceSessionId).toBe("session-1");
  6143. const transcriptBefore = app.transcript.snapshot();
  6144. vi.mocked(runtime.createSession).mockClear();
  6145. vi.mocked(runtime.forkSession).mockClear();
  6146. vi.mocked(runtime.getSessionForkOptions).mockClear();
  6147. vi.mocked(runtime.listSessionInputSummaries).mockClear();
  6148. await app.submit("/fork");
  6149. // 1. /fork loads input summaries, not the generic transcript.
  6150. await vi.waitFor(() =>
  6151. expect(runtime.listSessionInputSummaries).toHaveBeenCalledWith(
  6152. sourceSessionId,
  6153. {
  6154. limit: 100,
  6155. },
  6156. ),
  6157. );
  6158. expect(renderTerminalViewport(app, terminal)).toContain(
  6159. "Fork from a previous message",
  6160. );
  6161. expect(renderTerminalViewport(app, terminal)).not.toContain("Transcript");
  6162. // 2. The newest summary (last entry) is selected by default; confirm with Enter.
  6163. await vi.waitFor(() =>
  6164. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6165. kind: "feature",
  6166. id: "session-mutation:history",
  6167. }),
  6168. );
  6169. terminal.input?.("\r");
  6170. // The history selection only fetches options; it must not mutate yet.
  6171. await vi.waitFor(() =>
  6172. expect(runtime.getSessionForkOptions).toHaveBeenCalledWith(
  6173. sourceSessionId,
  6174. "msg-assistant-2",
  6175. ),
  6176. );
  6177. await vi.waitFor(() =>
  6178. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6179. kind: "feature",
  6180. id: "session-mutation:fork-confirm",
  6181. }),
  6182. );
  6183. expect(runtime.forkSession).not.toHaveBeenCalled();
  6184. expect(renderTerminalViewport(app, terminal)).toContain("Confirm fork");
  6185. // 3. Explicit confirmation performs the mutation.
  6186. terminal.input?.("\r");
  6187. await vi.waitFor(() =>
  6188. expect(runtime.forkSession).toHaveBeenCalledWith(
  6189. expect.objectContaining({
  6190. sessionId: sourceSessionId,
  6191. assistantMessageId: "msg-assistant-2",
  6192. useSuggestedTitle: true,
  6193. createIsolatedWorktree: false,
  6194. }),
  6195. ),
  6196. );
  6197. await vi.waitFor(() =>
  6198. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6199. kind: "feature",
  6200. id: "session-mutation:fork-confirm",
  6201. }),
  6202. );
  6203. terminal.input?.("\r");
  6204. await vi.waitFor(() =>
  6205. expect(runtime.forkSession).toHaveBeenCalledTimes(2),
  6206. );
  6207. const forkCalls = vi.mocked(runtime.forkSession).mock.calls;
  6208. const operationIds = forkCalls.map(([input]) => input.clientRequestId);
  6209. expect(operationIds[0]).toBeTruthy();
  6210. expect(operationIds[1]).toBeTruthy();
  6211. expect(operationIds[0]).not.toBe(operationIds[1]);
  6212. // 5. Activation moves the controller to the child session id.
  6213. await vi.waitFor(() =>
  6214. expect(app.controller.snapshot().session?.sessionId).toBe("session-fork"),
  6215. );
  6216. expect(runtime.createSession).not.toHaveBeenCalled();
  6217. // The user message that seeded the source session was already projected
  6218. // into the transcript before the fork ran; the fork flow must not write
  6219. // any new user-typed cell while the picker is open or the mutation runs.
  6220. expect(
  6221. transcriptBefore.filter((cell) => cell.kind === "user").length,
  6222. ).toBeGreaterThan(0);
  6223. });
  6224. it("does not call forkSession when /fork is cancelled, unavailable, or fails", async () => {
  6225. const scenarios: ReadonlyArray<{
  6226. readonly label: string;
  6227. readonly setup: (runtime: ReturnType<typeof createRuntime>) => void;
  6228. readonly interact: (terminal: FakeTerminal) => void | Promise<void>;
  6229. /** When true, expect forkSession to have been called exactly once. */
  6230. readonly expectForkCall: boolean;
  6231. readonly confirmAfterSelection?: boolean;
  6232. }> = [
  6233. {
  6234. label: "esc cancels the picker without invoking fork",
  6235. setup: (runtime) => {
  6236. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6237. {
  6238. userMessageId: "msg-user-1",
  6239. assistantMessageId: "msg-assistant-1",
  6240. contentHead: "Investigate flaky login tests",
  6241. timestamp: 1_700_000_000_000,
  6242. fileChangeCount: 0,
  6243. },
  6244. ]);
  6245. },
  6246. interact: (terminal) => {
  6247. terminal.input?.("\u001b");
  6248. },
  6249. expectForkCall: false,
  6250. },
  6251. {
  6252. label: "unavailable fork surfaces a warning without invoking fork",
  6253. setup: (runtime) => {
  6254. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6255. {
  6256. userMessageId: "msg-user-1",
  6257. assistantMessageId: "msg-assistant-1",
  6258. contentHead: "Investigate flaky login tests",
  6259. timestamp: 1_700_000_000_000,
  6260. fileChangeCount: 0,
  6261. },
  6262. ]);
  6263. vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
  6264. canFork: false,
  6265. unavailableReason: "No persisted user prompts yet.",
  6266. worktreeVisible: false,
  6267. worktreeEligible: false,
  6268. });
  6269. },
  6270. interact: (terminal) => {
  6271. terminal.input?.("\r");
  6272. },
  6273. expectForkCall: false,
  6274. },
  6275. {
  6276. label:
  6277. "forkSession failure preserves the source session and transcript",
  6278. setup: (runtime) => {
  6279. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6280. {
  6281. userMessageId: "msg-user-1",
  6282. assistantMessageId: "msg-assistant-1",
  6283. contentHead: "Investigate flaky login tests",
  6284. timestamp: 1_700_000_000_000,
  6285. fileChangeCount: 0,
  6286. },
  6287. ]);
  6288. vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
  6289. canFork: true,
  6290. worktreeVisible: false,
  6291. worktreeEligible: false,
  6292. });
  6293. vi.mocked(runtime.forkSession).mockRejectedValue(
  6294. new Error("Runtime offline."),
  6295. );
  6296. },
  6297. interact: (terminal) => {
  6298. terminal.input?.("\r");
  6299. },
  6300. expectForkCall: true,
  6301. confirmAfterSelection: true,
  6302. },
  6303. ];
  6304. for (const scenario of scenarios) {
  6305. const terminal = new FakeTerminal();
  6306. const runtime = createRuntime();
  6307. scenario.setup(runtime);
  6308. const app = createTuiApp({
  6309. runtime,
  6310. terminal,
  6311. version: "0.1.0",
  6312. workspaceDir: "/workspace",
  6313. });
  6314. app.start();
  6315. await app.ready;
  6316. await app.submit("Seed the session");
  6317. await vi.waitFor(() =>
  6318. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6319. );
  6320. const sourceSessionId = app.controller.snapshot().session?.sessionId;
  6321. const transcriptBefore = app.transcript.snapshot();
  6322. await app.submit("/fork");
  6323. await vi.waitFor(() =>
  6324. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6325. kind: "feature",
  6326. id: "session-mutation:history",
  6327. }),
  6328. );
  6329. await scenario.interact(terminal);
  6330. if (scenario.expectForkCall || scenario.label.includes("unavailable")) {
  6331. await vi.waitFor(() =>
  6332. expect(runtime.getSessionForkOptions).toHaveBeenCalled(),
  6333. );
  6334. }
  6335. expect(runtime.forkSession).not.toHaveBeenCalled();
  6336. if (scenario.confirmAfterSelection) {
  6337. terminal.input?.("\r");
  6338. }
  6339. // Give the async fork pipeline a chance to settle.
  6340. await new Promise((resolve) => setTimeout(resolve, 40));
  6341. if (scenario.expectForkCall) {
  6342. expect(
  6343. vi.mocked(runtime.forkSession).mock.calls.length,
  6344. `${scenario.label} should call forkSession once`,
  6345. ).toBe(1);
  6346. } else {
  6347. expect(
  6348. vi.mocked(runtime.forkSession).mock.calls.length,
  6349. `${scenario.label} should not call forkSession`,
  6350. ).toBe(0);
  6351. }
  6352. expect(
  6353. app.controller.snapshot().session?.sessionId,
  6354. `${scenario.label} must not switch sessions`,
  6355. ).toBe(sourceSessionId);
  6356. expect(
  6357. app.transcript.snapshot().filter((cell) => cell.kind === "user").length,
  6358. `${scenario.label} must preserve the source transcript`,
  6359. ).toBe(transcriptBefore.filter((cell) => cell.kind === "user").length);
  6360. await app.stop();
  6361. }
  6362. });
  6363. it("does not call forkSession when the source session changes between summary and selection", async () => {
  6364. const terminal = new FakeTerminal();
  6365. const runtime = createRuntime();
  6366. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6367. {
  6368. userMessageId: "msg-user-1",
  6369. assistantMessageId: "msg-assistant-1",
  6370. contentHead: "Investigate flaky login tests",
  6371. timestamp: 1_700_000_000_000,
  6372. fileChangeCount: 0,
  6373. },
  6374. ]);
  6375. vi.mocked(runtime.getSessionForkOptions).mockResolvedValue({
  6376. canFork: true,
  6377. worktreeVisible: false,
  6378. worktreeEligible: false,
  6379. });
  6380. const app = createTuiApp({
  6381. runtime,
  6382. terminal,
  6383. version: "0.1.0",
  6384. workspaceDir: "/workspace",
  6385. });
  6386. app.start();
  6387. await app.ready;
  6388. await app.submit("Seed the session");
  6389. await vi.waitFor(() =>
  6390. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6391. );
  6392. await app.submit("/fork");
  6393. await vi.waitFor(() =>
  6394. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6395. kind: "feature",
  6396. id: "session-mutation:history",
  6397. }),
  6398. );
  6399. // Simulate the source session changing while the picker is open.
  6400. const otherSession = {
  6401. sessionId: "session-other",
  6402. title: "Other session",
  6403. workspaceDir: "/workspace",
  6404. };
  6405. vi.mocked(runtime.listSessions).mockResolvedValue([otherSession]);
  6406. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  6407. sessionId === otherSession.sessionId
  6408. ? otherSession
  6409. : { sessionId, workspaceDir: "/workspace" },
  6410. );
  6411. await app.openSession(otherSession.sessionId);
  6412. expect(app.controller.snapshot().session?.sessionId).toBe(
  6413. otherSession.sessionId,
  6414. );
  6415. // Confirming the picker now must not call forkSession.
  6416. terminal.input?.("\r");
  6417. await new Promise((resolve) => setTimeout(resolve, 20));
  6418. expect(vi.mocked(runtime.forkSession)).not.toHaveBeenCalled();
  6419. expect(vi.mocked(runtime.getSessionForkOptions).mock.calls.length).toBe(0);
  6420. });
  6421. it("preserves the /fork command draft and skips mutation when a turn is running", async () => {
  6422. const terminal = new FakeTerminal();
  6423. const runtime = createRuntime();
  6424. let finishTurn: (() => void) | undefined;
  6425. vi.mocked(runtime.sendMessage).mockImplementation(
  6426. async function* sendMessage() {
  6427. await new Promise<void>((resolve) => {
  6428. finishTurn = resolve;
  6429. });
  6430. yield { type: "done" };
  6431. },
  6432. );
  6433. const app = createTuiApp({
  6434. runtime,
  6435. terminal,
  6436. version: "0.1.0",
  6437. workspaceDir: "/workspace",
  6438. });
  6439. app.start();
  6440. await app.ready;
  6441. const submission = app.submit("Seed the session");
  6442. await vi.waitFor(() =>
  6443. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6444. );
  6445. await vi.waitFor(() =>
  6446. expect(vi.mocked(runtime.sendMessage)).toHaveBeenCalled(),
  6447. );
  6448. const summariesBefore = vi.mocked(runtime.listSessionInputSummaries).mock
  6449. .calls.length;
  6450. const forkOptionsBefore = vi.mocked(runtime.getSessionForkOptions).mock
  6451. .calls.length;
  6452. const forkBefore = vi.mocked(runtime.forkSession).mock.calls.length;
  6453. // While the turn is still running, /fork should preserve the draft and
  6454. // skip every runtime mutation method.
  6455. app.editor.setText("/fork");
  6456. await app.submit("/fork");
  6457. expect(app.editor.getText()).toBe("/fork");
  6458. expect(vi.mocked(runtime.listSessionInputSummaries).mock.calls.length).toBe(
  6459. summariesBefore,
  6460. );
  6461. expect(vi.mocked(runtime.getSessionForkOptions).mock.calls.length).toBe(
  6462. forkOptionsBefore,
  6463. );
  6464. expect(vi.mocked(runtime.forkSession).mock.calls.length).toBe(forkBefore);
  6465. // The fork surface should not have been pushed either.
  6466. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6467. kind: "chat",
  6468. id: "chat",
  6469. });
  6470. finishTurn?.();
  6471. await submission;
  6472. await app.stop();
  6473. });
  6474. it.each([
  6475. ["conversation", []],
  6476. ["conversation_and_files", ["\u001b[B"]],
  6477. ] as const)(
  6478. "runs /rewind with explicit %s scope and stable operation id",
  6479. async (scope, navigation) => {
  6480. const terminal = new FakeTerminal();
  6481. const runtime = createRuntime();
  6482. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6483. {
  6484. userMessageId: "msg-user-rewind",
  6485. contentHead: "Undo this point",
  6486. timestamp: 1_700_000_000_000,
  6487. fileChangeCount: 2,
  6488. },
  6489. ]);
  6490. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  6491. turns: [
  6492. {
  6493. turnId: "turn-1",
  6494. files: [
  6495. { filePath: "src/ready.ts", action: "modified", skipped: false },
  6496. { filePath: "src/skipped.ts", action: "deleted", skipped: true },
  6497. ],
  6498. },
  6499. ],
  6500. });
  6501. vi.mocked(runtime.rewindSession).mockResolvedValue(
  6502. scope === "conversation"
  6503. ? { rewound: true }
  6504. : {
  6505. rewound: true,
  6506. turnDiffRewind: {
  6507. status: "rewound",
  6508. revertedTurnIds: ["turn-1"],
  6509. },
  6510. },
  6511. );
  6512. const app = createTuiApp({
  6513. runtime,
  6514. terminal,
  6515. version: "0.1.0",
  6516. workspaceDir: "/workspace",
  6517. });
  6518. app.start();
  6519. await app.ready;
  6520. await app.submit("Seed rewind session");
  6521. await vi.waitFor(() =>
  6522. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6523. );
  6524. expect(
  6525. app.transcript.snapshot().some((cell) => cell.kind === "turn-duration"),
  6526. ).toBe(true);
  6527. vi.mocked(runtime.getMessages).mockResolvedValue([]);
  6528. await app.submit("/rewind");
  6529. await vi.waitFor(() =>
  6530. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6531. kind: "feature",
  6532. id: "session-mutation:history",
  6533. }),
  6534. );
  6535. terminal.input?.("\r");
  6536. await vi.waitFor(() =>
  6537. expect(runtime.getSessionRewindPreview).toHaveBeenCalledWith({
  6538. sessionId: "session-1",
  6539. userMessageId: "msg-user-rewind",
  6540. }),
  6541. );
  6542. await vi.waitFor(() =>
  6543. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6544. kind: "feature",
  6545. id: "session-mutation:rewind-preview",
  6546. }),
  6547. );
  6548. expect(renderTerminalViewport(app, terminal)).toContain("src/ready.ts");
  6549. expect(renderTerminalViewport(app, terminal)).toContain("src/skipped.ts");
  6550. terminal.input?.("\r");
  6551. await vi.waitFor(() =>
  6552. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6553. kind: "feature",
  6554. id: "session-mutation:scope",
  6555. }),
  6556. );
  6557. for (const key of navigation) terminal.input?.(key);
  6558. terminal.input?.("\r");
  6559. await vi.waitFor(() =>
  6560. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6561. kind: "feature",
  6562. id: "session-mutation:rewind-confirm",
  6563. }),
  6564. );
  6565. expect(runtime.rewindSession).not.toHaveBeenCalled();
  6566. terminal.input?.("\r");
  6567. await vi.waitFor(() =>
  6568. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  6569. );
  6570. const input = vi.mocked(runtime.rewindSession).mock.calls[0]?.[0];
  6571. expect(input).toEqual({
  6572. sessionId: "session-1",
  6573. userMessageId: "msg-user-rewind",
  6574. clientRequestId: expect.stringMatching(/^tui-rewind_/),
  6575. ...(scope === "conversation_and_files" ? { rewindTurnDiff: true } : {}),
  6576. });
  6577. expect(input?.clientRequestId).toMatch(/^tui-rewind_/);
  6578. await vi.waitFor(() => expect(runtime.getMessages).toHaveBeenCalled());
  6579. await vi.waitFor(() =>
  6580. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6581. kind: "chat",
  6582. id: "chat",
  6583. }),
  6584. );
  6585. expect(
  6586. app.transcript
  6587. .snapshot()
  6588. .some((cell) => cell.content === "Rewind completed."),
  6589. ).toBe(false);
  6590. expect(app.transcript.snapshot()).toEqual([]);
  6591. await app.stop();
  6592. },
  6593. );
  6594. it("edits only the latest user turn, hides that turn while editing, and adds no completion cell", async () => {
  6595. const terminal = new FakeTerminal();
  6596. const runtime = createRuntime();
  6597. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6598. {
  6599. userMessageId: "msg-user-older",
  6600. assistantMessageId: "msg-assistant-older",
  6601. contentHead: "Older prompt",
  6602. timestamp: 1,
  6603. fileChangeCount: 0,
  6604. },
  6605. {
  6606. userMessageId: "msg-user-latest",
  6607. assistantMessageId: "msg-assistant-latest",
  6608. contentHead: "Latest prompt",
  6609. timestamp: 2,
  6610. fileChangeCount: 0,
  6611. },
  6612. ]);
  6613. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  6614. messages: [
  6615. {
  6616. id: "msg-user-older",
  6617. role: "user",
  6618. content: "Older prompt",
  6619. timestamp: 1,
  6620. },
  6621. {
  6622. id: "msg-user-latest",
  6623. role: "user",
  6624. content: "Latest prompt",
  6625. timestamp: 2,
  6626. },
  6627. ],
  6628. hasMore: false,
  6629. });
  6630. const app = createTuiApp({
  6631. runtime,
  6632. terminal,
  6633. version: "0.1.0",
  6634. workspaceDir: "/workspace",
  6635. });
  6636. app.start();
  6637. await app.ready;
  6638. await app.submit("Seed edit session");
  6639. await vi.waitFor(() =>
  6640. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6641. );
  6642. app.transcript.upsert({
  6643. id: "older-user-cell",
  6644. kind: "user",
  6645. status: "succeeded",
  6646. content: "Older prompt",
  6647. sourceMessageId: "msg-user-older",
  6648. turnId: "turn-older",
  6649. createdAtMs: 1,
  6650. });
  6651. app.transcript.upsert({
  6652. id: "latest-user-cell",
  6653. kind: "user",
  6654. status: "succeeded",
  6655. content: "Latest prompt",
  6656. sourceMessageId: "msg-user-latest",
  6657. turnId: "turn-latest",
  6658. createdAtMs: 2,
  6659. });
  6660. app.transcript.upsert({
  6661. id: "latest-assistant-cell",
  6662. kind: "assistant",
  6663. status: "succeeded",
  6664. content: "Latest response",
  6665. sourceMessageId: "msg-assistant-latest",
  6666. turnId: "turn-latest",
  6667. createdAtMs: 3,
  6668. });
  6669. await app.submit("/edit");
  6670. await vi.waitFor(() =>
  6671. expect(app.editor.getExpandedText()).toBe("Latest prompt"),
  6672. );
  6673. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6674. kind: "chat",
  6675. id: "chat",
  6676. });
  6677. const editingFrame = app.tui.render(100).join("\n");
  6678. expect(editingFrame).toContain("Older prompt");
  6679. expect(editingFrame).not.toContain("Latest response");
  6680. const historyRefreshCount = vi.mocked(runtime.getMessages).mock.calls
  6681. .length;
  6682. app.editor.setText("Edited latest prompt");
  6683. app.editor.handleInput("\r");
  6684. await vi.waitFor(() =>
  6685. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  6686. );
  6687. await vi.waitFor(() =>
  6688. expect(vi.mocked(runtime.getMessages).mock.calls.length).toBeGreaterThan(
  6689. historyRefreshCount,
  6690. ),
  6691. );
  6692. expect(
  6693. app.transcript
  6694. .snapshot()
  6695. .some(
  6696. (cell) =>
  6697. cell.content ===
  6698. "Edited message submitted; regenerating from this point.",
  6699. ),
  6700. ).toBe(false);
  6701. expect(runtime.editSessionMessage).toHaveBeenCalledWith(
  6702. expect.objectContaining({
  6703. userMessageId: "msg-user-latest",
  6704. content: "Edited latest prompt",
  6705. }),
  6706. );
  6707. await app.stop();
  6708. });
  6709. it("restores the hidden latest turn when Edit is cancelled", async () => {
  6710. const terminal = new FakeTerminal();
  6711. const runtime = createRuntime();
  6712. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6713. {
  6714. userMessageId: "msg-user-latest",
  6715. assistantMessageId: "msg-assistant-latest",
  6716. contentHead: "Latest prompt",
  6717. timestamp: 2,
  6718. fileChangeCount: 0,
  6719. },
  6720. ]);
  6721. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  6722. messages: [
  6723. {
  6724. id: "msg-user-latest",
  6725. role: "user",
  6726. content: "Latest prompt",
  6727. timestamp: 2,
  6728. },
  6729. ],
  6730. hasMore: false,
  6731. });
  6732. const app = createTuiApp({
  6733. runtime,
  6734. terminal,
  6735. version: "0.1.0",
  6736. workspaceDir: "/workspace",
  6737. });
  6738. app.start();
  6739. await app.ready;
  6740. await app.submit("Seed edit session");
  6741. app.transcript.upsert({
  6742. id: "latest-user-cell",
  6743. kind: "user",
  6744. status: "succeeded",
  6745. content: "Latest prompt",
  6746. sourceMessageId: "msg-user-latest",
  6747. turnId: "turn-latest",
  6748. createdAtMs: 2,
  6749. });
  6750. app.transcript.upsert({
  6751. id: "latest-assistant-cell",
  6752. kind: "assistant",
  6753. status: "succeeded",
  6754. content: "Latest response restored on cancel",
  6755. sourceMessageId: "msg-assistant-latest",
  6756. turnId: "turn-latest",
  6757. createdAtMs: 3,
  6758. });
  6759. await app.submit("/edit");
  6760. await vi.waitFor(() =>
  6761. expect(app.editor.getExpandedText()).toBe("Latest prompt"),
  6762. );
  6763. expect(app.tui.render(100).join("\n")).not.toContain(
  6764. "Latest response restored on cancel",
  6765. );
  6766. terminal.input?.("\u001b");
  6767. await vi.waitFor(() => expect(app.editor.getExpandedText()).toBe(""));
  6768. expect(app.tui.render(100).join("\n")).toContain(
  6769. "Latest response restored on cancel",
  6770. );
  6771. expect(runtime.editSessionMessage).not.toHaveBeenCalled();
  6772. await app.stop();
  6773. });
  6774. it.each([
  6775. { reference: "filePath", action: "cancel" },
  6776. { reference: "assetId", action: "send" },
  6777. { reference: "assetId", action: "delete" },
  6778. { reference: "filePath", action: "undo" },
  6779. { reference: "assetId", action: "add" },
  6780. { reference: "filePath", action: "clear-restore" },
  6781. { reference: "filePath", action: "cached" },
  6782. ] as const)(
  6783. "restores editable image chips after double Escape and retry ($reference / $action)",
  6784. async ({ reference, action }) => {
  6785. const terminal = new FakeTerminal();
  6786. const runtime = createRuntime();
  6787. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6788. {
  6789. userMessageId: "msg-user-latest",
  6790. assistantMessageId: "msg-assistant-latest",
  6791. contentHead: "Latest prompt from shortcut",
  6792. timestamp: 2,
  6793. fileChangeCount: 0,
  6794. },
  6795. ]);
  6796. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  6797. messages: [
  6798. {
  6799. id: "msg-user-latest",
  6800. role: "user",
  6801. content: "Latest prompt from shortcut",
  6802. attachments: [
  6803. {
  6804. type: "image",
  6805. fileName: "edit-reference.png",
  6806. mimeType: "image/png",
  6807. [reference]:
  6808. reference === "filePath"
  6809. ? "/workspace/edit-reference.png"
  6810. : "asset-edit-image",
  6811. },
  6812. ],
  6813. timestamp: 2,
  6814. },
  6815. ],
  6816. hasMore: false,
  6817. });
  6818. const app = createTuiApp({
  6819. runtime,
  6820. terminal,
  6821. version: "0.1.0",
  6822. workspaceDir: "/workspace",
  6823. resolveAttachment: async (path) => ({
  6824. type: "image",
  6825. filePath: path,
  6826. fileName: path.endsWith("new.png") ? "new.png" : "edit-reference.png",
  6827. mimeType: "image/png",
  6828. sizeBytes: 123,
  6829. }),
  6830. });
  6831. app.start();
  6832. await app.ready;
  6833. let restoredText = "Latest prompt from shortcut [Image #1] ";
  6834. if (action === "cached") {
  6835. terminal.input?.("\x1b[200~/workspace/edit-reference.png\x1b[201~");
  6836. await vi.waitFor(() =>
  6837. expect(app.editor.getText()).toContain("[Image #1]"),
  6838. );
  6839. app.editor.handleInput("Latest prompt from shortcut");
  6840. restoredText = app.editor.getText();
  6841. app.editor.handleInput("\r");
  6842. await vi.waitFor(() =>
  6843. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  6844. );
  6845. await vi.waitFor(() =>
  6846. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  6847. );
  6848. } else {
  6849. await app.submit("Seed edit session");
  6850. }
  6851. terminal.input?.("\u001b");
  6852. terminal.input?.("\u001b");
  6853. await vi.waitFor(() =>
  6854. expect(app.editor.getExpandedText()).toBe(restoredText),
  6855. );
  6856. expect(runtime.listSessionInputSummaries).toHaveBeenCalledWith(
  6857. "session-1",
  6858. { limit: 100 },
  6859. );
  6860. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6861. kind: "chat",
  6862. id: "chat",
  6863. });
  6864. expect(stripAnsi(app.tui.render(100).join("\n"))).toContain("[Image #1]");
  6865. vi.mocked(runtime.editSessionMessage).mockRejectedValueOnce(
  6866. new Error("Temporary failure"),
  6867. );
  6868. app.editor.handleInput("\r");
  6869. await vi.waitFor(() =>
  6870. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  6871. );
  6872. await vi.waitFor(() =>
  6873. expect(app.editor.getExpandedText()).toBe(restoredText),
  6874. );
  6875. expect(stripAnsi(app.tui.render(100).join("\n"))).toContain("[Image #1]");
  6876. expect(runtime.editSessionMessage).toHaveBeenCalledWith(
  6877. expect.objectContaining({
  6878. content: "Latest prompt from shortcut",
  6879. attachments: [
  6880. expect.objectContaining({
  6881. fileName: "edit-reference.png",
  6882. [reference]:
  6883. reference === "filePath"
  6884. ? "/workspace/edit-reference.png"
  6885. : "asset-edit-image",
  6886. }),
  6887. ],
  6888. }),
  6889. );
  6890. if (action === "delete" || action === "undo") {
  6891. app.editor.handleInput("\x05");
  6892. app.editor.handleInput("\x7f");
  6893. await vi.waitFor(() =>
  6894. expect(app.editor.getText()).not.toContain("[Image #1]"),
  6895. );
  6896. if (action === "undo") {
  6897. app.editor.handleInput("\x1f");
  6898. expect(app.editor.getText()).toContain("[Image #1]");
  6899. }
  6900. }
  6901. if (action === "add") {
  6902. terminal.input?.("\x1b[200~/workspace/new.png\x1b[201~");
  6903. await vi.waitFor(() =>
  6904. expect(app.editor.getText()).toContain("[Image #2]"),
  6905. );
  6906. expect(app.editor.captureDraft().attachmentPlaceholders).toHaveLength(
  6907. 2,
  6908. );
  6909. }
  6910. if (action === "clear-restore") {
  6911. terminal.input?.("\x03");
  6912. expect(app.editor.getText()).toBe("");
  6913. terminal.input?.("\x1f");
  6914. expect(app.editor.getText()).toContain("[Image #1]");
  6915. }
  6916. if (action === "cancel") {
  6917. terminal.input?.("\u001b");
  6918. } else {
  6919. app.editor.handleInput("\r");
  6920. await vi.waitFor(() =>
  6921. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(2),
  6922. );
  6923. const sent = vi.mocked(runtime.editSessionMessage).mock.calls[1]?.[0];
  6924. expect(sent?.content).toBe("Latest prompt from shortcut");
  6925. expect(sent?.attachments ?? []).toHaveLength(
  6926. action === "delete" ? 0 : action === "add" ? 2 : 1,
  6927. );
  6928. if (action !== "delete")
  6929. expect(sent?.attachments?.[0]?.fileName).toBe("edit-reference.png");
  6930. }
  6931. await vi.waitFor(() =>
  6932. expect(stripAnsi(app.tui.render(100).join("\n"))).not.toContain(
  6933. "[Image #1]",
  6934. ),
  6935. );
  6936. await app.stop();
  6937. },
  6938. );
  6939. it("edits the latest committed user turn through the desktop-aligned mutation contract", async () => {
  6940. const terminal = new FakeTerminal();
  6941. const runtime = createRuntime();
  6942. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  6943. {
  6944. userMessageId: "msg-user-v1-target",
  6945. assistantMessageId: "msg-assistant-v1-target",
  6946. contentHead: "Original prompt head",
  6947. timestamp: 1_700_000_000_000,
  6948. fileChangeCount: 1,
  6949. },
  6950. ]);
  6951. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  6952. messages: [
  6953. {
  6954. id: "msg-user-v1-target",
  6955. role: "user",
  6956. content: "Original complete prompt",
  6957. attachments: [
  6958. {
  6959. type: "file",
  6960. fileName: "spec.md",
  6961. mimeType: "text/markdown",
  6962. sizeBytes: 42,
  6963. filePath: "/workspace/spec.md",
  6964. },
  6965. ],
  6966. timestamp: 1_700_000_000_000,
  6967. },
  6968. ],
  6969. hasMore: false,
  6970. });
  6971. const app = createTuiApp({
  6972. runtime,
  6973. terminal,
  6974. version: "0.1.0",
  6975. workspaceDir: "/workspace",
  6976. });
  6977. app.start();
  6978. await app.ready;
  6979. await app.submit("Seed edit session");
  6980. await vi.waitFor(() =>
  6981. expect(app.controller.snapshot().session?.sessionId).toBe("session-1"),
  6982. );
  6983. await app.submit("/edit");
  6984. await vi.waitFor(() =>
  6985. expect(app.editor.getExpandedText()).toBe(
  6986. "Original complete prompt [File #1] ",
  6987. ),
  6988. );
  6989. expect(app.surfaceHost.getActiveSurface()).toEqual({
  6990. kind: "chat",
  6991. id: "chat",
  6992. });
  6993. app.editor.setText("Updated prompt");
  6994. app.editor.handleInput("\r");
  6995. await vi.waitFor(() =>
  6996. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  6997. );
  6998. expect(runtime.editSessionMessage).toHaveBeenCalledWith({
  6999. sessionId: "session-1",
  7000. userMessageId: "msg-user-v1-target",
  7001. clientRequestId: expect.stringMatching(/^tui-edit_/u),
  7002. content: "Updated prompt",
  7003. attachments: [
  7004. {
  7005. type: "file",
  7006. fileName: "spec.md",
  7007. mimeType: "text/markdown",
  7008. sizeBytes: 42,
  7009. filePath: "/workspace/spec.md",
  7010. },
  7011. ],
  7012. rewindTurnDiff: true,
  7013. });
  7014. await app.stop();
  7015. });
  7016. it("keeps hidden chat context out of the editor and restores it for Edit transport", async () => {
  7017. const terminal = new FakeTerminal();
  7018. const runtime = createRuntime();
  7019. const transportContent = [
  7020. "<user-provided-context>",
  7021. "Referenced context",
  7022. "</user-provided-context>",
  7023. "",
  7024. "Original visible prompt",
  7025. ].join("\n");
  7026. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7027. {
  7028. userMessageId: "msg-user-v1-context",
  7029. assistantMessageId: "msg-assistant-v1-context",
  7030. contentHead: "Original visible prompt",
  7031. timestamp: 1_700_000_000_000,
  7032. fileChangeCount: 0,
  7033. },
  7034. ]);
  7035. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7036. messages: [
  7037. {
  7038. id: "msg-user-v1-context",
  7039. role: "user",
  7040. content: transportContent,
  7041. timestamp: 1_700_000_000_000,
  7042. },
  7043. ],
  7044. hasMore: false,
  7045. });
  7046. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7047. const app = createTuiApp({
  7048. runtime,
  7049. terminal,
  7050. version: "0.1.0",
  7051. workspaceDir: "/workspace",
  7052. });
  7053. app.start();
  7054. await app.ready;
  7055. await app.submit("Seed edit session");
  7056. await app.submit("/edit");
  7057. await vi.waitFor(() =>
  7058. expect(app.editor.getExpandedText()).toBe("Original visible prompt"),
  7059. );
  7060. expect(app.editor.getExpandedText()).not.toContain("user-provided-context");
  7061. app.editor.setText("Updated visible prompt");
  7062. app.editor.handleInput("\r");
  7063. await vi.waitFor(() =>
  7064. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7065. );
  7066. expect(runtime.editSessionMessage).toHaveBeenCalledWith(
  7067. expect.objectContaining({
  7068. content: [
  7069. "<user-provided-context>",
  7070. "Referenced context",
  7071. "</user-provided-context>",
  7072. "",
  7073. "Updated visible prompt",
  7074. ].join("\n"),
  7075. }),
  7076. );
  7077. await app.stop();
  7078. });
  7079. it("preserves hidden context and attachments when Edit recovery requires a new message", async () => {
  7080. const terminal = new FakeTerminal();
  7081. const runtime = createRuntime();
  7082. const transportContent = [
  7083. "<mavis-chat-context>",
  7084. "Referenced context",
  7085. "</mavis-chat-context>",
  7086. "",
  7087. "Original visible prompt",
  7088. ].join("\n");
  7089. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7090. {
  7091. userMessageId: "msg-user-v1-recovery",
  7092. assistantMessageId: "msg-assistant-v1-recovery",
  7093. contentHead: "Original visible prompt",
  7094. timestamp: 1_700_000_000_000,
  7095. fileChangeCount: 0,
  7096. },
  7097. ]);
  7098. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7099. messages: [
  7100. {
  7101. id: "msg-user-v1-recovery",
  7102. role: "user",
  7103. content: transportContent,
  7104. attachments: [
  7105. {
  7106. type: "file",
  7107. fileName: "context.md",
  7108. mimeType: "text/markdown",
  7109. sizeBytes: 42,
  7110. assetId: "asset-context-md",
  7111. },
  7112. ],
  7113. timestamp: 1_700_000_000_000,
  7114. },
  7115. ],
  7116. hasMore: false,
  7117. });
  7118. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7119. vi.mocked(runtime.editSessionMessage).mockRejectedValueOnce(
  7120. Object.assign(new Error("history already rewound"), {
  7121. key: "EDIT_RESTART_NEEDS_RESUBMIT",
  7122. }),
  7123. );
  7124. const app = createTuiApp({
  7125. runtime,
  7126. terminal,
  7127. version: "0.1.0",
  7128. workspaceDir: "/workspace",
  7129. });
  7130. app.start();
  7131. await app.ready;
  7132. await app.submit("Seed edit session");
  7133. const sendCountBeforeEdit = vi.mocked(runtime.sendMessage).mock.calls
  7134. .length;
  7135. await app.submit("/edit");
  7136. await vi.waitFor(() =>
  7137. expect(app.editor.getExpandedText()).toBe(
  7138. "Original visible prompt [File #1] ",
  7139. ),
  7140. );
  7141. app.editor.setText("/help should remain message text");
  7142. app.editor.handleInput("\r");
  7143. await vi.waitFor(() =>
  7144. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7145. );
  7146. await vi.waitFor(() =>
  7147. expect(app.editor.getExpandedText()).toBe(
  7148. "/help should remain message text [File #1] ",
  7149. ),
  7150. );
  7151. expect(app.editor.getExpandedText()).not.toContain("mavis-chat-context");
  7152. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
  7153. let releaseAdmission!: () => void;
  7154. vi.mocked(runtime.getAccountStatus).mockImplementationOnce(
  7155. async () =>
  7156. await new Promise((resolve) => {
  7157. releaseAdmission = () =>
  7158. resolve({
  7159. status: "ready",
  7160. defaultModel: "minimax/MiniMax-M2.7",
  7161. providerId: "minimax",
  7162. modelId: "MiniMax-M2.7",
  7163. authMode: "managed-login",
  7164. managedTokenPresent: true,
  7165. warnings: [],
  7166. });
  7167. }),
  7168. );
  7169. app.editor.handleInput("\r");
  7170. await vi.waitFor(() =>
  7171. expect(app.controller.snapshot().activeTurnId).toBeDefined(),
  7172. );
  7173. terminal.input?.("\u001b");
  7174. releaseAdmission();
  7175. await vi.waitFor(() =>
  7176. expect(app.editor.getExpandedText()).toBe(
  7177. "/help should remain message text [File #1] ",
  7178. ),
  7179. );
  7180. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
  7181. app.editor.handleInput("\r");
  7182. await vi.waitFor(() =>
  7183. expect(runtime.sendMessage).toHaveBeenCalledTimes(
  7184. sendCountBeforeEdit + 1,
  7185. ),
  7186. );
  7187. expect(vi.mocked(runtime.sendMessage).mock.calls.at(-1)?.[0]).toMatchObject(
  7188. {
  7189. content: [
  7190. "<mavis-chat-context>",
  7191. "Referenced context",
  7192. "</mavis-chat-context>",
  7193. "",
  7194. "/help should remain message text",
  7195. ].join("\n"),
  7196. attachments: [
  7197. {
  7198. meta: {
  7199. attachmentType: "file",
  7200. fileName: "context.md",
  7201. mimeType: "text/markdown",
  7202. sizeBytes: 42,
  7203. },
  7204. local: { assetId: "asset-context-md" },
  7205. },
  7206. ],
  7207. },
  7208. );
  7209. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1);
  7210. expect(
  7211. app.transcript
  7212. .snapshot()
  7213. .filter((cell) => cell.kind === "user")
  7214. .map((cell) => cell.content)
  7215. .join("\n"),
  7216. ).toContain("/help should remain message text");
  7217. expect(
  7218. app.transcript
  7219. .snapshot()
  7220. .filter((cell) => cell.kind === "user")
  7221. .map((cell) => cell.content)
  7222. .join("\n"),
  7223. ).not.toContain("mavis-chat-context");
  7224. await app.stop();
  7225. });
  7226. it("allows an attachment-only committed message to enter Edit and gain a body", async () => {
  7227. const terminal = new FakeTerminal();
  7228. const runtime = createRuntime();
  7229. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7230. {
  7231. userMessageId: "msg-user-v1-attachment-only",
  7232. assistantMessageId: "msg-assistant-v1-attachment-only",
  7233. timestamp: 1_700_000_000_000,
  7234. fileChangeCount: 0,
  7235. },
  7236. ]);
  7237. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7238. messages: [
  7239. {
  7240. id: "msg-user-v1-attachment-only",
  7241. role: "user",
  7242. content: "",
  7243. attachments: [
  7244. {
  7245. type: "image",
  7246. fileName: "reference.png",
  7247. mimeType: "image/png",
  7248. filePath: "/workspace/reference.png",
  7249. },
  7250. ],
  7251. timestamp: 1_700_000_000_000,
  7252. },
  7253. ],
  7254. hasMore: false,
  7255. });
  7256. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7257. const app = createTuiApp({
  7258. runtime,
  7259. terminal,
  7260. version: "0.1.0",
  7261. workspaceDir: "/workspace",
  7262. });
  7263. app.start();
  7264. await app.ready;
  7265. await app.submit("Seed edit session");
  7266. const sendCountBeforeEdit = vi.mocked(runtime.sendMessage).mock.calls
  7267. .length;
  7268. await app.submit("/edit");
  7269. await vi.waitFor(() =>
  7270. expect(app.tui.render(100).join("\n")).toContain(
  7271. "Editing the selected message",
  7272. ),
  7273. );
  7274. expect(app.editor.getExpandedText()).toBe("[Image #1] ");
  7275. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7276. kind: "chat",
  7277. id: "chat",
  7278. });
  7279. app.editor.setText("Describe this reference");
  7280. app.editor.handleInput("\r");
  7281. await vi.waitFor(() =>
  7282. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7283. );
  7284. expect(runtime.editSessionMessage).toHaveBeenCalledWith({
  7285. sessionId: "session-1",
  7286. userMessageId: "msg-user-v1-attachment-only",
  7287. clientRequestId: expect.stringMatching(/^tui-edit_/u),
  7288. content: "Describe this reference",
  7289. attachments: [
  7290. {
  7291. type: "image",
  7292. fileName: "reference.png",
  7293. mimeType: "image/png",
  7294. filePath: "/workspace/reference.png",
  7295. },
  7296. ],
  7297. rewindTurnDiff: true,
  7298. });
  7299. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
  7300. await app.stop();
  7301. });
  7302. it("keeps a second composer submission while an edit request is still in flight", async () => {
  7303. const terminal = new FakeTerminal();
  7304. const runtime = createRuntime();
  7305. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7306. {
  7307. userMessageId: "msg-user-v1-target",
  7308. assistantMessageId: "msg-assistant-v1-target",
  7309. contentHead: "Original prompt",
  7310. timestamp: 1,
  7311. fileChangeCount: 0,
  7312. },
  7313. ]);
  7314. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7315. messages: [
  7316. {
  7317. id: "msg-user-v1-target",
  7318. role: "user",
  7319. content: "Original prompt",
  7320. timestamp: 1,
  7321. },
  7322. ],
  7323. hasMore: false,
  7324. });
  7325. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7326. let resolveEdit!: (value: {
  7327. rewound: boolean;
  7328. turnId: string;
  7329. userMessageId: string;
  7330. }) => void;
  7331. vi.mocked(runtime.editSessionMessage).mockImplementation(
  7332. () =>
  7333. new Promise((resolve) => {
  7334. resolveEdit = resolve;
  7335. }),
  7336. );
  7337. const app = createTuiApp({
  7338. runtime,
  7339. terminal,
  7340. version: "0.1.0",
  7341. workspaceDir: "/workspace",
  7342. });
  7343. app.start();
  7344. await app.ready;
  7345. await app.submit("Seed edit session");
  7346. const sendCountBeforeEdit = vi.mocked(runtime.sendMessage).mock.calls
  7347. .length;
  7348. await app.submit("/edit");
  7349. await vi.waitFor(() =>
  7350. expect(app.editor.getText()).toBe("Original prompt"),
  7351. );
  7352. app.editor.setText("First edited prompt");
  7353. app.editor.handleInput("\r");
  7354. await vi.waitFor(() =>
  7355. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7356. );
  7357. app.editor.setText("Keep this until edit settles");
  7358. app.editor.handleInput("\r");
  7359. await vi.waitFor(() =>
  7360. expect(app.editor.getText()).toBe("Keep this until edit settles"),
  7361. );
  7362. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCountBeforeEdit);
  7363. resolveEdit({
  7364. rewound: true,
  7365. turnId: "turn-edit-1",
  7366. userMessageId: "msg-user-v1-edited",
  7367. });
  7368. await app.stop();
  7369. });
  7370. it("preserves the edit and retries the same operation when submission fails after rewind", async () => {
  7371. const terminal = new FakeTerminal();
  7372. const runtime = createRuntime();
  7373. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7374. {
  7375. userMessageId: "msg-user-v1-target",
  7376. assistantMessageId: "msg-assistant-v1-target",
  7377. contentHead: "Original prompt",
  7378. timestamp: 1,
  7379. fileChangeCount: 0,
  7380. },
  7381. ]);
  7382. vi.mocked(runtime.listMessagePage).mockResolvedValue({
  7383. messages: [
  7384. {
  7385. id: "msg-user-v1-target",
  7386. role: "user",
  7387. content: "Original prompt",
  7388. timestamp: 1,
  7389. },
  7390. ],
  7391. hasMore: false,
  7392. });
  7393. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7394. vi.mocked(runtime.editSessionMessage)
  7395. .mockRejectedValueOnce(
  7396. Object.assign(new Error("submit failed"), {
  7397. key: "EDIT_SUBMIT_FAILED_AFTER_REWIND",
  7398. }),
  7399. )
  7400. .mockResolvedValueOnce({
  7401. rewound: true,
  7402. turnId: "turn-edit-retry",
  7403. userMessageId: "msg-user-v1-edited",
  7404. });
  7405. const app = createTuiApp({
  7406. runtime,
  7407. terminal,
  7408. version: "0.1.0",
  7409. workspaceDir: "/workspace",
  7410. });
  7411. app.start();
  7412. await app.ready;
  7413. await app.submit("Seed edit session");
  7414. await app.submit("/edit");
  7415. await vi.waitFor(() =>
  7416. expect(app.editor.getText()).toBe("Original prompt"),
  7417. );
  7418. app.editor.setText("Preserve this edited prompt");
  7419. app.editor.handleInput("\r");
  7420. await vi.waitFor(() =>
  7421. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(1),
  7422. );
  7423. await vi.waitFor(() =>
  7424. expect(app.editor.getText()).toBe("Preserve this edited prompt"),
  7425. );
  7426. expect(
  7427. app.transcript
  7428. .snapshot()
  7429. .some((cell) => cell.content.includes("History was rewound")),
  7430. ).toBe(true);
  7431. const firstOperationId = vi.mocked(runtime.editSessionMessage).mock
  7432. .calls[0]?.[0].clientRequestId;
  7433. const sendCount = vi.mocked(runtime.sendMessage).mock.calls.length;
  7434. app.editor.handleInput("\r");
  7435. await vi.waitFor(() =>
  7436. expect(runtime.editSessionMessage).toHaveBeenCalledTimes(2),
  7437. );
  7438. expect(runtime.editSessionMessage).toHaveBeenLastCalledWith(
  7439. expect.objectContaining({ clientRequestId: firstOperationId }),
  7440. );
  7441. expect(runtime.sendMessage).toHaveBeenCalledTimes(sendCount);
  7442. await app.stop();
  7443. });
  7444. it("cancels /rewind preview and ignores duplicate scope submission", async () => {
  7445. const terminal = new FakeTerminal();
  7446. const runtime = createRuntime();
  7447. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7448. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7449. ]);
  7450. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7451. turns: [
  7452. {
  7453. turnId: "turn-1",
  7454. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7455. },
  7456. ],
  7457. });
  7458. let resolveRewind!: (value: { rewound: boolean }) => void;
  7459. vi.mocked(runtime.rewindSession).mockImplementation(
  7460. () =>
  7461. new Promise((resolve) => {
  7462. resolveRewind = resolve;
  7463. }),
  7464. );
  7465. const app = createTuiApp({
  7466. runtime,
  7467. terminal,
  7468. version: "0.1.0",
  7469. workspaceDir: "/workspace",
  7470. });
  7471. app.start();
  7472. await app.ready;
  7473. await app.submit("Seed rewind session");
  7474. await app.submit("/rewind");
  7475. await vi.waitFor(() =>
  7476. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7477. kind: "feature",
  7478. id: "session-mutation:history",
  7479. }),
  7480. );
  7481. terminal.input?.("\r");
  7482. await vi.waitFor(() =>
  7483. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7484. kind: "feature",
  7485. id: "session-mutation:rewind-preview",
  7486. }),
  7487. );
  7488. terminal.input?.("\u001b");
  7489. expect(runtime.rewindSession).not.toHaveBeenCalled();
  7490. await app.submit("/rewind");
  7491. await vi.waitFor(() =>
  7492. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7493. kind: "feature",
  7494. id: "session-mutation:history",
  7495. }),
  7496. );
  7497. terminal.input?.("\r");
  7498. await vi.waitFor(() =>
  7499. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7500. kind: "feature",
  7501. id: "session-mutation:rewind-preview",
  7502. }),
  7503. );
  7504. terminal.input?.("\r");
  7505. await vi.waitFor(() =>
  7506. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7507. kind: "feature",
  7508. id: "session-mutation:scope",
  7509. }),
  7510. );
  7511. terminal.input?.("\r");
  7512. await vi.waitFor(() =>
  7513. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7514. kind: "feature",
  7515. id: "session-mutation:rewind-confirm",
  7516. }),
  7517. );
  7518. terminal.input?.("\r");
  7519. await vi.waitFor(() =>
  7520. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  7521. );
  7522. terminal.input?.("\u001b");
  7523. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7524. kind: "feature",
  7525. id: "session-mutation:rewind-confirm",
  7526. });
  7527. resolveRewind({ rewound: true });
  7528. await app.stop();
  7529. });
  7530. it("invalidates /rewind when the active session switches before mutation", async () => {
  7531. const terminal = new FakeTerminal();
  7532. const runtime = createRuntime();
  7533. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7534. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 0 },
  7535. ]);
  7536. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({ turns: [] });
  7537. const app = createTuiApp({
  7538. runtime,
  7539. terminal,
  7540. version: "0.1.0",
  7541. workspaceDir: "/workspace",
  7542. });
  7543. app.start();
  7544. await app.ready;
  7545. await app.submit("Seed rewind session");
  7546. await app.submit("/rewind");
  7547. await vi.waitFor(() =>
  7548. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7549. kind: "feature",
  7550. id: "session-mutation:history",
  7551. }),
  7552. );
  7553. const other = {
  7554. sessionId: "session-other",
  7555. title: "Other",
  7556. workspaceDir: "/workspace",
  7557. };
  7558. vi.mocked(runtime.getSession).mockResolvedValue(other);
  7559. await app.openSession(other.sessionId);
  7560. terminal.input?.("\r");
  7561. await new Promise((resolve) => setTimeout(resolve, 20));
  7562. expect(runtime.getSessionRewindPreview).not.toHaveBeenCalled();
  7563. expect(runtime.rewindSession).not.toHaveBeenCalled();
  7564. expect(app.controller.snapshot().session?.sessionId).toBe(other.sessionId);
  7565. await app.stop();
  7566. });
  7567. it("retries a failed file rewind with the same operation id", async () => {
  7568. const terminal = new FakeTerminal();
  7569. const runtime = createRuntime();
  7570. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7571. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7572. ]);
  7573. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7574. turns: [
  7575. {
  7576. turnId: "turn-1",
  7577. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7578. },
  7579. ],
  7580. });
  7581. vi.mocked(runtime.rewindSession)
  7582. .mockRejectedValueOnce(new Error("temporary conflict"))
  7583. .mockResolvedValueOnce({
  7584. rewound: true,
  7585. turnDiffRewind: { status: "rewound", revertedTurnIds: ["turn-1"] },
  7586. });
  7587. const app = createTuiApp({
  7588. runtime,
  7589. terminal,
  7590. version: "0.1.0",
  7591. workspaceDir: "/workspace",
  7592. });
  7593. app.start();
  7594. await app.ready;
  7595. await app.submit("Seed rewind session");
  7596. await app.submit("/rewind");
  7597. await vi.waitFor(() =>
  7598. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7599. kind: "feature",
  7600. id: "session-mutation:history",
  7601. }),
  7602. );
  7603. terminal.input?.("\r");
  7604. await vi.waitFor(() =>
  7605. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7606. kind: "feature",
  7607. id: "session-mutation:rewind-preview",
  7608. }),
  7609. );
  7610. terminal.input?.("\r");
  7611. await vi.waitFor(() =>
  7612. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7613. kind: "feature",
  7614. id: "session-mutation:scope",
  7615. }),
  7616. );
  7617. terminal.input?.("\u001b[B");
  7618. terminal.input?.("\r");
  7619. await vi.waitFor(() =>
  7620. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7621. kind: "feature",
  7622. id: "session-mutation:rewind-confirm",
  7623. }),
  7624. );
  7625. terminal.input?.("\r");
  7626. await vi.waitFor(() =>
  7627. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  7628. );
  7629. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7630. kind: "feature",
  7631. id: "session-mutation:rewind-confirm",
  7632. });
  7633. terminal.input?.("\r");
  7634. await vi.waitFor(() =>
  7635. expect(runtime.rewindSession).toHaveBeenCalledTimes(2),
  7636. );
  7637. const ids = vi
  7638. .mocked(runtime.rewindSession)
  7639. .mock.calls.map(([input]) => input.clientRequestId);
  7640. expect(ids[0]).toBe(ids[1]);
  7641. await app.stop();
  7642. });
  7643. it.each([
  7644. [
  7645. "terminal busy failure",
  7646. "CONVERSATION_MUTATION_BUSY",
  7647. "Stop the running response and try again.",
  7648. false,
  7649. ],
  7650. [
  7651. "pending display publication",
  7652. "REWIND_DISPLAY_COMMIT_FAILED",
  7653. "retry with the same operation id",
  7654. true,
  7655. ],
  7656. ] as const)(
  7657. "keeps a failed conversation rewind open and retries %s with the correct operation id",
  7658. async (_label, errorCode, expectedCopy, reuseOperationId) => {
  7659. const terminal = new FakeTerminal();
  7660. const runtime = createRuntime();
  7661. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7662. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 0 },
  7663. ]);
  7664. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7665. turns: [],
  7666. });
  7667. vi.mocked(runtime.rewindSession)
  7668. .mockRejectedValueOnce(
  7669. Object.assign(new Error("rewind failed"), { key: errorCode }),
  7670. )
  7671. .mockResolvedValueOnce({ rewound: true });
  7672. const app = createTuiApp({
  7673. runtime,
  7674. terminal,
  7675. version: "0.1.0",
  7676. workspaceDir: "/workspace",
  7677. });
  7678. app.start();
  7679. await app.ready;
  7680. await app.submit("Seed rewind session");
  7681. await app.submit("/rewind");
  7682. await vi.waitFor(() =>
  7683. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7684. kind: "feature",
  7685. id: "session-mutation:history",
  7686. }),
  7687. );
  7688. terminal.input?.("\r");
  7689. await vi.waitFor(() =>
  7690. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7691. kind: "feature",
  7692. id: "session-mutation:rewind-preview",
  7693. }),
  7694. );
  7695. terminal.input?.("\r");
  7696. await vi.waitFor(() =>
  7697. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7698. kind: "feature",
  7699. id: "session-mutation:scope",
  7700. }),
  7701. );
  7702. terminal.input?.("\r");
  7703. await vi.waitFor(() =>
  7704. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7705. kind: "feature",
  7706. id: "session-mutation:rewind-confirm",
  7707. }),
  7708. );
  7709. terminal.input?.("\r");
  7710. await vi.waitFor(() =>
  7711. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  7712. );
  7713. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7714. kind: "feature",
  7715. id: "session-mutation:rewind-confirm",
  7716. });
  7717. expect(renderTerminalViewport(app, terminal)).toContain(expectedCopy);
  7718. terminal.input?.("\r");
  7719. await vi.waitFor(() =>
  7720. expect(runtime.rewindSession).toHaveBeenCalledTimes(2),
  7721. );
  7722. const ids = vi
  7723. .mocked(runtime.rewindSession)
  7724. .mock.calls.map(([input]) => input.clientRequestId);
  7725. if (reuseOperationId) expect(ids[0]).toBe(ids[1]);
  7726. else expect(ids[0]).not.toBe(ids[1]);
  7727. await app.stop();
  7728. },
  7729. );
  7730. it.each([
  7731. [
  7732. "failed-after-rewind",
  7733. {
  7734. status: "failed-after-rewind",
  7735. revertedTurnIds: ["turn-1"],
  7736. errorCode: "conflict",
  7737. },
  7738. ],
  7739. ["empty-reverted-ids", { status: "rewound", revertedTurnIds: [] }],
  7740. [
  7741. "unknown-status",
  7742. { status: "future-runtime-status", revertedTurnIds: ["turn-1"] },
  7743. ],
  7744. ] as const)(
  7745. "does not report %s as a successful file rewind",
  7746. async (_label, turnDiffRewind) => {
  7747. const terminal = new FakeTerminal();
  7748. const runtime = createRuntime();
  7749. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7750. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7751. ]);
  7752. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7753. turns: [
  7754. {
  7755. turnId: "turn-1",
  7756. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7757. },
  7758. ],
  7759. });
  7760. vi.mocked(runtime.rewindSession).mockResolvedValue({
  7761. rewound: true,
  7762. turnDiffRewind,
  7763. });
  7764. const app = createTuiApp({
  7765. runtime,
  7766. terminal,
  7767. version: "0.1.0",
  7768. workspaceDir: "/workspace",
  7769. });
  7770. app.start();
  7771. await app.ready;
  7772. await app.submit("Seed rewind session");
  7773. await app.submit("/rewind");
  7774. await vi.waitFor(() =>
  7775. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7776. kind: "feature",
  7777. id: "session-mutation:history",
  7778. }),
  7779. );
  7780. terminal.input?.("\r");
  7781. await vi.waitFor(() =>
  7782. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7783. kind: "feature",
  7784. id: "session-mutation:rewind-preview",
  7785. }),
  7786. );
  7787. terminal.input?.("\r");
  7788. await vi.waitFor(() =>
  7789. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7790. kind: "feature",
  7791. id: "session-mutation:scope",
  7792. }),
  7793. );
  7794. terminal.input?.("\u001b[B");
  7795. terminal.input?.("\r");
  7796. await vi.waitFor(() =>
  7797. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7798. kind: "feature",
  7799. id: "session-mutation:rewind-confirm",
  7800. }),
  7801. );
  7802. terminal.input?.("\r");
  7803. await vi.waitFor(() =>
  7804. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  7805. );
  7806. await vi.waitFor(() =>
  7807. expect(app.transcript.snapshot().at(-1)?.content).toMatch(
  7808. /did not complete|No file changes/,
  7809. ),
  7810. );
  7811. expect(app.transcript.snapshot().at(-1)?.content).not.toContain(
  7812. "Files rewound; conversation history was kept.",
  7813. );
  7814. await app.stop();
  7815. },
  7816. );
  7817. it.each([
  7818. [
  7819. "MESSAGE_BOUNDARY_INVALID",
  7820. "This conversation point is no longer available.",
  7821. ],
  7822. [
  7823. "CONVERSATION_MUTATION_REQUEST_CONFLICT",
  7824. "This action was already submitted or became stale.",
  7825. ],
  7826. ["CONVERSATION_MUTATION_BUSY", "Stop the running response and try again."],
  7827. ] as const)(
  7828. "maps rewind Runtime error %s to stable copy",
  7829. async (code, expected) => {
  7830. const terminal = new FakeTerminal();
  7831. const runtime = createRuntime();
  7832. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7833. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7834. ]);
  7835. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7836. turns: [
  7837. {
  7838. turnId: "turn-1",
  7839. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7840. },
  7841. ],
  7842. });
  7843. vi.mocked(runtime.rewindSession).mockRejectedValue(
  7844. Object.assign(new Error("raw prompt token=secret"), { key: code }),
  7845. );
  7846. const app = createTuiApp({
  7847. runtime,
  7848. terminal,
  7849. version: "0.1.0",
  7850. workspaceDir: "/workspace",
  7851. });
  7852. app.start();
  7853. await app.ready;
  7854. await app.submit("Seed rewind session");
  7855. await app.submit("/rewind");
  7856. await vi.waitFor(() =>
  7857. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7858. kind: "feature",
  7859. id: "session-mutation:history",
  7860. }),
  7861. );
  7862. terminal.input?.("\r");
  7863. await vi.waitFor(() =>
  7864. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7865. kind: "feature",
  7866. id: "session-mutation:rewind-preview",
  7867. }),
  7868. );
  7869. terminal.input?.("\r");
  7870. await vi.waitFor(() =>
  7871. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7872. kind: "feature",
  7873. id: "session-mutation:scope",
  7874. }),
  7875. );
  7876. terminal.input?.("\u001b[B");
  7877. terminal.input?.("\r");
  7878. await vi.waitFor(() =>
  7879. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7880. kind: "feature",
  7881. id: "session-mutation:rewind-confirm",
  7882. }),
  7883. );
  7884. terminal.input?.("\r");
  7885. await vi.waitFor(() =>
  7886. expect(
  7887. app.transcript.snapshot().some((cell) => cell.content === expected),
  7888. ),
  7889. );
  7890. expect(
  7891. app.transcript
  7892. .snapshot()
  7893. .some((cell) => cell.content.includes("raw prompt token")),
  7894. ).toBe(false);
  7895. await app.stop();
  7896. },
  7897. );
  7898. it("reports refresh failure without unhandled rejection after conversation-and-files rewind", async () => {
  7899. const terminal = new FakeTerminal();
  7900. const runtime = createRuntime();
  7901. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7902. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7903. ]);
  7904. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7905. turns: [
  7906. {
  7907. turnId: "turn-1",
  7908. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7909. },
  7910. ],
  7911. });
  7912. vi.mocked(runtime.rewindSession).mockResolvedValue({
  7913. rewound: true,
  7914. turnDiffRewind: { status: "rewound", revertedTurnIds: ["turn-1"] },
  7915. });
  7916. vi.mocked(runtime.getMessages).mockRejectedValueOnce(
  7917. new Error("refresh unavailable"),
  7918. );
  7919. const app = createTuiApp({
  7920. runtime,
  7921. terminal,
  7922. version: "0.1.0",
  7923. workspaceDir: "/workspace",
  7924. });
  7925. app.start();
  7926. await app.ready;
  7927. await app.submit("Seed rewind session");
  7928. await app.submit("/rewind");
  7929. await vi.waitFor(() =>
  7930. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7931. kind: "feature",
  7932. id: "session-mutation:history",
  7933. }),
  7934. );
  7935. terminal.input?.("\r");
  7936. await vi.waitFor(() =>
  7937. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7938. kind: "feature",
  7939. id: "session-mutation:rewind-preview",
  7940. }),
  7941. );
  7942. terminal.input?.("\r");
  7943. await vi.waitFor(() =>
  7944. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7945. kind: "feature",
  7946. id: "session-mutation:scope",
  7947. }),
  7948. );
  7949. terminal.input?.("\u001b[B");
  7950. terminal.input?.("\r");
  7951. await vi.waitFor(() =>
  7952. expect(app.surfaceHost.getActiveSurface()).toEqual({
  7953. kind: "feature",
  7954. id: "session-mutation:rewind-confirm",
  7955. }),
  7956. );
  7957. terminal.input?.("\r");
  7958. await vi.waitFor(() =>
  7959. expect(
  7960. app.transcript
  7961. .snapshot()
  7962. .some((cell) => cell.content.includes("could not be refreshed")),
  7963. ),
  7964. );
  7965. await app.stop();
  7966. });
  7967. it("does not apply a pending rewind refresh result after switching sessions", async () => {
  7968. const terminal = new FakeTerminal();
  7969. const runtime = createRuntime();
  7970. vi.mocked(runtime.listSessionInputSummaries).mockResolvedValue([
  7971. { userMessageId: "msg-user-rewind", timestamp: 1, fileChangeCount: 1 },
  7972. ]);
  7973. vi.mocked(runtime.getSessionRewindPreview).mockResolvedValue({
  7974. turns: [
  7975. {
  7976. turnId: "turn-1",
  7977. files: [{ filePath: "a.ts", action: "modified", skipped: false }],
  7978. },
  7979. ],
  7980. });
  7981. vi.mocked(runtime.rewindSession).mockResolvedValue({
  7982. rewound: true,
  7983. turnDiffRewind: { status: "rewound", revertedTurnIds: ["turn-1"] },
  7984. });
  7985. let resolveRefresh!: (messages: readonly TuiMessage[]) => void;
  7986. const refreshPromise = new Promise<readonly TuiMessage[]>((resolve) => {
  7987. resolveRefresh = resolve;
  7988. });
  7989. const app = createTuiApp({
  7990. runtime,
  7991. terminal,
  7992. version: "0.1.0",
  7993. workspaceDir: "/workspace",
  7994. });
  7995. app.start();
  7996. await app.ready;
  7997. await app.submit("Seed rewind session");
  7998. vi.mocked(runtime.getMessages).mockImplementationOnce(() => refreshPromise);
  7999. await app.submit("/rewind");
  8000. await vi.waitFor(() =>
  8001. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8002. kind: "feature",
  8003. id: "session-mutation:history",
  8004. }),
  8005. );
  8006. terminal.input?.("\r");
  8007. await vi.waitFor(() =>
  8008. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8009. kind: "feature",
  8010. id: "session-mutation:rewind-preview",
  8011. }),
  8012. );
  8013. terminal.input?.("\r");
  8014. await vi.waitFor(() =>
  8015. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8016. kind: "feature",
  8017. id: "session-mutation:scope",
  8018. }),
  8019. );
  8020. terminal.input?.("\u001b[B");
  8021. terminal.input?.("\r");
  8022. await vi.waitFor(() =>
  8023. expect(app.surfaceHost.getActiveSurface()).toEqual({
  8024. kind: "feature",
  8025. id: "session-mutation:rewind-confirm",
  8026. }),
  8027. );
  8028. terminal.input?.("\r");
  8029. await vi.waitFor(() =>
  8030. expect(runtime.rewindSession).toHaveBeenCalledTimes(1),
  8031. );
  8032. const other = {
  8033. sessionId: "session-other",
  8034. title: "Other",
  8035. workspaceDir: "/workspace",
  8036. };
  8037. vi.mocked(runtime.getSession).mockResolvedValue(other);
  8038. vi.mocked(runtime.getMessages).mockResolvedValue([]);
  8039. const open = app.openSession(other.sessionId);
  8040. resolveRefresh([
  8041. {
  8042. id: "stale-message",
  8043. role: "assistant",
  8044. content: "stale",
  8045. timestamp: 3,
  8046. },
  8047. ]);
  8048. await open;
  8049. expect(app.controller.snapshot().session?.sessionId).toBe(other.sessionId);
  8050. expect(
  8051. app.transcript
  8052. .snapshot()
  8053. .some((cell) => cell.content.includes("Files rewound")),
  8054. ).toBe(false);
  8055. await app.stop();
  8056. });
  8057. it("redirects a hidden task child to its parent before rendering", async () => {
  8058. const runtime = createRuntime();
  8059. const parent = {
  8060. sessionId: "session-parent",
  8061. title: "CLI integration",
  8062. workspaceDir: "/workspace",
  8063. };
  8064. const child = {
  8065. sessionId: "session-child",
  8066. parentSessionId: parent.sessionId,
  8067. title: "Review recent CLI changes",
  8068. workspaceDir: "/workspace",
  8069. sessionType: "branch",
  8070. sessionKind: "task",
  8071. visibility: "hidden",
  8072. purpose: "local-task:turn-1:tool-1",
  8073. agentName: "verifier",
  8074. };
  8075. vi.mocked(runtime.listSessions).mockResolvedValue([parent]);
  8076. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  8077. sessionId === child.sessionId ? child : parent,
  8078. );
  8079. const app = createTuiApp({
  8080. runtime,
  8081. terminal: new FakeTerminal(),
  8082. version: "0.1.0",
  8083. workspaceDir: "/workspace",
  8084. });
  8085. await app.ready;
  8086. await app.openSession(child.sessionId);
  8087. expect(runtime.getSession).toHaveBeenLastCalledWith(parent.sessionId);
  8088. expect(app.controller.snapshot().session?.sessionId).toBe(parent.sessionId);
  8089. expect(app.tui.render(140).join("\n")).not.toContain("Sub: verifier");
  8090. expect(app.transcript.snapshot().at(-1)?.content).toBe(
  8091. "Sub-agent Sessions are internal. Opened the parent Session instead.",
  8092. );
  8093. await app.stop();
  8094. });
  8095. it("shows compact Agent Team status without exposing child details or commands", async () => {
  8096. const terminal = new FakeTerminal();
  8097. terminal.rows = 24;
  8098. const runtime = createRuntime();
  8099. const parent = {
  8100. sessionId: "session-parent",
  8101. title: "Agent Team parent",
  8102. workspaceDir: "/workspace",
  8103. };
  8104. const child = {
  8105. sessionId: "session-child",
  8106. parentSessionId: parent.sessionId,
  8107. title: "Verify the TUI",
  8108. workspaceDir: "/workspace",
  8109. sessionType: "branch" as const,
  8110. sessionKind: "task",
  8111. visibility: "hidden" as const,
  8112. purpose: "local-task:turn-1:tool-1",
  8113. agentName: "verifier",
  8114. status: "finished",
  8115. };
  8116. vi.mocked(runtime.listSessions).mockResolvedValue([parent]);
  8117. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  8118. sessionId === child.sessionId ? child : parent,
  8119. );
  8120. vi.mocked(runtime.getDelegationSnapshot).mockResolvedValue({
  8121. schemaVersion: 1,
  8122. rootSessionId: parent.sessionId,
  8123. members: [
  8124. {
  8125. sessionId: child.sessionId,
  8126. parentSessionId: parent.sessionId,
  8127. agentName: child.agentName,
  8128. task: child.title,
  8129. status: "running",
  8130. createdAtMs: 100,
  8131. updatedAtMs: 200,
  8132. },
  8133. ],
  8134. });
  8135. vi.mocked(runtime.getMessages).mockImplementation(async (sessionId) =>
  8136. sessionId === child.sessionId
  8137. ? [
  8138. {
  8139. id: "child-answer",
  8140. turnId: "turn-child",
  8141. role: "assistant",
  8142. content: "Child verification result",
  8143. timestamp: 200,
  8144. },
  8145. ]
  8146. : [],
  8147. );
  8148. vi.mocked(runtime.getActiveRun).mockImplementation(async (sessionId) => ({
  8149. schemaVersion: 1,
  8150. sessionId,
  8151. state: sessionId === child.sessionId ? "running" : "idle",
  8152. ...(sessionId === child.sessionId ? { turnId: "turn-child" } : {}),
  8153. actions: { steer: false },
  8154. }));
  8155. const app = createTuiApp({
  8156. runtime,
  8157. terminal,
  8158. version: "0.1.0",
  8159. workspaceDir: "/workspace",
  8160. });
  8161. await app.ready;
  8162. await app.openSession(parent.sessionId);
  8163. app.start();
  8164. const summary = app.tui.render(100).join("\n");
  8165. expect(summary).toContain("Tasks · 1 agent active · /tasks details");
  8166. expect(summary).not.toContain("verifier");
  8167. expect(summary).not.toContain("/agents");
  8168. expect(
  8169. app.transcript.snapshot().some((cell) => cell.kind === "agent-team"),
  8170. ).toBe(false);
  8171. await app.submit("/agents");
  8172. await app.submit("/team");
  8173. expect(app.controller.snapshot().session?.sessionId).toBe(parent.sessionId);
  8174. expect(app.tui.hasOverlay()).toBe(false);
  8175. expect(app.interaction.isActive()).toBe(false);
  8176. expect(app.tui.render(100).join("\n")).not.toContain(
  8177. "Child verification result",
  8178. );
  8179. expect(
  8180. vi
  8181. .mocked(runtime.sendMessage)
  8182. .mock.calls.map(([request]) => request.content),
  8183. ).toEqual(["/agents", "/team"]);
  8184. await app.stop();
  8185. });
  8186. it("allocates enough standard-terminal space for ten session choices", async () => {
  8187. const terminal = new FakeTerminal();
  8188. terminal.rows = 24;
  8189. const runtime = createRuntime();
  8190. vi.mocked(runtime.listSessionPage).mockResolvedValue({
  8191. sessions: Array.from({ length: 12 }, (_, index) => ({
  8192. sessionId: `session-${String(index + 1).padStart(2, "0")}`,
  8193. title: `Session ${String(index + 1).padStart(2, "0")}`,
  8194. workspaceDir: "/workspace",
  8195. updatedAt: 12 - index,
  8196. })),
  8197. hasMore: false,
  8198. });
  8199. const app = createTuiApp({
  8200. runtime,
  8201. terminal,
  8202. version: "0.1.0",
  8203. workspaceDir: "/workspace",
  8204. });
  8205. await app.submit("/sessions");
  8206. const lines = app.interaction.current()?.render(80) ?? [];
  8207. const rendered = lines.join("\n");
  8208. expect(lines.length).toBeLessThanOrEqual(terminal.rows);
  8209. expect(rendered).toContain("Session 10");
  8210. expect(rendered).not.toContain("Session 11");
  8211. });
  8212. it("switches, restores, and resumes archived Desktop sessions from the session manager", async () => {
  8213. const terminal = new FakeTerminal();
  8214. const runtime = createRuntime();
  8215. let archived = true;
  8216. const activeSession = {
  8217. sessionId: "session-active",
  8218. title: "Active session",
  8219. workspaceDir: "/workspace",
  8220. updatedAt: 200,
  8221. };
  8222. const archivedSession = {
  8223. sessionId: "session-archived",
  8224. title: "Archived session",
  8225. workspaceDir: "/workspace",
  8226. updatedAt: 100,
  8227. archived: true,
  8228. };
  8229. vi.mocked(runtime.listSessions).mockResolvedValue([activeSession]);
  8230. vi.mocked(runtime.listSessionPage).mockResolvedValue({
  8231. sessions: [activeSession, archivedSession],
  8232. hasMore: false,
  8233. });
  8234. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) => ({
  8235. ...(sessionId === archivedSession.sessionId
  8236. ? archivedSession
  8237. : activeSession),
  8238. archived: sessionId === archivedSession.sessionId ? archived : false,
  8239. }));
  8240. vi.mocked(runtime.archiveSession).mockImplementation(
  8241. async (_sessionId, value) => {
  8242. archived = value;
  8243. },
  8244. );
  8245. const app = createTuiApp({
  8246. runtime,
  8247. terminal,
  8248. version: "0.1.0",
  8249. workspaceDir: "/workspace",
  8250. });
  8251. app.start();
  8252. await app.ready;
  8253. await app.submit("/sessions");
  8254. expect(runtime.listSessionPage).toHaveBeenCalledWith({
  8255. allAgents: true,
  8256. workspaceDir: "/workspace",
  8257. limit: 50,
  8258. includeArchived: true,
  8259. includeHidden: true,
  8260. });
  8261. expect(app.tui.hasOverlay()).toBe(false);
  8262. expect(app.interaction.isActive()).toBe(true);
  8263. terminal.input?.("\t");
  8264. terminal.input?.("\r");
  8265. await vi.waitFor(() =>
  8266. expect(runtime.archiveSession).toHaveBeenCalledWith(
  8267. "session-archived",
  8268. false,
  8269. ),
  8270. );
  8271. await vi.waitFor(() =>
  8272. expect(runtime.getMessages).toHaveBeenCalledWith("session-archived"),
  8273. );
  8274. expect(app.getSurface()).toBe("conversation");
  8275. expect(app.controller.snapshot().session?.sessionId).toBe(
  8276. "session-archived",
  8277. );
  8278. expect(app.tui.hasOverlay()).toBe(false);
  8279. await app.stop();
  8280. });
  8281. it("uses the resume alias to search every Desktop session page", async () => {
  8282. const terminal = new FakeTerminal();
  8283. const runtime = createRuntime();
  8284. vi.mocked(runtime.listSessionPage)
  8285. .mockResolvedValueOnce({
  8286. sessions: [
  8287. {
  8288. sessionId: "session-page-1",
  8289. title: "First page",
  8290. workspaceDir: "/workspace",
  8291. updatedAt: 200,
  8292. },
  8293. ],
  8294. hasMore: true,
  8295. nextCursor: "session-page-1",
  8296. })
  8297. .mockResolvedValueOnce({
  8298. sessions: [
  8299. {
  8300. sessionId: "session-page-2",
  8301. title: "Second page",
  8302. workspaceDir: "/workspace",
  8303. updatedAt: 100,
  8304. },
  8305. ],
  8306. hasMore: false,
  8307. });
  8308. const app = createTuiApp({
  8309. runtime,
  8310. terminal,
  8311. version: "0.1.0",
  8312. workspaceDir: "/workspace",
  8313. });
  8314. app.start();
  8315. await app.ready;
  8316. await app.submit("/resume Second page");
  8317. await vi.waitFor(() =>
  8318. expect(runtime.listSessionPage).toHaveBeenNthCalledWith(2, {
  8319. allAgents: true,
  8320. workspaceDir: "/workspace",
  8321. limit: 50,
  8322. cursor: "session-page-1",
  8323. includeArchived: true,
  8324. includeHidden: true,
  8325. }),
  8326. );
  8327. expect(app.tui.hasOverlay()).toBe(false);
  8328. expect(app.interaction.isActive()).toBe(true);
  8329. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8330. "Second page",
  8331. );
  8332. await app.stop();
  8333. });
  8334. it("queries the current workspace first and reloads the global catalog on Ctrl+A", async () => {
  8335. const terminal = new FakeTerminal();
  8336. const runtime = createRuntime();
  8337. vi.mocked(runtime.listSessionPage).mockImplementation(
  8338. async (input = {}) => {
  8339. if (input.cursor === "all-page-2") {
  8340. return {
  8341. sessions: [
  8342. {
  8343. sessionId: "session-other-older",
  8344. title: "Older session elsewhere",
  8345. workspaceDir: "/other-workspace",
  8346. updatedAt: 50,
  8347. },
  8348. ],
  8349. hasMore: false,
  8350. };
  8351. }
  8352. return input.workspaceDir
  8353. ? {
  8354. sessions: [
  8355. {
  8356. sessionId: "session-workspace-old",
  8357. title: "Older workspace session",
  8358. workspaceDir: "/workspace",
  8359. updatedAt: 100,
  8360. },
  8361. ],
  8362. hasMore: false,
  8363. }
  8364. : {
  8365. sessions: [
  8366. {
  8367. sessionId: "session-other-new",
  8368. title: "Newer session elsewhere",
  8369. workspaceDir: "/other-workspace",
  8370. updatedAt: 200,
  8371. },
  8372. {
  8373. sessionId: "session-workspace-old",
  8374. title: "Older workspace session",
  8375. workspaceDir: "/workspace",
  8376. updatedAt: 100,
  8377. },
  8378. ],
  8379. hasMore: true,
  8380. nextCursor: "all-page-2",
  8381. };
  8382. },
  8383. );
  8384. const app = createTuiApp({
  8385. runtime,
  8386. terminal,
  8387. version: "0.1.0",
  8388. workspaceDir: "/workspace",
  8389. });
  8390. app.start();
  8391. await app.ready;
  8392. await app.submit("/sessions");
  8393. expect(runtime.listSessionPage).toHaveBeenNthCalledWith(1, {
  8394. allAgents: true,
  8395. workspaceDir: "/workspace",
  8396. limit: 50,
  8397. includeArchived: true,
  8398. includeHidden: true,
  8399. });
  8400. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8401. "Older workspace session",
  8402. );
  8403. terminal.input?.("\x01");
  8404. await vi.waitFor(() =>
  8405. expect(runtime.listSessionPage).toHaveBeenNthCalledWith(2, {
  8406. allAgents: true,
  8407. limit: 50,
  8408. includeArchived: true,
  8409. includeHidden: true,
  8410. }),
  8411. );
  8412. await vi.waitFor(() =>
  8413. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8414. "Newer session elsewhere",
  8415. ),
  8416. );
  8417. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8418. "All sessions",
  8419. );
  8420. terminal.input?.("\x0c");
  8421. await vi.waitFor(() =>
  8422. expect(runtime.listSessionPage).toHaveBeenNthCalledWith(3, {
  8423. allAgents: true,
  8424. limit: 50,
  8425. cursor: "all-page-2",
  8426. includeArchived: true,
  8427. includeHidden: true,
  8428. }),
  8429. );
  8430. await vi.waitFor(() =>
  8431. expect(app.interaction.current()?.render(100).join("\n")).toContain(
  8432. "Older session elsewhere",
  8433. ),
  8434. );
  8435. await app.stop();
  8436. });
  8437. it("shows account status and resolves pending permission and questionnaire decisions", async () => {
  8438. const terminal = new FakeTerminal();
  8439. const runtime = createRuntime();
  8440. vi.mocked(runtime.listSessions).mockResolvedValue([
  8441. {
  8442. sessionId: "session-existing",
  8443. title: "Existing session",
  8444. workspaceDir: "/workspace",
  8445. },
  8446. ]);
  8447. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  8448. {
  8449. requestId: "permission-1",
  8450. sessionId: "session-existing",
  8451. agentName: "mavis",
  8452. toolName: "bash",
  8453. reason: "Run tests",
  8454. allowAlwaysSupported: true,
  8455. },
  8456. ]);
  8457. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8458. id: "question-1",
  8459. title: "Choose",
  8460. steps: [
  8461. {
  8462. id: "step-1",
  8463. question: "Proceed?",
  8464. selectionMode: "single",
  8465. options: [
  8466. { id: "yes", label: "Yes" },
  8467. { id: "no", label: "No" },
  8468. ],
  8469. },
  8470. ],
  8471. });
  8472. const app = createTuiApp({
  8473. runtime,
  8474. terminal,
  8475. version: "0.1.0",
  8476. workspaceDir: "/workspace",
  8477. });
  8478. await app.ready;
  8479. await app.submit("/resume session-existing");
  8480. expect(app.transcript.snapshot()).toEqual(
  8481. expect.arrayContaining([
  8482. expect.objectContaining({ kind: "permission", status: "blocked" }),
  8483. expect.objectContaining({ kind: "question", status: "blocked" }),
  8484. ]),
  8485. );
  8486. expect(app.transcript.get("permission:permission-1")).toMatchObject({
  8487. title: "bash",
  8488. content: "Run tests",
  8489. });
  8490. expect(
  8491. app.transcript.get("permission:permission-1")?.content,
  8492. ).not.toContain("decision panel");
  8493. expect(app.transcript.get("permission:permission-1")?.content).not.toMatch(
  8494. /\/(?:allow|always|deny)\b/u,
  8495. );
  8496. expect(app.transcript.get("question:question-1")?.content).toBe("");
  8497. await app.submit("/q1 1");
  8498. expect(runtime.replyQuestionnaire).not.toHaveBeenCalled();
  8499. expect(app.tui.hasOverlay()).toBe(false);
  8500. expect(app.interaction.isActive()).toBe(true);
  8501. expect(terminal.mouseTracking).toBe(false);
  8502. await app.submit("/allow");
  8503. await app.submit("/q1 1");
  8504. await app.submit("/status");
  8505. expect(runtime.replyPermission).toHaveBeenCalledWith(
  8506. "mavis",
  8507. "permission-1",
  8508. "allowOnce",
  8509. );
  8510. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  8511. "mavis",
  8512. "question-1",
  8513. [
  8514. {
  8515. stepId: "step-1",
  8516. selectedOptionIds: ["yes"],
  8517. selectedOther: false,
  8518. },
  8519. ],
  8520. );
  8521. expect(terminal.mouseTracking).toBe(false);
  8522. expect(app.transcript.get("question:question-1")).toMatchObject({
  8523. status: "resolved",
  8524. title: "Answers sent",
  8525. content: "Proceed? Yes",
  8526. });
  8527. expect(app.interaction.current()).toBeDefined();
  8528. expect(app.tui.render(80).join("\n")).toContain("MCode status");
  8529. expect(app.transcript.snapshot()).not.toEqual(
  8530. expect.arrayContaining([
  8531. expect.objectContaining({
  8532. kind: "inspection",
  8533. inspection: expect.objectContaining({
  8534. visualization: { kind: "status" },
  8535. }),
  8536. }),
  8537. ]),
  8538. );
  8539. });
  8540. it("does not let a stale permission response hide a newer decision surface", async () => {
  8541. const terminal = new FakeTerminal();
  8542. const runtime = createRuntime();
  8543. vi.mocked(runtime.listSessions).mockResolvedValue([
  8544. {
  8545. sessionId: "session-race",
  8546. title: "Decision race",
  8547. workspaceDir: "/workspace",
  8548. },
  8549. ]);
  8550. const firstPermission = {
  8551. requestId: "permission-first",
  8552. sessionId: "session-race",
  8553. agentName: "mavis",
  8554. toolName: "bash",
  8555. reason: "First request",
  8556. allowAlwaysSupported: true,
  8557. };
  8558. const secondPermission = {
  8559. requestId: "permission-second",
  8560. sessionId: "session-race",
  8561. agentName: "mavis",
  8562. toolName: "write_file",
  8563. reason: "Newer request",
  8564. allowAlwaysSupported: false,
  8565. };
  8566. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  8567. firstPermission,
  8568. ]);
  8569. let finishReply: ((value: boolean) => void) | undefined;
  8570. vi.mocked(runtime.replyPermission).mockImplementation(
  8571. async () =>
  8572. await new Promise<boolean>((resolve) => {
  8573. finishReply = resolve;
  8574. }),
  8575. );
  8576. let emitEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  8577. vi.mocked(runtime.watchEvents).mockImplementation(
  8578. async function* watchEvents(signal) {
  8579. const event = await new Promise<TuiRuntimeEvent | undefined>(
  8580. (resolve) => {
  8581. emitEvent = resolve;
  8582. signal.addEventListener("abort", () => resolve(undefined), {
  8583. once: true,
  8584. });
  8585. },
  8586. );
  8587. if (event) yield event;
  8588. await new Promise<void>((resolve) => {
  8589. signal.addEventListener("abort", resolve, { once: true });
  8590. });
  8591. },
  8592. );
  8593. const app = createTuiApp({
  8594. runtime,
  8595. terminal,
  8596. version: "0.1.0",
  8597. workspaceDir: "/workspace",
  8598. });
  8599. app.start();
  8600. await app.ready;
  8601. await app.submit("/resume session-race");
  8602. const resolving = app.submit("/allow");
  8603. await vi.waitFor(() => expect(runtime.replyPermission).toHaveBeenCalled());
  8604. await vi.waitFor(() => expect(emitEvent).toBeTypeOf("function"));
  8605. emitEvent?.(
  8606. runtimeEvent({
  8607. type: "permission.ask",
  8608. timestamp: Date.now(),
  8609. source: "test",
  8610. payload: secondPermission,
  8611. }),
  8612. );
  8613. await vi.waitFor(() =>
  8614. expect(app.tui.render(80).join("\n")).toContain("Newer request"),
  8615. );
  8616. finishReply?.(true);
  8617. await resolving;
  8618. const rendered = app.tui.render(80).join("\n");
  8619. expect(rendered).toContain("Write file");
  8620. expect(rendered).toContain("Newer request");
  8621. expect(runtime.replyPermission).toHaveBeenCalledTimes(1);
  8622. await app.stop();
  8623. });
  8624. it("closes a permission that another surface resolved before the reply arrived", async () => {
  8625. const terminal = new FakeTerminal();
  8626. const runtime = createRuntime();
  8627. const permission = {
  8628. requestId: "permission-stale",
  8629. sessionId: "session-permission-stale",
  8630. agentName: "mavis",
  8631. toolName: "bash",
  8632. reason: "Run tests",
  8633. allowAlwaysSupported: true,
  8634. };
  8635. vi.mocked(runtime.listSessions).mockResolvedValue([
  8636. {
  8637. sessionId: "session-permission-stale",
  8638. title: "Permission race",
  8639. workspaceDir: "/workspace",
  8640. },
  8641. ]);
  8642. vi.mocked(runtime.listPendingPermissions)
  8643. .mockResolvedValueOnce([permission])
  8644. .mockResolvedValue([]);
  8645. vi.mocked(runtime.replyPermission).mockResolvedValue(false);
  8646. const app = createTuiApp({
  8647. runtime,
  8648. terminal,
  8649. version: "0.1.0",
  8650. workspaceDir: "/workspace",
  8651. });
  8652. await app.ready;
  8653. await app.submit("/resume session-permission-stale");
  8654. await app.submit("/allow");
  8655. expect(app.transcript.get("permission:permission-stale")).toMatchObject({
  8656. status: "resolved",
  8657. detail: "Resolved on another surface.",
  8658. });
  8659. expect(app.interaction.isActive()).toBe(false);
  8660. });
  8661. it("keeps an option-only questionnaire pending after an invalid slash answer", async () => {
  8662. const terminal = new FakeTerminal();
  8663. const runtime = createRuntime();
  8664. vi.mocked(runtime.listSessions).mockResolvedValue([
  8665. {
  8666. sessionId: "session-questionnaire",
  8667. title: "Questionnaire session",
  8668. workspaceDir: "/workspace",
  8669. },
  8670. ]);
  8671. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8672. id: "question-options-only",
  8673. title: "Choose",
  8674. steps: [
  8675. {
  8676. id: "channel",
  8677. question: "Choose a release channel",
  8678. selectionMode: "single",
  8679. options: [
  8680. { id: "preview", label: "Preview" },
  8681. { id: "stable", label: "Stable" },
  8682. ],
  8683. allowOther: false,
  8684. },
  8685. ],
  8686. });
  8687. const app = createTuiApp({
  8688. runtime,
  8689. terminal,
  8690. version: "0.1.0",
  8691. workspaceDir: "/workspace",
  8692. });
  8693. await app.ready;
  8694. await app.submit("/resume session-questionnaire");
  8695. await app.submit("/q1 nightly");
  8696. expect(runtime.replyQuestionnaire).not.toHaveBeenCalled();
  8697. expect(app.transcript.get("question:question-options-only")).toMatchObject({
  8698. status: "blocked",
  8699. });
  8700. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  8701. kind: "warning",
  8702. content:
  8703. "/q1 accepts only listed options. Use an option number, ID, or label.",
  8704. });
  8705. await app.submit("/q1 1");
  8706. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  8707. "mavis",
  8708. "question-options-only",
  8709. [
  8710. {
  8711. stepId: "channel",
  8712. selectedOptionIds: ["preview"],
  8713. selectedOther: false,
  8714. },
  8715. ],
  8716. );
  8717. });
  8718. it("shows the first AskUser answer immediately while later questions remain pending", async () => {
  8719. const terminal = new FakeTerminal();
  8720. const runtime = createRuntime();
  8721. vi.mocked(runtime.listSessions).mockResolvedValue([
  8722. {
  8723. sessionId: "session-multi-question",
  8724. title: "Multi question",
  8725. workspaceDir: "/workspace",
  8726. },
  8727. ]);
  8728. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8729. id: "question-multi-step",
  8730. title: "Preferences",
  8731. steps: [
  8732. {
  8733. id: "animal",
  8734. question: "Favorite animal?",
  8735. selectionMode: "single",
  8736. options: [
  8737. { id: "cat", label: "Cat" },
  8738. { id: "dog", label: "Dog" },
  8739. ],
  8740. },
  8741. {
  8742. id: "color",
  8743. question: "Favorite color?",
  8744. selectionMode: "single",
  8745. options: [
  8746. { id: "blue", label: "Blue" },
  8747. { id: "green", label: "Green" },
  8748. ],
  8749. },
  8750. ],
  8751. });
  8752. const app = createTuiApp({
  8753. runtime,
  8754. terminal,
  8755. version: "0.1.0",
  8756. workspaceDir: "/workspace",
  8757. });
  8758. await app.ready;
  8759. app.start();
  8760. await app.submit("/resume session-multi-question");
  8761. const picker = app.interaction.current();
  8762. expect(picker).toBeDefined();
  8763. terminal.input?.("1");
  8764. expect(runtime.replyQuestionnaire).not.toHaveBeenCalled();
  8765. expect(app.interaction.current()).toBe(picker);
  8766. expect(app.transcript.get("question:question-multi-step")).toMatchObject({
  8767. status: "blocked",
  8768. content: "Favorite animal? Cat",
  8769. detail: "1 of 2 answered",
  8770. });
  8771. const rendered = app.tui.render(80).join("\n");
  8772. expect(rendered).toContain("Answers so far");
  8773. expect(rendered).toContain("Favorite animal? Cat");
  8774. expect(rendered).toContain("Favorite color?");
  8775. terminal.input?.("\u001B[B");
  8776. expect(app.tui.render(80).join("\n")).toContain("› 2 Green");
  8777. terminal.input?.("\r");
  8778. await vi.waitFor(() => {
  8779. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  8780. "mavis",
  8781. "question-multi-step",
  8782. [
  8783. {
  8784. stepId: "animal",
  8785. selectedOptionIds: ["cat"],
  8786. selectedOther: false,
  8787. },
  8788. {
  8789. stepId: "color",
  8790. selectedOptionIds: ["green"],
  8791. selectedOther: false,
  8792. },
  8793. ],
  8794. );
  8795. });
  8796. await app.stop();
  8797. });
  8798. it("sends the selected answer immediately and refreshes the Agent continuation", async () => {
  8799. const terminal = new FakeTerminal();
  8800. const runtime = createRuntime();
  8801. vi.mocked(runtime.listSessions).mockResolvedValue([
  8802. {
  8803. sessionId: "session-review",
  8804. title: "Questionnaire review",
  8805. workspaceDir: "/workspace",
  8806. },
  8807. ]);
  8808. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8809. id: "question-review",
  8810. title: "Release setup",
  8811. steps: [
  8812. {
  8813. id: "channel",
  8814. question: "Choose a channel",
  8815. selectionMode: "single",
  8816. options: [
  8817. { id: "preview", label: "Preview" },
  8818. { id: "stable", label: "Stable" },
  8819. ],
  8820. },
  8821. ],
  8822. });
  8823. const previousMessages = [
  8824. {
  8825. id: "previous-question-answer",
  8826. role: "user" as const,
  8827. content: [
  8828. "<questionnaire-response>",
  8829. " <requestId>question-previous</requestId>",
  8830. " <answers />",
  8831. "</questionnaire-response>",
  8832. "",
  8833. "Q: Choose a channel",
  8834. "A: Preview",
  8835. ].join("\n"),
  8836. },
  8837. ];
  8838. vi.mocked(runtime.getMessages).mockResolvedValue(previousMessages);
  8839. const app = createTuiApp({
  8840. runtime,
  8841. terminal,
  8842. version: "0.1.0",
  8843. workspaceDir: "/workspace",
  8844. });
  8845. let releaseReply: ((result: boolean) => void) | undefined;
  8846. let releaseContinuation: (() => void) | undefined;
  8847. vi.mocked(runtime.replyQuestionnaire).mockImplementation(
  8848. async () =>
  8849. await new Promise<boolean>((resolve) => {
  8850. releaseReply = resolve;
  8851. }),
  8852. );
  8853. vi.mocked(runtime.watchEvents).mockImplementation(
  8854. async function* watchEvents(signal) {
  8855. await new Promise<void>((resolve) => {
  8856. releaseContinuation = resolve;
  8857. signal.addEventListener("abort", resolve, { once: true });
  8858. });
  8859. if (signal.aborted) return;
  8860. yield runtimeEvent({
  8861. type: "session.start",
  8862. timestamp: Date.now(),
  8863. source: "runtime",
  8864. payload: {
  8865. sessionId: "session-review",
  8866. turnId: "turn-questionnaire-continuation",
  8867. },
  8868. });
  8869. yield runtimeEvent({
  8870. type: "session.finish",
  8871. timestamp: Date.now(),
  8872. source: "runtime",
  8873. payload: {
  8874. sessionId: "session-review",
  8875. turnId: "turn-questionnaire-continuation",
  8876. },
  8877. });
  8878. },
  8879. );
  8880. app.start();
  8881. await app.ready;
  8882. await app.submit("/resume session-review");
  8883. expect(app.tui.hasOverlay()).toBe(false);
  8884. expect(app.interaction.isActive()).toBe(true);
  8885. terminal.input?.("2");
  8886. await vi.waitFor(() =>
  8887. expect(runtime.replyQuestionnaire).toHaveBeenCalledWith(
  8888. "mavis",
  8889. "question-review",
  8890. [
  8891. {
  8892. stepId: "channel",
  8893. selectedOptionIds: ["stable"],
  8894. selectedOther: false,
  8895. },
  8896. ],
  8897. ),
  8898. );
  8899. expect(app.tui.hasOverlay()).toBe(false);
  8900. expect(app.transcript.get("question:question-review")).toMatchObject({
  8901. status: "pending",
  8902. detail: "Sending your answer…",
  8903. });
  8904. releaseReply?.(true);
  8905. await vi.waitFor(() =>
  8906. expect(app.transcript.get("question:question-review")).toMatchObject({
  8907. status: "resolved",
  8908. detail: "Answer sent · MCode is continuing…",
  8909. }),
  8910. );
  8911. vi.mocked(runtime.getMessages).mockResolvedValue([
  8912. ...previousMessages,
  8913. {
  8914. id: "assistant-after-question",
  8915. role: "assistant",
  8916. content: "Agent continued after your answer.",
  8917. },
  8918. ]);
  8919. releaseContinuation?.();
  8920. await vi.waitFor(() =>
  8921. expect(
  8922. app.transcript
  8923. .snapshot()
  8924. .map((cell) => cell.content)
  8925. .join("\n"),
  8926. ).toContain("Agent continued after your answer."),
  8927. );
  8928. expect(app.transcript.get("question:question-review")).toMatchObject({
  8929. kind: "question",
  8930. status: "resolved",
  8931. title: "Answers sent",
  8932. content: "Choose a channel Stable",
  8933. detail: undefined,
  8934. });
  8935. expect(
  8936. app.transcript
  8937. .snapshot()
  8938. .filter((cell) => cell.kind === "question")
  8939. .map((cell) => cell.content),
  8940. ).toEqual(["Choose a channel Preview", "Choose a channel Stable"]);
  8941. expect(app.tui.render(80).join("\n")).not.toContain("Thinking · Message");
  8942. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
  8943. await app.stop();
  8944. });
  8945. it("redraws after a delayed questionnaire reply resolves", async () => {
  8946. const terminal = new FakeTerminal();
  8947. const runtime = createRuntime();
  8948. vi.mocked(runtime.listSessions).mockResolvedValue([
  8949. {
  8950. sessionId: "session-delayed-reply",
  8951. title: "Delayed questionnaire reply",
  8952. workspaceDir: "/workspace",
  8953. },
  8954. ]);
  8955. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  8956. id: "question-delayed-reply",
  8957. steps: [
  8958. {
  8959. id: "channel",
  8960. question: "Choose a channel",
  8961. selectionMode: "single",
  8962. options: [{ id: "preview", label: "Preview" }],
  8963. },
  8964. ],
  8965. });
  8966. let finishReply: ((result: boolean) => void) | undefined;
  8967. vi.mocked(runtime.replyQuestionnaire).mockImplementation(
  8968. async () =>
  8969. await new Promise<boolean>((resolve) => {
  8970. finishReply = resolve;
  8971. }),
  8972. );
  8973. const app = createTuiApp({
  8974. runtime,
  8975. terminal,
  8976. version: "0.1.0",
  8977. workspaceDir: "/workspace",
  8978. });
  8979. app.start();
  8980. await app.ready;
  8981. await app.submit("/resume session-delayed-reply");
  8982. terminal.input?.("1");
  8983. await vi.waitFor(() =>
  8984. expect(runtime.replyQuestionnaire).toHaveBeenCalledTimes(1),
  8985. );
  8986. expect(app.tui.hasOverlay()).toBe(false);
  8987. const writesBeforeResolution = terminal.writes.length;
  8988. finishReply?.(true);
  8989. await vi.waitFor(() =>
  8990. expect(
  8991. app.transcript.get("question:question-delayed-reply"),
  8992. ).toMatchObject({
  8993. status: "resolved",
  8994. detail: "Answer sent · MCode is continuing…",
  8995. }),
  8996. );
  8997. await vi.waitFor(() =>
  8998. expect(terminal.writes.length).toBeGreaterThan(writesBeforeResolution),
  8999. );
  9000. await app.stop();
  9001. });
  9002. it("keeps the questionnaire interactive when the Runtime cannot start its continuation", async () => {
  9003. const terminal = new FakeTerminal();
  9004. const runtime = createRuntime();
  9005. vi.mocked(runtime.listSessions).mockResolvedValue([
  9006. {
  9007. sessionId: "session-retry-questionnaire",
  9008. title: "Retry questionnaire",
  9009. workspaceDir: "/workspace",
  9010. },
  9011. ]);
  9012. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9013. id: "question-retry",
  9014. title: "Choose a channel",
  9015. steps: [
  9016. {
  9017. id: "channel",
  9018. question: "Choose a channel",
  9019. selectionMode: "single",
  9020. options: [{ id: "preview", label: "Preview" }],
  9021. },
  9022. ],
  9023. });
  9024. vi.mocked(runtime.replyQuestionnaire).mockRejectedValue(
  9025. new Error(
  9026. "Questionnaire answer was saved, but the continuation could not start.",
  9027. ),
  9028. );
  9029. const app = createTuiApp({
  9030. runtime,
  9031. terminal,
  9032. version: "0.1.0",
  9033. workspaceDir: "/workspace",
  9034. });
  9035. app.start();
  9036. app.start();
  9037. await app.ready;
  9038. await app.submit("/resume session-retry-questionnaire");
  9039. terminal.input?.("1");
  9040. await vi.waitFor(() =>
  9041. expect(app.transcript.get("question:question-retry")).toMatchObject({
  9042. status: "blocked",
  9043. title: "Choose a channel",
  9044. detail: "Answer could not be sent · retry",
  9045. }),
  9046. );
  9047. expect(app.interaction.isActive()).toBe(true);
  9048. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  9049. kind: "error",
  9050. content:
  9051. "Couldn't send your answers: Questionnaire answer was saved, but the continuation could not start. Retry. The question remains open.",
  9052. });
  9053. await app.stop();
  9054. });
  9055. it("redraws after a delayed questionnaire dismissal resolves", async () => {
  9056. const terminal = new FakeTerminal();
  9057. const runtime = createRuntime();
  9058. vi.mocked(runtime.listSessions).mockResolvedValue([
  9059. {
  9060. sessionId: "session-delayed-dismiss",
  9061. title: "Delayed questionnaire dismissal",
  9062. workspaceDir: "/workspace",
  9063. },
  9064. ]);
  9065. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9066. id: "question-delayed-dismiss",
  9067. steps: [{ id: "confirmation", question: "Continue?" }],
  9068. });
  9069. let finishDismiss: ((result: boolean) => void) | undefined;
  9070. vi.mocked(runtime.dismissQuestionnaire).mockImplementation(
  9071. async () =>
  9072. await new Promise<boolean>((resolve) => {
  9073. finishDismiss = resolve;
  9074. }),
  9075. );
  9076. const app = createTuiApp({
  9077. runtime,
  9078. terminal,
  9079. version: "0.1.0",
  9080. workspaceDir: "/workspace",
  9081. });
  9082. app.start();
  9083. await app.ready;
  9084. await app.submit("/resume session-delayed-dismiss");
  9085. const dismissing = app.submit("/ask-cancel");
  9086. await vi.waitFor(() =>
  9087. expect(runtime.dismissQuestionnaire).toHaveBeenCalledTimes(1),
  9088. );
  9089. const writesBeforeResolution = terminal.writes.length;
  9090. finishDismiss?.(true);
  9091. await dismissing;
  9092. expect(
  9093. app.transcript.get("question:question-delayed-dismiss"),
  9094. ).toMatchObject({
  9095. status: "resolved",
  9096. title: "Question dismissed",
  9097. content: "",
  9098. detail: undefined,
  9099. });
  9100. await vi.waitFor(() =>
  9101. expect(terminal.writes.length).toBeGreaterThan(writesBeforeResolution),
  9102. );
  9103. await app.stop();
  9104. });
  9105. it.each([
  9106. { keyName: "Escape", input: "\x1b" },
  9107. { keyName: "Ctrl-C", input: "\x03" },
  9108. ])(
  9109. "keeps AskUser focused while $keyName dismisses the pending questionnaire",
  9110. async ({ input }) => {
  9111. const terminal = new FakeTerminal();
  9112. const runtime = createRuntime();
  9113. vi.mocked(runtime.listSessions).mockResolvedValue([
  9114. {
  9115. sessionId: "session-escape-dismiss",
  9116. title: "Escape questionnaire dismissal",
  9117. workspaceDir: "/workspace",
  9118. },
  9119. ]);
  9120. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9121. id: "question-escape-dismiss",
  9122. steps: [
  9123. {
  9124. id: "channel",
  9125. question: "Choose a channel",
  9126. selectionMode: "single",
  9127. options: [{ id: "preview", label: "Preview" }],
  9128. },
  9129. ],
  9130. });
  9131. let finishDismiss: ((result: boolean) => void) | undefined;
  9132. vi.mocked(runtime.dismissQuestionnaire).mockImplementation(
  9133. async () =>
  9134. await new Promise<boolean>((resolve) => {
  9135. finishDismiss = resolve;
  9136. }),
  9137. );
  9138. const app = createTuiApp({
  9139. runtime,
  9140. terminal,
  9141. version: "0.1.0",
  9142. workspaceDir: "/workspace",
  9143. });
  9144. app.start();
  9145. await app.ready;
  9146. await app.submit("/resume session-escape-dismiss");
  9147. terminal.input?.(input);
  9148. if (input === "\x1b") {
  9149. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9150. "Cancel this question?",
  9151. );
  9152. terminal.input?.("\r");
  9153. }
  9154. await vi.waitFor(() =>
  9155. expect(runtime.dismissQuestionnaire).toHaveBeenCalledWith(
  9156. "mavis",
  9157. "question-escape-dismiss",
  9158. ),
  9159. );
  9160. expect(app.interaction.isActive()).toBe(true);
  9161. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9162. "Closing question",
  9163. );
  9164. expect(
  9165. app.state.snapshot().sessions.get("session-escape-dismiss")?.attention
  9166. .question,
  9167. ).toBe(true);
  9168. finishDismiss?.(true);
  9169. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  9170. expect(
  9171. app.transcript.get("question:question-escape-dismiss"),
  9172. ).toMatchObject({
  9173. status: "resolved",
  9174. title: "Question dismissed",
  9175. });
  9176. expect(
  9177. app.state.snapshot().sessions.get("session-escape-dismiss")?.attention
  9178. .question,
  9179. ).toBe(false);
  9180. expect(app.tui.render(80).join("\n")).not.toContain("Reply required");
  9181. await app.stop();
  9182. },
  9183. );
  9184. it("denies a pending permission explicitly and releases the blocked interaction", async () => {
  9185. const terminal = new FakeTerminal();
  9186. const runtime = createRuntime();
  9187. vi.mocked(runtime.listSessions).mockResolvedValue([
  9188. {
  9189. sessionId: "session-pending",
  9190. title: "Pending permission",
  9191. workspaceDir: "/workspace",
  9192. },
  9193. ]);
  9194. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  9195. {
  9196. requestId: "permission-pending",
  9197. sessionId: "session-pending",
  9198. agentName: "mavis",
  9199. toolName: "bash",
  9200. toolInput: "pnpm test",
  9201. ruleContents: ["Bash(pnpm test:*)"],
  9202. allowAlwaysSupported: true,
  9203. },
  9204. ]);
  9205. const app = createTuiApp({
  9206. runtime,
  9207. terminal,
  9208. version: "0.1.0",
  9209. workspaceDir: "/workspace",
  9210. });
  9211. app.start();
  9212. await app.ready;
  9213. await app.submit("/resume session-pending");
  9214. expect(app.tui.hasOverlay()).toBe(false);
  9215. expect(app.interaction.isActive()).toBe(true);
  9216. terminal.input?.("3");
  9217. terminal.input?.("\r");
  9218. await vi.waitFor(() =>
  9219. expect(runtime.replyPermission).toHaveBeenCalledWith(
  9220. "mavis",
  9221. "permission-pending",
  9222. "deny",
  9223. ),
  9224. );
  9225. expect(app.tui.hasOverlay()).toBe(false);
  9226. expect(app.interaction.isActive()).toBe(false);
  9227. expect(app.transcript.get("permission:permission-pending")).toMatchObject({
  9228. status: "resolved",
  9229. detail: "Denied · bash",
  9230. });
  9231. expect(app.tui.render(80).join("\n")).not.toContain("Approval required");
  9232. await app.stop();
  9233. });
  9234. it("resolves a regular inline permission without clearing the terminal viewport", async () => {
  9235. const terminal = new FakeTerminal();
  9236. terminal.rows = 8;
  9237. const runtime = createRuntime();
  9238. vi.mocked(runtime.listSessions).mockResolvedValue([
  9239. {
  9240. sessionId: "session-permission-render",
  9241. title: "Permission render",
  9242. workspaceDir: "/workspace",
  9243. },
  9244. ]);
  9245. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  9246. {
  9247. requestId: "permission-render",
  9248. sessionId: "session-permission-render",
  9249. agentName: "mavis",
  9250. toolName: "bash",
  9251. toolInput: "pnpm test",
  9252. reason: "Run focused tests",
  9253. allowAlwaysSupported: true,
  9254. },
  9255. ]);
  9256. const app = createTuiApp({
  9257. runtime,
  9258. terminal,
  9259. version: "0.2.6",
  9260. workspaceDir: "/workspace",
  9261. tuiMode: "regular",
  9262. });
  9263. app.start();
  9264. await app.ready;
  9265. await app.submit("/resume session-permission-render");
  9266. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(true));
  9267. app.tui.renderNow();
  9268. terminal.writes.length = 0;
  9269. terminal.input?.("\r");
  9270. await vi.waitFor(() => expect(app.interaction.isActive()).toBe(false));
  9271. await vi.waitFor(() => expect(terminal.writes.length).toBeGreaterThan(0));
  9272. expect(runtime.replyPermission).toHaveBeenCalledWith(
  9273. "mavis",
  9274. "permission-render",
  9275. "allowOnce",
  9276. );
  9277. expect(app.transcript.get("permission:permission-render")).toMatchObject({
  9278. status: "resolved",
  9279. detail: "Allowed for this conversation · bash",
  9280. });
  9281. expect(terminal.writes.join("")).not.toContain("\x1b[2J");
  9282. expect(terminal.writes.join("")).not.toContain("\x1b[3J");
  9283. await app.stop();
  9284. });
  9285. it("keeps a submission retryable when a pending decision blocks admission", async () => {
  9286. const terminal = new FakeTerminal();
  9287. const runtime = createRuntime();
  9288. vi.mocked(runtime.listSessions).mockResolvedValue([
  9289. {
  9290. sessionId: "session-draft-blocked",
  9291. title: "Pending decision",
  9292. workspaceDir: "/workspace",
  9293. },
  9294. ]);
  9295. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  9296. {
  9297. requestId: "permission-draft-blocked",
  9298. sessionId: "session-draft-blocked",
  9299. agentName: "mavis",
  9300. toolName: "bash",
  9301. allowAlwaysSupported: true,
  9302. },
  9303. ]);
  9304. const app = createTuiApp({
  9305. runtime,
  9306. terminal,
  9307. version: "0.1.0",
  9308. workspaceDir: "/workspace",
  9309. });
  9310. app.start();
  9311. await app.ready;
  9312. await app.submit("/resume session-draft-blocked");
  9313. app.editor.setText("Keep this draft for later");
  9314. app.editor.handleInput("\r");
  9315. await vi.waitFor(() => expect(app.editor.getText()).toBe(""));
  9316. expect(runtime.sendMessage).not.toHaveBeenCalled();
  9317. expect(app.tui.render(80).join("\n")).toContain("Approval required");
  9318. expect(app.tui.render(80).join("\n")).not.toContain("Message · Enter");
  9319. await app.stop();
  9320. });
  9321. it("keeps a pending questionnaire when Runtime rejects dismissal", async () => {
  9322. const terminal = new FakeTerminal();
  9323. const runtime = createRuntime();
  9324. vi.mocked(runtime.listSessions).mockResolvedValue([
  9325. {
  9326. sessionId: "session-existing",
  9327. title: "Existing session",
  9328. workspaceDir: "/workspace",
  9329. },
  9330. ]);
  9331. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9332. id: "question-rejected",
  9333. steps: [{ id: "step-1", question: "Proceed?" }],
  9334. });
  9335. vi.mocked(runtime.dismissQuestionnaire).mockResolvedValue(false);
  9336. const app = createTuiApp({
  9337. runtime,
  9338. terminal,
  9339. version: "0.1.0",
  9340. workspaceDir: "/workspace",
  9341. });
  9342. await app.ready;
  9343. await app.submit("/resume session-existing");
  9344. await app.submit("/ask-cancel");
  9345. expect(app.transcript.get("question:question-rejected")).toMatchObject({
  9346. status: "blocked",
  9347. });
  9348. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  9349. kind: "error",
  9350. content: "Couldn't dismiss this question. It remains open; retry.",
  9351. });
  9352. });
  9353. it("restores the questionnaire panel when an Escape dismissal request fails", async () => {
  9354. const runtime = createRuntime();
  9355. vi.mocked(runtime.listSessions).mockResolvedValue([
  9356. {
  9357. sessionId: "session-dismiss-retry",
  9358. title: "Dismiss retry",
  9359. workspaceDir: "/workspace",
  9360. },
  9361. ]);
  9362. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9363. id: "question-dismiss-retry",
  9364. steps: [
  9365. {
  9366. id: "step-1",
  9367. question: "Proceed?",
  9368. selectionMode: "single",
  9369. options: [{ id: "yes", label: "Yes" }],
  9370. },
  9371. ],
  9372. });
  9373. vi.mocked(runtime.dismissQuestionnaire).mockRejectedValue(
  9374. new Error("connection lost"),
  9375. );
  9376. const app = createTuiApp({
  9377. runtime,
  9378. terminal: new FakeTerminal(),
  9379. version: "0.1.0",
  9380. workspaceDir: "/workspace",
  9381. });
  9382. await app.ready;
  9383. await app.submit("/resume session-dismiss-retry");
  9384. app.interaction.current()?.handleInput("\u001b");
  9385. app.interaction.current()?.handleInput("\r");
  9386. await vi.waitFor(() =>
  9387. expect(runtime.dismissQuestionnaire).toHaveBeenCalledOnce(),
  9388. );
  9389. await vi.waitFor(() => {
  9390. const panel = app.interaction.current();
  9391. expect(panel).toBeDefined();
  9392. expect(panel?.render(80).join("\n")).toContain("Ask");
  9393. });
  9394. expect(app.transcript.get("question:question-dismiss-retry")).toMatchObject(
  9395. {
  9396. status: "blocked",
  9397. },
  9398. );
  9399. });
  9400. it("settles a questionnaire dismissal that already reached a terminal Runtime state", async () => {
  9401. const terminal = new FakeTerminal();
  9402. const runtime = createRuntime();
  9403. vi.mocked(runtime.listSessions).mockResolvedValue([
  9404. {
  9405. sessionId: "session-terminal-dismiss",
  9406. title: "Terminal dismissal",
  9407. workspaceDir: "/workspace",
  9408. },
  9409. ]);
  9410. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue({
  9411. id: "question-terminal-dismiss",
  9412. steps: [{ id: "step-1", question: "Proceed?" }],
  9413. });
  9414. vi.mocked(runtime.dismissQuestionnaire).mockRejectedValue(
  9415. Object.assign(new Error("already superseded"), {
  9416. status: 410,
  9417. code: "QUESTIONNAIRE_NOT_PENDING",
  9418. }),
  9419. );
  9420. const app = createTuiApp({
  9421. runtime,
  9422. terminal,
  9423. version: "0.1.0",
  9424. workspaceDir: "/workspace",
  9425. });
  9426. await app.ready;
  9427. await app.submit("/resume session-terminal-dismiss");
  9428. await app.submit("/ask-cancel");
  9429. expect(
  9430. app.transcript.get("question:question-terminal-dismiss"),
  9431. ).toMatchObject({
  9432. status: "resolved",
  9433. title: "Question closed",
  9434. detail: "Question is no longer pending.",
  9435. });
  9436. expect(app.interaction.isActive()).toBe(false);
  9437. });
  9438. it("projects live Desktop permission events into the transcript", async () => {
  9439. const terminal = new FakeTerminal();
  9440. const runtime = createRuntime();
  9441. vi.mocked(runtime.watchEvents).mockImplementation(
  9442. async function* watchEvents() {
  9443. yield runtimeEvent({
  9444. type: "permission.ask",
  9445. timestamp: 100,
  9446. source: "runtime",
  9447. payload: {
  9448. requestId: "permission-live",
  9449. sessionId: "session-1",
  9450. agentName: "mavis",
  9451. toolName: "bash",
  9452. toolDescription: "Run a shell command",
  9453. reason: "Run checks",
  9454. ruleContents: ["Bash(pnpm test:*)"],
  9455. allowAlwaysSupported: true,
  9456. },
  9457. });
  9458. },
  9459. );
  9460. const app = createTuiApp({
  9461. runtime,
  9462. terminal,
  9463. version: "0.1.0",
  9464. workspaceDir: "/workspace",
  9465. });
  9466. await app.ready;
  9467. await app.submit("Start the current session");
  9468. await app.submit("/transcript");
  9469. expect(app.surfaceHost.getActiveSurface()).toEqual({
  9470. kind: "feature",
  9471. id: "transcript",
  9472. });
  9473. app.start();
  9474. await vi.waitFor(() =>
  9475. expect(app.transcript.get("permission:permission-live")).toMatchObject({
  9476. kind: "permission",
  9477. status: "blocked",
  9478. content: expect.stringContaining("Run checks"),
  9479. }),
  9480. );
  9481. expect(app.transcript.get("permission:permission-live")).toMatchObject({
  9482. title: "bash",
  9483. content: "Run checks",
  9484. });
  9485. expect(
  9486. app.transcript.get("permission:permission-live")?.content,
  9487. ).not.toContain("Rules:");
  9488. expect(app.surfaceHost.getActiveSurface()).toEqual({
  9489. kind: "chat",
  9490. id: "chat",
  9491. });
  9492. await app.submit("/allow");
  9493. expect(app.surfaceHost.getActiveSurface()).toEqual({
  9494. kind: "feature",
  9495. id: "transcript",
  9496. });
  9497. await app.stop();
  9498. });
  9499. it("ignores Desktop interaction events until their session is active", async () => {
  9500. const terminal = new FakeTerminal();
  9501. const runtime = createRuntime();
  9502. let resolveEventsDelivered: (() => void) | undefined;
  9503. const eventsDelivered = new Promise<void>((resolve) => {
  9504. resolveEventsDelivered = resolve;
  9505. });
  9506. vi.mocked(runtime.watchEvents).mockImplementation(
  9507. async function* watchEvents(signal) {
  9508. yield runtimeEvent({
  9509. type: "permission.ask",
  9510. timestamp: 100,
  9511. source: "runtime",
  9512. payload: {
  9513. requestId: "permission-other-session",
  9514. sessionId: "session-other",
  9515. agentName: "mavis",
  9516. toolName: "bash",
  9517. },
  9518. });
  9519. yield runtimeEvent({
  9520. type: "questionnaire.ask",
  9521. timestamp: 101,
  9522. source: "runtime",
  9523. payload: {
  9524. sessionId: "session-other",
  9525. agentName: "mavis",
  9526. request: {
  9527. id: "question-other-session",
  9528. steps: [
  9529. { id: "step-1", question: "Proceed?", selectionMode: "single" },
  9530. ],
  9531. },
  9532. },
  9533. });
  9534. resolveEventsDelivered?.();
  9535. await new Promise<void>((resolve) => {
  9536. signal.addEventListener("abort", () => resolve(), { once: true });
  9537. });
  9538. },
  9539. );
  9540. const app = createTuiApp({
  9541. runtime,
  9542. terminal,
  9543. version: "0.1.0",
  9544. workspaceDir: "/workspace",
  9545. });
  9546. app.start();
  9547. await app.ready;
  9548. await eventsDelivered;
  9549. expect(
  9550. app.transcript.get("permission:permission-other-session"),
  9551. ).toBeUndefined();
  9552. expect(
  9553. app.transcript.get("question:question-other-session"),
  9554. ).toBeUndefined();
  9555. expect(
  9556. app.state.snapshot().sessions.get("session-other")?.interactions
  9557. .permission?.requestId,
  9558. ).toBe("permission-other-session");
  9559. expect(
  9560. app.state.snapshot().sessions.get("session-other")?.interactions
  9561. .questionnaire?.request.id,
  9562. ).toBe("question-other-session");
  9563. await app.stop();
  9564. });
  9565. it("surfaces only descendant permissions while keeping explicit Deny separate from Stop", async () => {
  9566. const terminal = new FakeTerminal();
  9567. const runtime = createRuntime();
  9568. const rootSession = {
  9569. sessionId: "session-root",
  9570. title: "Root session",
  9571. workspaceDir: "/workspace",
  9572. status: "started",
  9573. };
  9574. vi.mocked(runtime.listSessions).mockResolvedValue([rootSession]);
  9575. vi.mocked(runtime.getSession).mockResolvedValue(rootSession);
  9576. vi.mocked(runtime.getDelegationSnapshot).mockResolvedValue({
  9577. schemaVersion: 1,
  9578. rootSessionId: "session-root",
  9579. members: [
  9580. {
  9581. sessionId: "session-child",
  9582. parentSessionId: "session-root",
  9583. agentName: "worker",
  9584. task: "Delegate nested work",
  9585. status: "running",
  9586. },
  9587. {
  9588. sessionId: "session-grandchild",
  9589. parentSessionId: "session-child",
  9590. agentName: "verifier",
  9591. task: "Verify the result",
  9592. status: "running",
  9593. },
  9594. ],
  9595. });
  9596. vi.mocked(runtime.getActiveRun).mockImplementation(
  9597. async (sessionId: string) => ({
  9598. schemaVersion: 1,
  9599. sessionId,
  9600. state:
  9601. sessionId === rootSession.sessionId ? "decision-blocked" : "running",
  9602. turnId:
  9603. sessionId === rootSession.sessionId
  9604. ? "turn-root"
  9605. : `turn-${sessionId}`,
  9606. actions: { steer: false },
  9607. }),
  9608. );
  9609. const deniedPermissionIds = new Set<string>();
  9610. vi.mocked(runtime.replyPermission).mockImplementation(
  9611. async (_agentName, requestId) => {
  9612. deniedPermissionIds.add(requestId);
  9613. return true;
  9614. },
  9615. );
  9616. vi.mocked(runtime.listPendingPermissions).mockImplementation(async () =>
  9617. deniedPermissionIds.has("permission-grandchild")
  9618. ? [
  9619. {
  9620. requestId: "permission-unrelated-next",
  9621. sessionId: "session-unrelated",
  9622. agentName: "worker",
  9623. toolName: "bash",
  9624. reason: "Must remain hidden",
  9625. },
  9626. {
  9627. requestId: deniedPermissionIds.has("permission-child-next")
  9628. ? "permission-child-stop"
  9629. : "permission-child-next",
  9630. sessionId: "session-child",
  9631. agentName: "worker",
  9632. toolName: "read",
  9633. reason: deniedPermissionIds.has("permission-child-next")
  9634. ? "Wait for an explicit Stop"
  9635. : "Inspect the delegated output",
  9636. },
  9637. ]
  9638. : [],
  9639. );
  9640. vi.mocked(runtime.watchEvents).mockImplementation(
  9641. async function* watchEvents(signal) {
  9642. yield runtimeEvent({
  9643. type: "permission.ask",
  9644. timestamp: 100,
  9645. source: "runtime",
  9646. payload: {
  9647. requestId: "permission-unrelated",
  9648. sessionId: "session-unrelated",
  9649. agentName: "worker",
  9650. toolName: "bash",
  9651. reason: "Must stay hidden",
  9652. },
  9653. });
  9654. yield runtimeEvent({
  9655. type: "permission.ask",
  9656. timestamp: 101,
  9657. source: "runtime",
  9658. payload: {
  9659. requestId: "permission-grandchild",
  9660. sessionId: "session-grandchild",
  9661. agentName: "verifier",
  9662. toolName: "write",
  9663. reason: "Update the verification report",
  9664. allowAlwaysSupported: true,
  9665. },
  9666. });
  9667. await new Promise<void>((resolve) => {
  9668. signal.addEventListener("abort", resolve, { once: true });
  9669. });
  9670. },
  9671. );
  9672. const app = createTuiApp({
  9673. runtime,
  9674. terminal,
  9675. version: "0.1.0",
  9676. workspaceDir: "/workspace",
  9677. });
  9678. await app.ready;
  9679. await app.submit("/resume session-root");
  9680. vi.mocked(runtime.abortSession).mockClear();
  9681. vi.mocked(runtime.stopDelegation).mockClear();
  9682. app.start();
  9683. await vi.waitFor(() =>
  9684. expect(
  9685. app.transcript.get("permission:permission-grandchild"),
  9686. ).toMatchObject({
  9687. kind: "permission",
  9688. status: "blocked",
  9689. }),
  9690. );
  9691. expect(
  9692. app.transcript.get("permission:permission-unrelated"),
  9693. ).toBeUndefined();
  9694. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9695. "Update the verification report",
  9696. );
  9697. app.interaction.current()?.handleInput?.("3");
  9698. app.interaction.current()?.handleInput?.("\r");
  9699. await vi.waitFor(() =>
  9700. expect(runtime.replyPermission).toHaveBeenCalledWith(
  9701. "verifier",
  9702. "permission-grandchild",
  9703. "deny",
  9704. ),
  9705. );
  9706. expect(runtime.stopDelegation).not.toHaveBeenCalled();
  9707. expect(runtime.abortSession).not.toHaveBeenCalled();
  9708. await vi.waitFor(() =>
  9709. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9710. "Inspect the delegated output",
  9711. ),
  9712. );
  9713. expect(
  9714. app.transcript.get("permission:permission-unrelated-next"),
  9715. ).toBeUndefined();
  9716. terminal.input?.("\x1b");
  9717. await vi.waitFor(() =>
  9718. expect(runtime.replyPermission).toHaveBeenCalledWith(
  9719. "worker",
  9720. "permission-child-next",
  9721. "deny",
  9722. ),
  9723. );
  9724. expect(runtime.abortSession).not.toHaveBeenCalled();
  9725. expect(runtime.stopDelegation).not.toHaveBeenCalled();
  9726. await vi.waitFor(() =>
  9727. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9728. "Wait for an explicit Stop",
  9729. ),
  9730. );
  9731. terminal.input?.("\x03");
  9732. await vi.waitFor(() =>
  9733. expect(runtime.abortSession).toHaveBeenCalledWith({
  9734. id: rootSession.sessionId,
  9735. turnId: "turn-root",
  9736. reason: "user_stop",
  9737. }),
  9738. );
  9739. expect(runtime.stopDelegation).toHaveBeenCalledOnce();
  9740. expect(runtime.stopDelegation).toHaveBeenCalledWith(rootSession.sessionId);
  9741. expect(runtime.replyPermission).not.toHaveBeenCalledWith(
  9742. "worker",
  9743. "permission-child-stop",
  9744. "deny",
  9745. );
  9746. await app.stop();
  9747. });
  9748. it("recovers a descendant permission from the Runtime pending list without leaking unrelated requests", async () => {
  9749. const runtime = createRuntime();
  9750. const rootSession = {
  9751. sessionId: "session-recovery-root",
  9752. title: "Recovery root",
  9753. workspaceDir: "/workspace",
  9754. };
  9755. vi.mocked(runtime.listSessions).mockResolvedValue([rootSession]);
  9756. vi.mocked(runtime.getSession).mockResolvedValue(rootSession);
  9757. vi.mocked(runtime.getDelegationSnapshot).mockResolvedValue({
  9758. schemaVersion: 1,
  9759. rootSessionId: rootSession.sessionId,
  9760. members: [
  9761. {
  9762. sessionId: "session-recovery-child",
  9763. parentSessionId: rootSession.sessionId,
  9764. agentName: "worker",
  9765. task: "Resume delegated work",
  9766. status: "running",
  9767. },
  9768. ],
  9769. });
  9770. vi.mocked(runtime.listPendingPermissions).mockResolvedValue([
  9771. {
  9772. requestId: "permission-recovery-unrelated",
  9773. sessionId: "session-other-root",
  9774. agentName: "worker",
  9775. toolName: "bash",
  9776. reason: "Do not show this request",
  9777. },
  9778. {
  9779. requestId: "permission-recovery-child",
  9780. sessionId: "session-recovery-child",
  9781. agentName: "worker",
  9782. toolName: "write",
  9783. reason: "Resume the child request",
  9784. },
  9785. ]);
  9786. const app = createTuiApp({
  9787. runtime,
  9788. terminal: new FakeTerminal(),
  9789. version: "0.1.0",
  9790. workspaceDir: "/workspace",
  9791. });
  9792. await app.ready;
  9793. await app.submit("/resume session-recovery-root");
  9794. expect(
  9795. app.transcript.get("permission:permission-recovery-child"),
  9796. ).toMatchObject({
  9797. kind: "permission",
  9798. status: "blocked",
  9799. });
  9800. expect(
  9801. app.transcript.get("permission:permission-recovery-unrelated"),
  9802. ).toBeUndefined();
  9803. expect(app.interaction.current()?.render(80).join("\n")).toContain(
  9804. "Resume the child request",
  9805. );
  9806. await app.stop();
  9807. });
  9808. it("reconnects the Runtime event stream after a transient disconnect", async () => {
  9809. const terminal = new FakeTerminal();
  9810. const runtime = createRuntime();
  9811. const observability = createObservability();
  9812. let attempt = 0;
  9813. vi.mocked(runtime.watchEvents).mockImplementation(
  9814. async function* watchEvents() {
  9815. attempt += 1;
  9816. if (attempt === 1) throw new Error("connection reset");
  9817. yield runtimeEvent({
  9818. type: "permission.ask",
  9819. timestamp: 101,
  9820. source: "runtime",
  9821. payload: {
  9822. requestId: "permission-after-reconnect",
  9823. sessionId: "session-1",
  9824. toolName: "read",
  9825. },
  9826. });
  9827. },
  9828. );
  9829. const app = createTuiApp({
  9830. runtime,
  9831. terminal,
  9832. version: "0.1.0",
  9833. workspaceDir: "/workspace",
  9834. observability,
  9835. });
  9836. await app.ready;
  9837. await app.submit("Start the current session");
  9838. app.start();
  9839. await vi.waitFor(
  9840. () =>
  9841. expect(
  9842. app.transcript.get("permission:permission-after-reconnect"),
  9843. ).toMatchObject({
  9844. status: "blocked",
  9845. }),
  9846. { timeout: 1500 },
  9847. );
  9848. expect(runtime.watchEvents).toHaveBeenCalledTimes(2);
  9849. expect(observability.recordEventStream).toHaveBeenCalledWith(
  9850. expect.objectContaining({
  9851. state: "retry-scheduled",
  9852. attempt: 1,
  9853. retryDelayMs: 250,
  9854. errorKind: "Error",
  9855. }),
  9856. );
  9857. expect(observability.recordEventStream).toHaveBeenCalledWith(
  9858. expect.objectContaining({
  9859. state: "reconnected",
  9860. attempt: 1,
  9861. downtimeMs: expect.any(Number),
  9862. }),
  9863. );
  9864. expect(app.transcript.snapshot()).not.toEqual(
  9865. expect.arrayContaining([
  9866. expect.objectContaining({
  9867. kind: "warning",
  9868. content: expect.stringContaining("Runtime event stream"),
  9869. }),
  9870. ]),
  9871. );
  9872. await app.stop();
  9873. });
  9874. it("sends pasted local attachments and restores failed sends to the Composer", async () => {
  9875. const terminal = new FakeTerminal();
  9876. const runtime = createRuntime();
  9877. const readClipboardImage = vi.fn(async () => ({
  9878. attachment: {
  9879. type: "image" as const,
  9880. filePath: "/tmp/minimax-code-clipboard/diagram.png",
  9881. fileName: "diagram.png",
  9882. mimeType: "image/png",
  9883. sizeBytes: 2048,
  9884. },
  9885. dispose: vi.fn(async () => undefined),
  9886. }));
  9887. const app = createTuiApp({
  9888. runtime,
  9889. terminal,
  9890. version: "0.1.0",
  9891. workspaceDir: "/workspace",
  9892. readClipboardImage,
  9893. readClipboardText: async () => null,
  9894. });
  9895. app.start();
  9896. await app.ready;
  9897. terminal.input?.("\u001bv");
  9898. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(1));
  9899. await app.submit("Inspect the diagram");
  9900. expect(runtime.sendMessage).toHaveBeenCalledWith(
  9901. expect.objectContaining({
  9902. id: "session-1",
  9903. content: "Inspect the diagram",
  9904. attachments: [
  9905. expect.objectContaining({
  9906. local: { filePath: "/tmp/minimax-code-clipboard/diagram.png" },
  9907. meta: expect.objectContaining({ mimeType: "image/png" }),
  9908. }),
  9909. ],
  9910. }),
  9911. expect.any(AbortSignal),
  9912. );
  9913. expect(app.tui.render(80).join("\n")).not.toContain("[Image #1]");
  9914. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  9915. async function* sendMessage() {
  9916. yield { type: "error", message: "provider unavailable" };
  9917. },
  9918. );
  9919. terminal.input?.("\x16");
  9920. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(2));
  9921. app.editor.setText("Try again");
  9922. app.editor.handleInput("\r");
  9923. await vi.waitFor(() => expect(app.editor.getText()).toContain("Try again"));
  9924. expect(app.tui.render(80).join("\n")).toContain(
  9925. "Error The model provider is temporarily unavailable.",
  9926. );
  9927. expect(app.tui.render(80).join("\n")).not.toContain("Request failed");
  9928. expect(app.editor.getText()).toContain("[Image #1]");
  9929. expect(app.tui.render(80).join("\n")).not.toContain(
  9930. "Message kept under Failed",
  9931. );
  9932. await app.submit("/retry");
  9933. expect(runtime.sendMessage).toHaveBeenLastCalledWith(
  9934. expect.objectContaining({
  9935. content: "Try again",
  9936. attachments: [
  9937. expect.objectContaining({
  9938. local: { filePath: "/tmp/minimax-code-clipboard/diagram.png" },
  9939. }),
  9940. ],
  9941. }),
  9942. expect.any(AbortSignal),
  9943. );
  9944. await app.submit("A fresh turn");
  9945. expect(app.tui.render(80).join("\n")).not.toContain("Couldn't send");
  9946. await app.stop();
  9947. });
  9948. it.each([
  9949. ['content', 'Content review withdrew this response. Rephrase your request, then retry.'],
  9950. ['network', 'Content review did not return a usable result, so this response stopped.'],
  9951. ] as const)("presents a %s review stop without a failed Queue item", async (variant, notice) => {
  9952. const terminal = new FakeTerminal();
  9953. const runtime = createRuntime();
  9954. const busEvents: TuiRuntimeEvent[] = [];
  9955. let wakeBus: (() => void) | undefined;
  9956. vi.mocked(runtime.watchEvents).mockImplementation(
  9957. async function* watchEvents(signal) {
  9958. while (!signal.aborted) {
  9959. if (busEvents.length === 0) {
  9960. await new Promise<void>((resolve) => {
  9961. wakeBus = resolve;
  9962. signal.addEventListener("abort", resolve, { once: true });
  9963. });
  9964. }
  9965. const event = busEvents.shift();
  9966. if (event) yield event;
  9967. }
  9968. },
  9969. );
  9970. let releaseTurn: (() => void) | undefined;
  9971. vi.mocked(runtime.sendMessage).mockImplementation(
  9972. async function* sendMessage() {
  9973. await new Promise<void>((resolve) => {
  9974. releaseTurn = resolve;
  9975. });
  9976. yield { type: "done" };
  9977. },
  9978. );
  9979. const app = createTuiApp({
  9980. runtime,
  9981. terminal,
  9982. version: "0.1.0",
  9983. workspaceDir: "/workspace",
  9984. });
  9985. app.start();
  9986. await app.ready;
  9987. terminal.input?.("review this response");
  9988. terminal.input?.("\r");
  9989. await vi.waitFor(() =>
  9990. expect(app.controller.snapshot().activeTurnId).toBeTruthy(),
  9991. );
  9992. busEvents.push(
  9993. runtimeEvent({
  9994. type: "content.retry.exceeded",
  9995. timestamp: 100,
  9996. source: "runtime-v2",
  9997. payload: { sessionId: "session-1", variant },
  9998. }),
  9999. runtimeEvent({
  10000. type: "message.rewind",
  10001. timestamp: 101,
  10002. source: "runtime-v2",
  10003. payload: { sessionId: "session-1", contextReset: true },
  10004. }),
  10005. );
  10006. wakeBus?.();
  10007. releaseTurn?.();
  10008. await vi.waitFor(() =>
  10009. expect(app.editor.getText()).toBe("review this response"),
  10010. );
  10011. const rendered = app.tui.render(100).join("\n");
  10012. expect(rendered).toContain(notice);
  10013. expect(rendered).not.toContain('Check your network');
  10014. expect(rendered).not.toContain("Message kept under Failed");
  10015. await app.submit("/queue");
  10016. expect(app.interaction.current()).toBeUndefined();
  10017. await app.stop();
  10018. });
  10019. it("sends editable @directory/ input as ordinary text", async () => {
  10020. const terminal = new FakeTerminal();
  10021. const runtime = createRuntime();
  10022. const app = createTuiApp({
  10023. runtime,
  10024. terminal,
  10025. version: "0.1.0",
  10026. workspaceDir: "/workspace",
  10027. });
  10028. await app.submit("Review @src/");
  10029. expect(runtime.sendMessage).toHaveBeenCalledWith(
  10030. { id: "session-1", content: "Review @src/", turnId: expect.any(String) },
  10031. expect.any(AbortSignal),
  10032. );
  10033. await expect(app.submit("Review @generated/")).resolves.toBeUndefined();
  10034. expect(runtime.sendMessage).toHaveBeenCalledTimes(2);
  10035. });
  10036. it("pastes a clipboard image without replacing the text draft and cleans it after send", async () => {
  10037. const terminal = new FakeTerminal();
  10038. const runtime = createRuntime();
  10039. const dispose = vi.fn(async () => undefined);
  10040. const readClipboardImage = vi.fn(async () => ({
  10041. attachment: {
  10042. type: "image" as const,
  10043. filePath: "/tmp/minimax-code-clipboard/clipboard-1.png",
  10044. fileName: "clipboard-1.png",
  10045. mimeType: "image/png",
  10046. sizeBytes: 4096,
  10047. },
  10048. dispose,
  10049. }));
  10050. const app = createTuiApp({
  10051. runtime,
  10052. terminal,
  10053. version: "0.1.0",
  10054. workspaceDir: "/workspace",
  10055. readClipboardImage,
  10056. readClipboardText: async () => null,
  10057. });
  10058. app.start();
  10059. await app.ready;
  10060. app.editor.setText("Keep this draft");
  10061. terminal.input?.("\u001B[118;9u");
  10062. terminal.input?.("\u001B[118;9:3u");
  10063. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledOnce());
  10064. await vi.waitFor(() =>
  10065. expect(app.editor.getText()).toContain("[Image #1]"),
  10066. );
  10067. expect(app.editor.getText()).toBe("Keep this draft [Image #1] ");
  10068. expect(app.tui.render(100).join("\n")).not.toContain(
  10069. "A clipboard media paste is already in progress.",
  10070. );
  10071. await app.submit("Keep this draft");
  10072. expect(runtime.sendMessage).toHaveBeenCalledWith(
  10073. expect.objectContaining({
  10074. id: "session-1",
  10075. content: "Keep this draft",
  10076. attachments: [
  10077. expect.objectContaining({
  10078. local: { filePath: "/tmp/minimax-code-clipboard/clipboard-1.png" },
  10079. meta: expect.objectContaining({ mimeType: "image/png" }),
  10080. }),
  10081. ],
  10082. }),
  10083. expect.any(AbortSignal),
  10084. );
  10085. expect(dispose).toHaveBeenCalledOnce();
  10086. await app.stop();
  10087. });
  10088. it("retains existing draft state when clipboard read or send fails", async () => {
  10089. const terminal = new FakeTerminal();
  10090. const runtime = createRuntime();
  10091. const dispose = vi.fn(async () => undefined);
  10092. const readClipboardImage = vi
  10093. .fn()
  10094. .mockResolvedValueOnce({
  10095. attachment: {
  10096. type: "image" as const,
  10097. filePath: "/tmp/minimax-code-clipboard/clipboard-2.png",
  10098. fileName: "clipboard-2.png",
  10099. mimeType: "image/png",
  10100. sizeBytes: 1024,
  10101. },
  10102. dispose,
  10103. })
  10104. .mockRejectedValueOnce(new Error("clipboard has no image"));
  10105. vi.mocked(runtime.sendMessage).mockImplementationOnce(
  10106. async function* sendMessage() {
  10107. yield { type: "error", message: "provider unavailable" };
  10108. },
  10109. );
  10110. const app = createTuiApp({
  10111. runtime,
  10112. terminal,
  10113. version: "0.1.0",
  10114. workspaceDir: "/workspace",
  10115. readClipboardImage,
  10116. readClipboardText: async () => null,
  10117. });
  10118. app.start();
  10119. await app.ready;
  10120. app.editor.setText("Do not clear me");
  10121. terminal.input?.("\x16");
  10122. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(1));
  10123. terminal.input?.("\x16");
  10124. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledTimes(2));
  10125. expect(app.editor.getText()).toBe("Do not clear me [Image #1] ");
  10126. await app.submit("Try the image");
  10127. expect(dispose).not.toHaveBeenCalled();
  10128. expect(app.tui.render(80).join("\n")).toContain("[Image #1]");
  10129. terminal.input?.("\x7f");
  10130. expect(app.tui.render(80).join("\n")).not.toContain("[Image #1]");
  10131. expect(dispose).not.toHaveBeenCalled();
  10132. await app.stop();
  10133. expect(dispose).toHaveBeenCalledOnce();
  10134. });
  10135. it("cancels an in-flight clipboard read with Ctrl+C and keeps the draft", async () => {
  10136. const terminal = new FakeTerminal();
  10137. const runtime = createRuntime();
  10138. let observedSignal: AbortSignal | undefined;
  10139. const readClipboardImage = vi.fn(
  10140. async (signal?: AbortSignal) =>
  10141. await new Promise<never>((_resolve, reject) => {
  10142. observedSignal = signal;
  10143. signal?.addEventListener(
  10144. "abort",
  10145. () => reject(new Error("cancelled")),
  10146. { once: true },
  10147. );
  10148. }),
  10149. );
  10150. const app = createTuiApp({
  10151. runtime,
  10152. terminal,
  10153. version: "0.1.0",
  10154. workspaceDir: "/workspace",
  10155. readClipboardImage,
  10156. readClipboardText: async () => null,
  10157. });
  10158. app.start();
  10159. await app.ready;
  10160. app.editor.setText("Draft survives");
  10161. terminal.input?.("\x16");
  10162. await vi.waitFor(() => expect(observedSignal).toBeDefined());
  10163. terminal.input?.("\x03");
  10164. await vi.waitFor(() => expect(observedSignal?.aborted).toBe(true));
  10165. expect(app.editor.getText()).toBe("Draft survives");
  10166. await app.stop();
  10167. });
  10168. it("keeps queued clipboard files alive until the Runtime reports a terminal queue state", async () => {
  10169. const terminal = new FakeTerminal();
  10170. const runtime = createRuntime();
  10171. const dispose = vi.fn(async () => undefined);
  10172. let finishTurn: (() => void) | undefined;
  10173. let deliverQueueEvent: ((event: TuiRuntimeEvent) => void) | undefined;
  10174. vi.mocked(runtime.sendMessage).mockImplementation(
  10175. async function* sendMessage() {
  10176. await new Promise<void>((resolve) => {
  10177. finishTurn = resolve;
  10178. });
  10179. yield { type: "done" };
  10180. },
  10181. );
  10182. vi.mocked(runtime.watchEvents).mockImplementation(
  10183. async function* watchEvents() {
  10184. const event = await new Promise<TuiRuntimeEvent>((resolve) => {
  10185. deliverQueueEvent = resolve;
  10186. });
  10187. yield event;
  10188. },
  10189. );
  10190. const readClipboardImage = vi.fn(async () => ({
  10191. attachment: {
  10192. type: "image" as const,
  10193. filePath: "/tmp/minimax-code-clipboard/clipboard-queue.png",
  10194. fileName: "clipboard-queue.png",
  10195. mimeType: "image/png",
  10196. sizeBytes: 2048,
  10197. },
  10198. dispose,
  10199. }));
  10200. const app = createTuiApp({
  10201. runtime,
  10202. terminal,
  10203. version: "0.1.0",
  10204. workspaceDir: "/workspace",
  10205. productFeatures: { queue: true },
  10206. readClipboardImage,
  10207. });
  10208. app.start();
  10209. await app.ready;
  10210. const first = app.submit("First turn");
  10211. await vi.waitFor(() =>
  10212. expect(app.controller.snapshot().status).toBe("running"),
  10213. );
  10214. terminal.input?.("\x16");
  10215. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledOnce());
  10216. await app.submit("Queued with image");
  10217. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  10218. "session-1",
  10219. "Queued with image",
  10220. expect.objectContaining({
  10221. attachments: [
  10222. expect.objectContaining({ fileName: "clipboard-queue.png" }),
  10223. ],
  10224. }),
  10225. );
  10226. expect(dispose).not.toHaveBeenCalled();
  10227. deliverQueueEvent?.(
  10228. runtimeEvent({
  10229. type: "session.queue.updated",
  10230. timestamp: Date.now(),
  10231. source: "runtime",
  10232. payload: {
  10233. sessionId: "session-1",
  10234. itemId: "queue-1",
  10235. status: "completed",
  10236. queuedCount: 0,
  10237. },
  10238. }),
  10239. );
  10240. await vi.waitFor(() => expect(dispose).toHaveBeenCalledOnce());
  10241. finishTurn?.();
  10242. await first;
  10243. await app.stop();
  10244. });
  10245. it("opens the Desktop model picker and applies the selected session model", async () => {
  10246. const terminal = new FakeTerminal();
  10247. const runtime = createRuntime();
  10248. vi.mocked(runtime.listModels).mockResolvedValue([
  10249. {
  10250. providerId: "minimax",
  10251. modelId: "MiniMax-M3",
  10252. displayName: "MiniMax M3",
  10253. variant: "thinking",
  10254. thinkingConfig: { mode: "switchable", defaultValue: "true" },
  10255. providerKind: "minimax-managed",
  10256. selected: true,
  10257. },
  10258. ]);
  10259. const app = createTuiApp({
  10260. runtime,
  10261. terminal,
  10262. version: "0.1.0",
  10263. workspaceDir: "/workspace",
  10264. });
  10265. app.start();
  10266. await app.ready;
  10267. await app.submit("Create a session");
  10268. await app.submit("/model");
  10269. expect(app.tui.hasOverlay()).toBe(false);
  10270. expect(app.interaction.isActive()).toBe(true);
  10271. terminal.input?.("\x1b");
  10272. expect(app.tui.hasOverlay()).toBe(false);
  10273. await app.submit("/model");
  10274. terminal.input?.("\r");
  10275. await vi.waitFor(() =>
  10276. expect(runtime.selectModel).toHaveBeenCalledWith(
  10277. expect.objectContaining({
  10278. providerId: "minimax",
  10279. modelId: "MiniMax-M3",
  10280. variant: "thinking",
  10281. }),
  10282. "session-1",
  10283. ),
  10284. );
  10285. await vi.waitFor(() => {
  10286. const rendered = app.tui.render(120).join("\n");
  10287. expect(rendered).toContain("✦ MiniMax M3");
  10288. expect(rendered).toContain("Thinking On");
  10289. expect(rendered).not.toContain("MiniMax M3#thinking");
  10290. });
  10291. await app.stop();
  10292. });
  10293. it("queues a thinking-on model with the configured effort even when the Session stored none", async () => {
  10294. const terminal = new FakeTerminal();
  10295. const runtime = createRuntime();
  10296. let finishTurn: (() => void) | undefined;
  10297. vi.mocked(runtime.listModels).mockResolvedValue([
  10298. {
  10299. providerId: "minimax",
  10300. modelId: "deep-reasoner-1",
  10301. displayName: "deep-reasoner-1",
  10302. selected: true,
  10303. variant: "thinking",
  10304. thinkingConfig: { mode: "switchable", defaultValue: "true" },
  10305. effortOptions: ["xhigh"],
  10306. },
  10307. ]);
  10308. vi.mocked(runtime.sendMessage).mockImplementation(
  10309. async function* sendMessage() {
  10310. await new Promise<void>((resolve) => {
  10311. finishTurn = resolve;
  10312. });
  10313. yield { type: "done" };
  10314. },
  10315. );
  10316. const app = createTuiApp({
  10317. runtime,
  10318. terminal,
  10319. version: "0.1.0",
  10320. workspaceDir: "/workspace",
  10321. productFeatures: { queue: true },
  10322. });
  10323. app.start();
  10324. await app.ready;
  10325. const first = app.submit("First turn");
  10326. await vi.waitFor(() =>
  10327. expect(app.controller.snapshot().status).toBe("running"),
  10328. );
  10329. await app.submit("Queued turn");
  10330. // The Session echo carries no stored effort, so the per-Turn selection has to
  10331. // resolve the configured level. Sending only `variant: thinking` makes Runtime
  10332. // drop the effort and the provider apply its own default.
  10333. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  10334. "session-1",
  10335. "Queued turn",
  10336. expect.objectContaining({
  10337. model: expect.objectContaining({
  10338. providerId: "minimax",
  10339. modelId: "deep-reasoner-1",
  10340. variant: "thinking",
  10341. thinking: { effort: "xhigh" },
  10342. }),
  10343. }),
  10344. );
  10345. finishTurn?.();
  10346. await first;
  10347. await app.stop();
  10348. });
  10349. it("applies a welcome-screen effort to the new Session before sending its first message", async () => {
  10350. const terminal = new FakeTerminal();
  10351. const runtime = createRuntime();
  10352. vi.mocked(runtime.listModels).mockResolvedValue([
  10353. {
  10354. providerId: "custom_provider:byok",
  10355. modelId: "byok-large-5",
  10356. displayName: "BYOK Large 5",
  10357. selected: true,
  10358. variant: "",
  10359. thinkingConfig: { mode: "switchable", defaultValue: "false" },
  10360. effortOptions: ["low", "medium", "high"],
  10361. },
  10362. ]);
  10363. let releaseDefaultSelection: ((selected: boolean) => void) | undefined;
  10364. let releaseSessionSelection: ((selected: boolean) => void) | undefined;
  10365. vi.mocked(runtime.selectModel)
  10366. .mockImplementationOnce(
  10367. async () =>
  10368. await new Promise<boolean>((resolve) => {
  10369. releaseDefaultSelection = resolve;
  10370. }),
  10371. )
  10372. .mockImplementationOnce(
  10373. async () =>
  10374. await new Promise<boolean>((resolve) => {
  10375. releaseSessionSelection = resolve;
  10376. }),
  10377. );
  10378. const app = createTuiApp({
  10379. runtime,
  10380. terminal,
  10381. version: "0.1.0",
  10382. workspaceDir: "/workspace",
  10383. });
  10384. app.start();
  10385. await app.ready;
  10386. await app.submit("/model");
  10387. terminal.input?.("\u001b[C");
  10388. terminal.input?.("\r");
  10389. const firstTurn = app.submit("First turn");
  10390. await vi.waitFor(() =>
  10391. expect(runtime.selectModel).toHaveBeenNthCalledWith(
  10392. 1,
  10393. expect.objectContaining({ thinking: { effort: "high" }, variant: "" }),
  10394. undefined,
  10395. ),
  10396. );
  10397. expect(runtime.selectModel).toHaveBeenCalledOnce();
  10398. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10399. releaseDefaultSelection?.(true);
  10400. await vi.waitFor(() =>
  10401. expect(runtime.selectModel).toHaveBeenNthCalledWith(
  10402. 2,
  10403. expect.objectContaining({ thinking: { effort: "high" }, variant: "" }),
  10404. "session-1",
  10405. ),
  10406. );
  10407. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10408. releaseSessionSelection?.(true);
  10409. await firstTurn;
  10410. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  10411. expect(runtime.selectModel.mock.invocationCallOrder[1]).toBeLessThan(
  10412. runtime.sendMessage.mock.invocationCallOrder[0] ??
  10413. Number.POSITIVE_INFINITY,
  10414. );
  10415. await app.stop();
  10416. });
  10417. it("does not send the first message when Runtime rejects its pending effort", async () => {
  10418. const terminal = new FakeTerminal();
  10419. const runtime = createRuntime();
  10420. vi.mocked(runtime.listModels).mockResolvedValue([
  10421. {
  10422. providerId: "custom_provider:byok",
  10423. modelId: "byok-large-5",
  10424. displayName: "BYOK Large 5",
  10425. selected: true,
  10426. effortOptions: ["low", "medium", "high"],
  10427. },
  10428. ]);
  10429. vi.mocked(runtime.selectModel)
  10430. .mockResolvedValueOnce(true)
  10431. .mockResolvedValueOnce(false);
  10432. const app = createTuiApp({
  10433. runtime,
  10434. terminal,
  10435. version: "0.1.0",
  10436. workspaceDir: "/workspace",
  10437. });
  10438. app.start();
  10439. await app.ready;
  10440. await app.submit("/model");
  10441. terminal.input?.("\r");
  10442. await vi.waitFor(() => expect(runtime.selectModel).toHaveBeenCalledOnce());
  10443. await app.submit("First turn");
  10444. expect(runtime.selectModel).toHaveBeenCalledTimes(2);
  10445. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10446. await app.stop();
  10447. });
  10448. it("lets Escape cancel the first turn while Desktop is creating its session", async () => {
  10449. const terminal = new FakeTerminal();
  10450. const runtime = createRuntime();
  10451. let finishSessionCreation:
  10452. | ((session: { sessionId: string; workspaceDir: string }) => void)
  10453. | undefined;
  10454. vi.mocked(runtime.createSession).mockImplementation(
  10455. async () =>
  10456. await new Promise<{ sessionId: string; workspaceDir: string }>(
  10457. (resolve) => {
  10458. finishSessionCreation = resolve;
  10459. },
  10460. ),
  10461. );
  10462. const app = createTuiApp({
  10463. runtime,
  10464. terminal,
  10465. version: "0.1.0",
  10466. workspaceDir: "/workspace",
  10467. });
  10468. app.start();
  10469. await app.ready;
  10470. const submitting = app.submit("Wait for the session");
  10471. await vi.waitFor(() =>
  10472. expect(app.controller.snapshot()).toMatchObject({
  10473. status: "starting",
  10474. activeTurnId: expect.any(String),
  10475. }),
  10476. );
  10477. expect(app.tui.render(80).join("\n")).toContain("Loading");
  10478. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  10479. expect(app.tui.render(80).join("\n")).not.toContain("MCode ·");
  10480. terminal.input?.("\x1b");
  10481. await vi.waitFor(() =>
  10482. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  10483. );
  10484. finishSessionCreation?.({
  10485. sessionId: "session-created",
  10486. workspaceDir: "/workspace",
  10487. });
  10488. await submitting;
  10489. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10490. expect(app.transcript.snapshot()).toEqual(
  10491. expect.arrayContaining([
  10492. expect.objectContaining({ kind: "assistant", status: "cancelled" }),
  10493. ]),
  10494. );
  10495. await app.stop();
  10496. });
  10497. it("restores a submission attempted while the previous cancellation fence is active", async () => {
  10498. const terminal = new FakeTerminal();
  10499. const runtime = createRuntime();
  10500. let releaseCancelledStream: (() => void) | undefined;
  10501. let sendCount = 0;
  10502. vi.mocked(runtime.sendMessage).mockImplementation(
  10503. async function* sendMessage(_req: SendMessageReq, signal?: AbortSignal) {
  10504. sendCount += 1;
  10505. if (sendCount === 1) {
  10506. await new Promise<void>((resolve) => {
  10507. signal?.addEventListener("abort", resolve, { once: true });
  10508. });
  10509. await new Promise<void>((resolve) => {
  10510. releaseCancelledStream = resolve;
  10511. });
  10512. } else {
  10513. yield { type: "delta", content: "Second response" };
  10514. }
  10515. yield { type: "done" };
  10516. },
  10517. );
  10518. vi.mocked(runtime.abortSession).mockImplementation(async () => {
  10519. setTimeout(() => releaseCancelledStream?.(), 10);
  10520. return true;
  10521. });
  10522. const app = createTuiApp({
  10523. runtime,
  10524. terminal,
  10525. version: "0.1.0",
  10526. workspaceDir: "/workspace",
  10527. });
  10528. app.start();
  10529. await app.ready;
  10530. terminal.input?.("First request");
  10531. terminal.input?.("\r");
  10532. await vi.waitFor(() =>
  10533. expect(app.controller.snapshot().status).toBe("running"),
  10534. );
  10535. terminal.input?.("\x1b");
  10536. await vi.waitFor(() =>
  10537. expect(app.controller.snapshot().cancelling).toBe(true),
  10538. );
  10539. terminal.input?.("Second request");
  10540. terminal.input?.("\r");
  10541. await vi.waitFor(() => expect(app.editor.getText()).toBe("Second request"));
  10542. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  10543. await vi.waitFor(() =>
  10544. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  10545. );
  10546. await vi.waitFor(() =>
  10547. expect(app.controller.snapshot().retiringTurnId).toBeUndefined(),
  10548. );
  10549. expect(app.controller.snapshot().cancelling).toBe(false);
  10550. expect(app.tui.render(80).join("\n")).not.toContain(
  10551. "Stopping the current response",
  10552. );
  10553. app.editor.handleInput("\r");
  10554. await vi.waitFor(() =>
  10555. expect(runtime.sendMessage).toHaveBeenCalledTimes(2),
  10556. );
  10557. expect(runtime.sendMessage).toHaveBeenCalledTimes(2);
  10558. expect(runtime.enqueueMessage).not.toHaveBeenCalled();
  10559. expect(app.transcript.snapshot()).toEqual(
  10560. expect.arrayContaining([
  10561. expect.objectContaining({ kind: "assistant", status: "cancelled" }),
  10562. ]),
  10563. );
  10564. await app.stop();
  10565. });
  10566. it("restores a failed submission before text typed while cancellation is retiring", async () => {
  10567. const terminal = new FakeTerminal();
  10568. const runtime = createRuntime();
  10569. let releaseRuntimeOwnership: (() => void) | undefined;
  10570. const runtimeOwnershipReleased = new Promise<void>((resolve) => {
  10571. releaseRuntimeOwnership = resolve;
  10572. });
  10573. vi.mocked(runtime.sendMessage).mockImplementation(
  10574. async function* sendMessage(_req: SendMessageReq, signal?: AbortSignal) {
  10575. await new Promise<void>((resolve) => {
  10576. signal?.addEventListener("abort", resolve, { once: true });
  10577. });
  10578. await runtimeOwnershipReleased;
  10579. yield { type: "done" };
  10580. },
  10581. );
  10582. const app = createTuiApp({
  10583. runtime,
  10584. terminal,
  10585. version: "0.1.0",
  10586. workspaceDir: "/workspace",
  10587. });
  10588. app.start();
  10589. await app.ready;
  10590. terminal.input?.("First request");
  10591. terminal.input?.("\r");
  10592. await vi.waitFor(() =>
  10593. expect(app.controller.snapshot().status).toBe("running"),
  10594. );
  10595. terminal.input?.("\x1b");
  10596. await vi.waitFor(
  10597. () => expect(app.controller.snapshot().retiringTurnId).toBeTruthy(),
  10598. {
  10599. timeout: 2_000,
  10600. },
  10601. );
  10602. expect(app.controller.snapshot()).toMatchObject({
  10603. status: "idle",
  10604. activeTurnId: undefined,
  10605. cancelling: false,
  10606. });
  10607. terminal.input?.("Second request");
  10608. terminal.input?.("\r");
  10609. terminal.input?.("extra detail");
  10610. await vi.waitFor(() => expect(app.editor.getText()).toBe("extra detail"));
  10611. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  10612. await vi.waitFor(() =>
  10613. expect(app.tui.render(160).join("\n")).toContain("Second request"),
  10614. );
  10615. expect(app.editor.getText()).toBe("Second request\nextra detail");
  10616. releaseRuntimeOwnership?.();
  10617. await vi.waitFor(() =>
  10618. expect(app.controller.snapshot().retiringTurnId).toBeUndefined(),
  10619. );
  10620. expect(app.tui.render(160).join("\n")).not.toContain(
  10621. "Runtime is still stopping; your draft is preserved",
  10622. );
  10623. await app.stop();
  10624. });
  10625. it("aborts session creation when the TUI stops during its first turn", async () => {
  10626. const terminal = new FakeTerminal();
  10627. const runtime = createRuntime();
  10628. let finishSessionCreation:
  10629. | ((session: { sessionId: string; workspaceDir: string }) => void)
  10630. | undefined;
  10631. vi.mocked(runtime.createSession).mockImplementation(
  10632. async () =>
  10633. await new Promise<{ sessionId: string; workspaceDir: string }>(
  10634. (resolve) => {
  10635. finishSessionCreation = resolve;
  10636. },
  10637. ),
  10638. );
  10639. const app = createTuiApp({
  10640. runtime,
  10641. terminal,
  10642. version: "0.1.0",
  10643. workspaceDir: "/workspace",
  10644. });
  10645. app.start();
  10646. await app.ready;
  10647. const submitting = app.submit("Wait for the session");
  10648. await vi.waitFor(() =>
  10649. expect(app.controller.snapshot().activeTurnId).toEqual(
  10650. expect.any(String),
  10651. ),
  10652. );
  10653. const stopping = app.stop();
  10654. finishSessionCreation?.({
  10655. sessionId: "session-created",
  10656. workspaceDir: "/workspace",
  10657. });
  10658. await Promise.all([submitting, stopping]);
  10659. expect(runtime.sendMessage).not.toHaveBeenCalled();
  10660. expect(app.transcript.snapshot()).toEqual(
  10661. expect.arrayContaining([
  10662. expect.objectContaining({ kind: "assistant", status: "cancelled" }),
  10663. ]),
  10664. );
  10665. expect(terminal.stopped).toBe(true);
  10666. });
  10667. it.each(["minimax", "custom_provider:work"])(
  10668. "hydrates the Runtime-selected startup model for %s",
  10669. async (providerId) => {
  10670. const runtime = createRuntime();
  10671. vi.mocked(runtime.listModels).mockResolvedValue([
  10672. { providerId, modelId: "MiniMax-M3", selected: true },
  10673. ]);
  10674. const app = createTuiApp({
  10675. runtime,
  10676. terminal: new FakeTerminal(),
  10677. version: "0.1.0",
  10678. workspaceDir: "/workspace",
  10679. });
  10680. try {
  10681. await app.ready;
  10682. expect(runtime.listModels).toHaveBeenCalled();
  10683. expect(runtime.selectModel).not.toHaveBeenCalled();
  10684. await app.submit("/model");
  10685. expect(runtime.selectModel).not.toHaveBeenCalled();
  10686. } finally {
  10687. await app.stop();
  10688. }
  10689. },
  10690. );
  10691. it("offers provider onboarding when Desktop has no models", async () => {
  10692. const terminal = new FakeTerminal();
  10693. const runtime = createRuntime();
  10694. vi.mocked(runtime.listModels).mockResolvedValue([]);
  10695. const app = createTuiApp({
  10696. runtime,
  10697. terminal,
  10698. version: "0.1.0",
  10699. workspaceDir: "/workspace",
  10700. });
  10701. await app.ready;
  10702. await app.submit("/model unavailable");
  10703. expect(app.tui.hasOverlay()).toBe(false);
  10704. expect(app.interaction.isActive()).toBe(true);
  10705. const rendered = app.tui.render(120).join("\n");
  10706. expect(rendered).toContain("No matching models");
  10707. expect(rendered).toContain("Add 3rd-party provider");
  10708. terminal.input?.("\x1b");
  10709. await app.stop();
  10710. });
  10711. it("keeps the TUI usable when the Runtime model catalog fails to load", async () => {
  10712. const terminal = new FakeTerminal();
  10713. const runtime = createRuntime();
  10714. vi.mocked(runtime.listModels).mockRejectedValue(
  10715. new Error("catalog unavailable"),
  10716. );
  10717. const app = createTuiApp({
  10718. runtime,
  10719. terminal,
  10720. version: "0.1.0",
  10721. workspaceDir: "/workspace",
  10722. });
  10723. await app.ready;
  10724. await expect(app.submit("/model")).resolves.toBeUndefined();
  10725. expect(app.tui.hasOverlay()).toBe(false);
  10726. expect(app.transcript.snapshot().at(-1)).toMatchObject({
  10727. kind: "warning",
  10728. content: "Couldn't load models: catalog unavailable. Retry /model.",
  10729. });
  10730. });
  10731. it("shows a follow-up as queued while Runtime admission is pending", async () => {
  10732. const terminal = new FakeTerminal();
  10733. const runtime = createRuntime();
  10734. let finishFirstTurn: (() => void) | undefined;
  10735. let finishEnqueue: (() => void) | undefined;
  10736. let admitted = false;
  10737. vi.mocked(runtime.sendMessage).mockImplementation(
  10738. async function* sendMessage() {
  10739. await new Promise<void>((resolve) => {
  10740. finishFirstTurn = resolve;
  10741. });
  10742. yield { type: "done" };
  10743. },
  10744. );
  10745. vi.mocked(runtime.enqueueMessage).mockImplementation(async () => {
  10746. await new Promise<void>((resolve) => {
  10747. finishEnqueue = resolve;
  10748. });
  10749. admitted = true;
  10750. return { itemId: "queue-pending-1", status: "queued", position: 1 };
  10751. });
  10752. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () =>
  10753. admitted
  10754. ? [
  10755. {
  10756. itemId: "queue-pending-1",
  10757. sessionId: "session-1",
  10758. status: "queued",
  10759. content: "Second turn",
  10760. },
  10761. ]
  10762. : [],
  10763. );
  10764. const app = createTuiApp({
  10765. runtime,
  10766. terminal,
  10767. version: "0.1.0",
  10768. workspaceDir: "/workspace",
  10769. });
  10770. app.start();
  10771. await app.ready;
  10772. const first = app.submit("First turn");
  10773. await vi.waitFor(() =>
  10774. expect(app.controller.snapshot().activeTurnId).toEqual(
  10775. expect.any(String),
  10776. ),
  10777. );
  10778. terminal.input?.("Second turn");
  10779. terminal.input?.("\x1b\r");
  10780. await vi.waitFor(() =>
  10781. expect(runtime.enqueueMessage).toHaveBeenCalledOnce(),
  10782. );
  10783. try {
  10784. expect(
  10785. app.transcript
  10786. .snapshot()
  10787. .find((cell) => cell.content.includes("Second turn")),
  10788. ).toBeUndefined();
  10789. const rendered = app.tui.render(100).join("\n");
  10790. expect(rendered).not.toContain("Adding to Queue");
  10791. expect(rendered).toContain("Next · after current response");
  10792. expect(rendered).toContain("Second turn");
  10793. finishEnqueue?.();
  10794. await vi.waitFor(() => {
  10795. const confirmed = app.tui.render(100).join("\n");
  10796. expect(confirmed).not.toContain("Adding to Queue");
  10797. expect(confirmed).toContain("Next · after current response");
  10798. expect(confirmed).toContain("Second turn");
  10799. });
  10800. } finally {
  10801. finishEnqueue?.();
  10802. finishFirstTurn?.();
  10803. await first;
  10804. await app.stop();
  10805. }
  10806. });
  10807. it("removes the local Queue admission and restores the Draft when Runtime rejects it", async () => {
  10808. const terminal = new FakeTerminal();
  10809. const runtime = createRuntime();
  10810. let finishFirstTurn: (() => void) | undefined;
  10811. let rejectEnqueue: ((error: Error) => void) | undefined;
  10812. vi.mocked(runtime.sendMessage).mockImplementation(
  10813. async function* sendMessage() {
  10814. await new Promise<void>((resolve) => {
  10815. finishFirstTurn = resolve;
  10816. });
  10817. yield { type: "done" };
  10818. },
  10819. );
  10820. vi.mocked(runtime.enqueueMessage).mockImplementation(
  10821. async () =>
  10822. await new Promise<never>((_resolve, reject) => {
  10823. rejectEnqueue = reject;
  10824. }),
  10825. );
  10826. const app = createTuiApp({
  10827. runtime,
  10828. terminal,
  10829. version: "0.1.0",
  10830. workspaceDir: "/workspace",
  10831. });
  10832. app.start();
  10833. await app.ready;
  10834. const first = app.submit("First turn");
  10835. await vi.waitFor(() =>
  10836. expect(app.controller.snapshot().activeTurnId).toEqual(
  10837. expect.any(String),
  10838. ),
  10839. );
  10840. terminal.input?.("Keep this Draft");
  10841. terminal.input?.("\x1b\r");
  10842. await vi.waitFor(() =>
  10843. expect(app.tui.render(100).join("\n")).toContain(
  10844. "Next · after current response",
  10845. ),
  10846. );
  10847. await vi.waitFor(() =>
  10848. expect(runtime.enqueueMessage).toHaveBeenCalledOnce(),
  10849. );
  10850. rejectEnqueue?.(new Error("queue unavailable"));
  10851. await vi.waitFor(() =>
  10852. expect(app.editor.getText()).toBe("Keep this Draft"),
  10853. );
  10854. const rendered = app.tui.render(100).join("\n");
  10855. expect(rendered).not.toContain("Next · after current response");
  10856. expect(rendered).toContain("Couldn't add this message to the Queue");
  10857. finishFirstTurn?.();
  10858. await first;
  10859. await app.stop();
  10860. });
  10861. it("shows every rapid follow-up as queued while Runtime admissions are serialized", async () => {
  10862. const terminal = new FakeTerminal();
  10863. const runtime = createRuntime();
  10864. let finishFirstTurn: (() => void) | undefined;
  10865. const releaseAdmissions: Array<() => void> = [];
  10866. const queued: TuiQueuedMessage[] = [];
  10867. vi.mocked(runtime.sendMessage).mockImplementation(
  10868. async function* sendMessage() {
  10869. await new Promise<void>((resolve) => {
  10870. finishFirstTurn = resolve;
  10871. });
  10872. yield { type: "done" };
  10873. },
  10874. );
  10875. vi.mocked(runtime.enqueueMessage).mockImplementation(
  10876. async (sessionId, content) => {
  10877. await new Promise<void>((resolve) => releaseAdmissions.push(resolve));
  10878. const item = {
  10879. itemId: `queue-rapid-${String(queued.length + 1)}`,
  10880. sessionId,
  10881. status: "queued",
  10882. content,
  10883. } satisfies TuiQueuedMessage;
  10884. queued.push(item);
  10885. return {
  10886. itemId: item.itemId,
  10887. status: item.status,
  10888. position: queued.length,
  10889. };
  10890. },
  10891. );
  10892. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  10893. ...queued,
  10894. ]);
  10895. const app = createTuiApp({
  10896. runtime,
  10897. terminal,
  10898. version: "0.1.0",
  10899. workspaceDir: "/workspace",
  10900. });
  10901. app.start();
  10902. await app.ready;
  10903. const first = app.submit("First turn");
  10904. await vi.waitFor(() =>
  10905. expect(app.controller.snapshot().activeTurnId).toEqual(
  10906. expect.any(String),
  10907. ),
  10908. );
  10909. terminal.input?.("Second turn");
  10910. terminal.input?.("\x1b\r");
  10911. terminal.input?.("Third turn");
  10912. terminal.input?.("\x1b\r");
  10913. await vi.waitFor(() => {
  10914. const rendered = app.tui.render(100).join("\n");
  10915. expect(rendered).not.toContain("Adding");
  10916. expect(rendered).toContain("Queue · 2 next");
  10917. expect(rendered).toContain("Second turn");
  10918. expect(rendered).toContain("Third turn");
  10919. });
  10920. expect(
  10921. app.transcript
  10922. .snapshot()
  10923. .filter(
  10924. (cell) =>
  10925. cell.content.includes("Second turn") ||
  10926. cell.content.includes("Third turn"),
  10927. ),
  10928. ).toEqual([]);
  10929. await vi.waitFor(() =>
  10930. expect(runtime.enqueueMessage).toHaveBeenCalledOnce(),
  10931. );
  10932. releaseAdmissions[0]?.();
  10933. await vi.waitFor(() =>
  10934. expect(runtime.enqueueMessage).toHaveBeenCalledTimes(2),
  10935. );
  10936. const partiallyConfirmed = app.tui.render(100).join("\n");
  10937. expect(partiallyConfirmed).toContain("Queue · 2 next");
  10938. expect(partiallyConfirmed.indexOf("Second turn")).toBeLessThan(
  10939. partiallyConfirmed.indexOf("Third turn"),
  10940. );
  10941. releaseAdmissions[1]?.();
  10942. await vi.waitFor(() =>
  10943. expect(app.tui.render(100).join("\n")).toContain("Queue · 2 next"),
  10944. );
  10945. finishFirstTurn?.();
  10946. await first;
  10947. await app.stop();
  10948. });
  10949. it("submits follow-ups to the runtime-owned queue and never drains them in the CLI", async () => {
  10950. const terminal = new FakeTerminal();
  10951. const runtime = createRuntime();
  10952. let finishFirstTurn: (() => void) | undefined;
  10953. vi.mocked(runtime.sendMessage).mockImplementation(
  10954. async function* sendMessage(req: SendMessageReq) {
  10955. const content = req.content ?? "";
  10956. if (content === "First turn") {
  10957. await new Promise<void>((resolve) => {
  10958. finishFirstTurn = resolve;
  10959. });
  10960. }
  10961. yield { type: "delta", content: `Reply to ${content || "attachment"}` };
  10962. yield { type: "done" };
  10963. },
  10964. );
  10965. const attachment = {
  10966. type: "file" as const,
  10967. filePath: "/workspace/notes.md",
  10968. fileName: "notes.md",
  10969. mimeType: "text/markdown",
  10970. sizeBytes: 32,
  10971. };
  10972. const queued: Array<{
  10973. itemId: string;
  10974. sessionId: string;
  10975. status: string;
  10976. content: string;
  10977. }> = [];
  10978. vi.mocked(runtime.enqueueMessage).mockImplementation(
  10979. async (sessionId, content) => {
  10980. const item = {
  10981. itemId: `queue-${queued.length + 1}`,
  10982. sessionId,
  10983. status: "queued",
  10984. content,
  10985. };
  10986. queued.push(item);
  10987. return {
  10988. itemId: item.itemId,
  10989. status: item.status,
  10990. position: queued.length,
  10991. };
  10992. },
  10993. );
  10994. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  10995. ...queued,
  10996. ]);
  10997. vi.mocked(runtime.deleteQueuedMessage).mockImplementation(
  10998. async (_sessionId, itemId) => {
  10999. const index = queued.findIndex((item) => item.itemId === itemId);
  11000. if (index < 0) return undefined;
  11001. return queued.splice(index, 1)[0];
  11002. },
  11003. );
  11004. const readClipboardImage = vi.fn(async () => ({
  11005. attachment,
  11006. dispose: vi.fn(async () => undefined),
  11007. }));
  11008. const app = createTuiApp({
  11009. runtime,
  11010. terminal,
  11011. version: "0.1.0",
  11012. workspaceDir: "/workspace",
  11013. readClipboardImage,
  11014. });
  11015. app.start();
  11016. await app.ready;
  11017. const first = app.submit("First turn");
  11018. await vi.waitFor(() =>
  11019. expect(app.controller.snapshot().activeTurnId).toEqual(
  11020. expect.any(String),
  11021. ),
  11022. );
  11023. terminal.input?.("\x16");
  11024. await vi.waitFor(() => expect(readClipboardImage).toHaveBeenCalledOnce());
  11025. await app.submit("Second turn");
  11026. await app.submit("Third turn");
  11027. expect(runtime.sendMessage).toHaveBeenCalledTimes(1);
  11028. expect(runtime.enqueueMessage).toHaveBeenNthCalledWith(
  11029. 1,
  11030. "session-1",
  11031. "Second turn",
  11032. {
  11033. attachments: [attachment],
  11034. model: { providerId: "minimax", modelId: "MiniMax-M2.7" },
  11035. },
  11036. );
  11037. expect(runtime.enqueueMessage).toHaveBeenNthCalledWith(
  11038. 2,
  11039. "session-1",
  11040. "Third turn",
  11041. {
  11042. attachments: [],
  11043. model: { providerId: "minimax", modelId: "MiniMax-M2.7" },
  11044. },
  11045. );
  11046. expect(app.transcript.get("queue:queue-1")).toBeUndefined();
  11047. expect(app.transcript.get("queue:queue-2")).toBeUndefined();
  11048. const queuedUi = app.tui.render(80).join("\n");
  11049. expect(queuedUi).toContain("Queue · 2 next");
  11050. expect(queuedUi).toContain("after current response");
  11051. expect(queuedUi).toContain("Second turn");
  11052. expect(queuedUi).toContain("Third turn");
  11053. expect(queuedUi).toContain("/queue manage");
  11054. await app.submit("/queue");
  11055. expect(app.interaction.render(80).join("\n")).toContain("Queue");
  11056. expect(app.interaction.render(80).join("\n")).toContain("2 next");
  11057. expect(app.interaction.render(80).join("\n")).toContain("› 2. Third turn");
  11058. expect(app.editor.getText()).toBe("");
  11059. terminal.input?.("d");
  11060. expect(app.interaction.render(80).join("\n")).toContain(
  11061. "Remove this next message?",
  11062. );
  11063. terminal.input?.("\r");
  11064. await vi.waitFor(() =>
  11065. expect(runtime.deleteQueuedMessage).toHaveBeenCalledWith(
  11066. "session-1",
  11067. "queue-2",
  11068. ),
  11069. );
  11070. await vi.waitFor(() =>
  11071. expect(app.tui.render(80).join("\n")).not.toContain("Third turn"),
  11072. );
  11073. expect(app.tui.render(80).join("\n")).toContain("Second turn");
  11074. terminal.input?.("\x1b");
  11075. finishFirstTurn?.();
  11076. await first;
  11077. expect(
  11078. vi.mocked(runtime.sendMessage).mock.calls.map((call) => call[0].content),
  11079. ).toEqual(["First turn"]);
  11080. expect(app.tui.render(80).join("\n")).toContain(
  11081. "Next · after current response",
  11082. );
  11083. expect(app.tui.render(80).join("\n")).toContain("Second turn");
  11084. expect(app.tui.render(80).join("\n")).not.toContain("Sending next");
  11085. await app.stop();
  11086. });
  11087. it("uses the Runtime queue when a resumed started session is active before queue/model hydration finishes", async () => {
  11088. const terminal = new FakeTerminal();
  11089. const runtime = createRuntime();
  11090. let releaseQueue: ((items: TuiQueuedMessage[]) => void) | undefined;
  11091. const slowQueue = new Promise<TuiQueuedMessage[]>((resolve) => {
  11092. releaseQueue = resolve;
  11093. });
  11094. let releaseModels: ((models: TuiModel[]) => void) | undefined;
  11095. const slowModels = new Promise<TuiModel[]>((resolve) => {
  11096. releaseModels = resolve;
  11097. });
  11098. const session = {
  11099. sessionId: "session-running",
  11100. title: "Running session",
  11101. workspaceDir: "/workspace",
  11102. status: "started",
  11103. };
  11104. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11105. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11106. vi.mocked(runtime.getActiveRun).mockResolvedValue({
  11107. schemaVersion: 1,
  11108. sessionId: "session-running",
  11109. state: "running",
  11110. turnId: "turn-running",
  11111. actions: { steer: true },
  11112. });
  11113. vi.mocked(runtime.listQueuedMessages).mockImplementation(
  11114. async () => slowQueue,
  11115. );
  11116. vi.mocked(runtime.listModels).mockImplementation(async (sessionId) =>
  11117. sessionId ? slowModels : [],
  11118. );
  11119. vi.mocked(runtime.enqueueMessage).mockResolvedValue({
  11120. itemId: "queue-running-1",
  11121. status: "queued",
  11122. position: 1,
  11123. });
  11124. const app = createTuiApp({
  11125. runtime,
  11126. terminal,
  11127. version: "0.1.0",
  11128. workspaceDir: "/workspace",
  11129. productFeatures: { queue: true },
  11130. });
  11131. await app.ready;
  11132. const resuming = app.submit("/resume session-running");
  11133. await vi.waitFor(() =>
  11134. expect(app.tui.render(80).join("\n")).toContain("Loading"),
  11135. );
  11136. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  11137. const followUp = app.submit("Send this through the Runtime queue");
  11138. await vi.waitFor(() =>
  11139. expect(runtime.enqueueMessage).toHaveBeenCalledWith(
  11140. "session-running",
  11141. "Send this through the Runtime queue",
  11142. { attachments: [] },
  11143. ),
  11144. );
  11145. expect(runtime.sendMessage).not.toHaveBeenCalled();
  11146. releaseQueue?.([]);
  11147. releaseModels?.([]);
  11148. await Promise.all([resuming, followUp]);
  11149. await app.stop();
  11150. });
  11151. it("does not recover a terminal session as an active turn", async () => {
  11152. const terminal = new FakeTerminal();
  11153. const runtime = createRuntime();
  11154. const session = {
  11155. sessionId: "session-finished",
  11156. title: "Finished session",
  11157. workspaceDir: "/workspace",
  11158. status: "finished",
  11159. };
  11160. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11161. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11162. const app = createTuiApp({
  11163. runtime,
  11164. terminal,
  11165. version: "0.1.0",
  11166. workspaceDir: "/workspace",
  11167. });
  11168. await app.ready;
  11169. await app.submit("/resume session-finished");
  11170. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
  11171. expect(app.tui.render(80).join("\n")).toContain("Message · Enter send");
  11172. await app.stop();
  11173. });
  11174. it("does not recover a stale started Session when Runtime is already idle", async () => {
  11175. const terminal = new FakeTerminal();
  11176. const runtime = createRuntime();
  11177. const session = {
  11178. sessionId: "session-stale",
  11179. title: "Stale session",
  11180. workspaceDir: "/workspace",
  11181. status: "started",
  11182. };
  11183. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11184. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11185. const app = createTuiApp({
  11186. runtime,
  11187. terminal,
  11188. version: "0.1.0",
  11189. workspaceDir: "/workspace",
  11190. });
  11191. app.start();
  11192. await app.ready;
  11193. await app.submit("/resume session-stale");
  11194. await vi.waitFor(() =>
  11195. expect(app.tui.render(80).join("\n")).not.toContain("Loading"),
  11196. );
  11197. const rendered = app.tui.render(80).join("\n");
  11198. expect(rendered).not.toContain("Thinking");
  11199. expect(rendered).not.toContain("Stopping response");
  11200. expect(rendered).not.toContain("Stopping the current response");
  11201. expect(rendered).toContain("Message · Enter send");
  11202. await app.stop();
  11203. });
  11204. it("stops a recovered Runtime turn with /stop and Escape through abortSession", async () => {
  11205. const terminal = new FakeTerminal();
  11206. const runtime = createRuntime();
  11207. const session = {
  11208. sessionId: "session-running",
  11209. title: "Running session",
  11210. workspaceDir: "/workspace",
  11211. status: "started",
  11212. };
  11213. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11214. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11215. vi.mocked(runtime.getActiveRun).mockResolvedValue({
  11216. schemaVersion: 1,
  11217. sessionId: "session-running",
  11218. state: "running",
  11219. turnId: "turn-running",
  11220. actions: { steer: true },
  11221. });
  11222. vi.mocked(runtime.abortSession).mockResolvedValue(true);
  11223. const app = createTuiApp({
  11224. runtime,
  11225. terminal,
  11226. version: "0.1.0",
  11227. workspaceDir: "/workspace",
  11228. });
  11229. app.start();
  11230. await app.ready;
  11231. await app.submit("/resume session-running");
  11232. await app.submit("/stop");
  11233. expect(runtime.abortSession).toHaveBeenCalledWith(
  11234. expect.objectContaining({ id: "session-running" }),
  11235. );
  11236. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt");
  11237. vi.mocked(runtime.abortSession).mockClear();
  11238. await app.submit("/resume session-running");
  11239. terminal.input?.("\x1b");
  11240. await vi.waitFor(() =>
  11241. expect(runtime.abortSession).toHaveBeenCalledWith(
  11242. expect.objectContaining({ id: "session-running" }),
  11243. ),
  11244. );
  11245. await vi.waitFor(() =>
  11246. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt"),
  11247. );
  11248. expect(app.tui.render(80).join("\n")).not.toMatch(
  11249. /Stopped after|Interrupted after/u,
  11250. );
  11251. await app.stop();
  11252. });
  11253. it.each([
  11254. [
  11255. "rejects the abort",
  11256. async () => false,
  11257. "Runtime did not confirm that the active response stopped.",
  11258. ],
  11259. [
  11260. "fails the abort request",
  11261. async () => Promise.reject(new Error("connection lost")),
  11262. "Couldn't stop the current response:",
  11263. ],
  11264. ])(
  11265. "clears the recovered foreground projection and reports when Runtime %s",
  11266. async (_label, abort, expectedError) => {
  11267. const terminal = new FakeTerminal();
  11268. const runtime = createRuntime();
  11269. const session = {
  11270. sessionId: "session-running",
  11271. title: "Running session",
  11272. workspaceDir: "/workspace",
  11273. status: "started",
  11274. };
  11275. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11276. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11277. vi.mocked(runtime.getActiveRun).mockResolvedValue({
  11278. schemaVersion: 1,
  11279. sessionId: "session-running",
  11280. state: "running",
  11281. turnId: "turn-running",
  11282. actions: { steer: false },
  11283. });
  11284. vi.mocked(runtime.abortSession).mockImplementation(abort);
  11285. const app = createTuiApp({
  11286. runtime,
  11287. terminal,
  11288. version: "0.1.0",
  11289. workspaceDir: "/workspace",
  11290. });
  11291. app.start();
  11292. await app.ready;
  11293. await app.submit("/resume session-running");
  11294. terminal.input?.("\x1b");
  11295. await vi.waitFor(() =>
  11296. expect(runtime.abortSession).toHaveBeenCalledWith(
  11297. expect.objectContaining({ id: "session-running" }),
  11298. ),
  11299. );
  11300. await vi.waitFor(() =>
  11301. expect(app.tui.render(80).join("\n")).not.toContain("Esc to interrupt"),
  11302. );
  11303. await vi.waitFor(() =>
  11304. expect(app.tui.render(80).join("\n")).toContain(expectedError),
  11305. );
  11306. await app.stop();
  11307. },
  11308. );
  11309. it("keeps Request failed visible when Runtime still has queued follow-ups", async () => {
  11310. const terminal = new FakeTerminal();
  11311. const runtime = createRuntime();
  11312. let finishTurn: (() => void) | undefined;
  11313. const queued = [
  11314. {
  11315. itemId: "queue-after-error",
  11316. sessionId: "session-1",
  11317. status: "queued",
  11318. content: "Continue after failure",
  11319. },
  11320. ];
  11321. vi.mocked(runtime.listQueuedMessages).mockResolvedValue(queued);
  11322. vi.mocked(runtime.enqueueMessage).mockResolvedValue({
  11323. itemId: "queue-after-error",
  11324. status: "queued",
  11325. position: 1,
  11326. });
  11327. vi.mocked(runtime.sendMessage).mockImplementation(
  11328. async function* sendMessage() {
  11329. await new Promise<void>((resolve) => {
  11330. finishTurn = resolve;
  11331. });
  11332. yield { type: "error", message: "provider unavailable" };
  11333. },
  11334. );
  11335. const app = createTuiApp({
  11336. runtime,
  11337. terminal,
  11338. version: "0.1.0",
  11339. workspaceDir: "/workspace",
  11340. productFeatures: { queue: true },
  11341. });
  11342. await app.ready;
  11343. const first = app.submit("First turn");
  11344. await vi.waitFor(() =>
  11345. expect(app.controller.snapshot().activeTurnId).toEqual(
  11346. expect.any(String),
  11347. ),
  11348. );
  11349. await app.submit("Continue after failure");
  11350. finishTurn?.();
  11351. await first;
  11352. expect(app.tui.render(80).join("\n")).toContain(
  11353. "Error The model provider is temporarily unavailable.",
  11354. );
  11355. expect(app.tui.render(80).join("\n")).not.toContain("Request failed");
  11356. await app.stop();
  11357. });
  11358. it("converges a recovered running state after the Runtime emits a terminal event", async () => {
  11359. const terminal = new FakeTerminal();
  11360. const runtime = createRuntime();
  11361. const session = {
  11362. sessionId: "session-recovered",
  11363. title: "Recovered session",
  11364. workspaceDir: "/workspace",
  11365. status: "started",
  11366. };
  11367. const busEvents: TuiRuntimeEvent[] = [];
  11368. let wakeBus: (() => void) | undefined;
  11369. const waitForNextBusEvent = (signal: AbortSignal) =>
  11370. new Promise<void>((resolve) => {
  11371. wakeBus = resolve;
  11372. signal.addEventListener("abort", resolve, { once: true });
  11373. });
  11374. vi.mocked(runtime.listSessions).mockResolvedValue([session]);
  11375. vi.mocked(runtime.getSession).mockResolvedValue(session);
  11376. let activeRecoveredTurn = true;
  11377. vi.mocked(runtime.getActiveRun).mockImplementation(async () =>
  11378. activeRecoveredTurn
  11379. ? {
  11380. schemaVersion: 1,
  11381. sessionId: "session-recovered",
  11382. state: "running",
  11383. turnId: "turn-recovered",
  11384. actions: { steer: true },
  11385. }
  11386. : {
  11387. schemaVersion: 1,
  11388. sessionId: "session-recovered",
  11389. state: "terminal",
  11390. turnId: "turn-recovered",
  11391. actions: { steer: false },
  11392. },
  11393. );
  11394. let durableMessages: Awaited<ReturnType<TuiRuntime["getMessages"]>> = [];
  11395. vi.mocked(runtime.getMessages).mockImplementation(
  11396. async () => durableMessages,
  11397. );
  11398. vi.mocked(runtime.watchEvents).mockImplementation(
  11399. async function* watchEvents(signal) {
  11400. while (!signal.aborted) {
  11401. if (busEvents.length === 0) await waitForNextBusEvent(signal);
  11402. if (signal.aborted) return;
  11403. const event = busEvents.shift();
  11404. if (event) yield event;
  11405. }
  11406. },
  11407. );
  11408. const app = createTuiApp({
  11409. runtime,
  11410. terminal,
  11411. version: "0.1.0",
  11412. workspaceDir: "/workspace",
  11413. });
  11414. app.start();
  11415. await app.ready;
  11416. await app.submit("/resume session-recovered");
  11417. expect(app.tui.render(80).join("\n")).toContain("Loading");
  11418. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  11419. await vi.waitFor(() =>
  11420. expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
  11421. "session-recovered",
  11422. "turn-recovered",
  11423. expect.any(AbortSignal),
  11424. ),
  11425. );
  11426. activeRecoveredTurn = false;
  11427. const historyCallsBeforeTerminal = vi.mocked(runtime.getMessages).mock.calls
  11428. .length;
  11429. durableMessages = [
  11430. {
  11431. id: "message-recovered-assistant",
  11432. turnId: "turn-recovered",
  11433. role: "assistant",
  11434. content: "Recovered answer",
  11435. timestamp: 101,
  11436. },
  11437. ];
  11438. busEvents.push(
  11439. runtimeEvent({
  11440. type: "session.finish",
  11441. timestamp: 101,
  11442. source: "runtime",
  11443. payload: {
  11444. sessionId: "session-recovered",
  11445. turnId: "turn-recovered",
  11446. status: "finished",
  11447. },
  11448. }),
  11449. );
  11450. wakeBus?.();
  11451. wakeBus = undefined;
  11452. await vi.waitFor(() =>
  11453. expect(vi.mocked(runtime.getMessages).mock.calls.length).toBeGreaterThan(
  11454. historyCallsBeforeTerminal,
  11455. ),
  11456. );
  11457. await vi.waitFor(() => {
  11458. const rendered = app.tui.render(80).join("\n");
  11459. expect(rendered).not.toContain("Esc to interrupt");
  11460. expect(app.transcript.snapshot()).toEqual(
  11461. expect.arrayContaining([
  11462. expect.objectContaining({
  11463. kind: "assistant",
  11464. content: "Recovered answer",
  11465. }),
  11466. ]),
  11467. );
  11468. });
  11469. await app.stop();
  11470. });
  11471. it("clears a recovered decision block when switching to a session without a pending decision", async () => {
  11472. const terminal = new FakeTerminal();
  11473. const runtime = createRuntime();
  11474. let controllerSessionId = "";
  11475. const firstSession = {
  11476. sessionId: "session-blocked",
  11477. title: "Blocked session",
  11478. workspaceDir: "/workspace",
  11479. status: "started",
  11480. };
  11481. const secondSession = {
  11482. sessionId: "session-clear",
  11483. title: "Clear session",
  11484. workspaceDir: "/workspace",
  11485. status: "finished",
  11486. };
  11487. vi.mocked(runtime.listSessions).mockResolvedValue([
  11488. firstSession,
  11489. secondSession,
  11490. ]);
  11491. vi.mocked(runtime.getSession).mockImplementation(async (sessionId) =>
  11492. sessionId === firstSession.sessionId ? firstSession : secondSession,
  11493. );
  11494. vi.mocked(runtime.listPendingPermissions).mockImplementation(async () =>
  11495. controllerSessionId === firstSession.sessionId
  11496. ? [
  11497. {
  11498. requestId: "permission-blocked",
  11499. sessionId: firstSession.sessionId,
  11500. agentName: "mavis",
  11501. toolName: "bash",
  11502. reason: "Run checks",
  11503. allowAlwaysSupported: true,
  11504. },
  11505. ]
  11506. : [],
  11507. );
  11508. vi.mocked(runtime.getPendingQuestionnaire).mockResolvedValue(undefined);
  11509. const app = createTuiApp({
  11510. runtime,
  11511. terminal,
  11512. version: "0.1.0",
  11513. workspaceDir: "/workspace",
  11514. });
  11515. await app.ready;
  11516. controllerSessionId = firstSession.sessionId;
  11517. await app.submit("/resume session-blocked");
  11518. expect(app.tui.hasOverlay()).toBe(false);
  11519. expect(app.interaction.isActive()).toBe(true);
  11520. expect(app.tui.render(80).join("\n")).toContain("Approval required");
  11521. controllerSessionId = secondSession.sessionId;
  11522. await app.submit("/resume session-clear");
  11523. expect(app.tui.hasOverlay()).toBe(false);
  11524. const rendered = app.tui.render(80).join("\n");
  11525. expect(rendered).not.toContain("Approval required");
  11526. expect(rendered).not.toContain("Reply required");
  11527. await app.stop();
  11528. });
  11529. it("moves a sending follow-up from the Composer area into the user transcript", async () => {
  11530. const terminal = new FakeTerminal();
  11531. const runtime = createRuntime();
  11532. const busEvents: TuiRuntimeEvent[] = [];
  11533. let wakeBus: (() => void) | undefined;
  11534. const waitForNextBusEvent = (signal: AbortSignal) =>
  11535. new Promise<void>((resolve) => {
  11536. wakeBus = resolve;
  11537. signal.addEventListener("abort", resolve, { once: true });
  11538. });
  11539. vi.mocked(runtime.listSessions).mockResolvedValue([
  11540. {
  11541. sessionId: "session-existing",
  11542. title: "Existing",
  11543. workspaceDir: "/workspace",
  11544. },
  11545. ]);
  11546. vi.mocked(runtime.listQueuedMessages).mockResolvedValue([
  11547. {
  11548. itemId: "queue-with-attachment",
  11549. sessionId: "session-existing",
  11550. status: "queued",
  11551. content: "Review the attached plan",
  11552. attachments: [
  11553. {
  11554. meta: {
  11555. attachmentType: "file",
  11556. fileName: "plan.md",
  11557. mimeType: "text/markdown",
  11558. sizeBytes: 42,
  11559. },
  11560. local: { filePath: "/workspace/plan.md" },
  11561. },
  11562. ],
  11563. },
  11564. {
  11565. itemId: "queue-that-fails",
  11566. sessionId: "session-existing",
  11567. status: "queued",
  11568. content: "Run the failing follow-up",
  11569. },
  11570. ]);
  11571. vi.mocked(runtime.watchEvents).mockImplementation(
  11572. async function* watchEvents(signal) {
  11573. while (!signal.aborted) {
  11574. if (busEvents.length === 0) await waitForNextBusEvent(signal);
  11575. if (signal.aborted) return;
  11576. const event = busEvents.shift();
  11577. if (event) yield event;
  11578. }
  11579. },
  11580. );
  11581. const emitQueueStatus = (
  11582. itemId: string,
  11583. status: string,
  11584. failedReason?: string,
  11585. ) => {
  11586. busEvents.push(
  11587. runtimeEvent({
  11588. type: "session.queue.updated",
  11589. timestamp: Date.now(),
  11590. source: "runtime",
  11591. payload: {
  11592. sessionId: "session-existing",
  11593. itemId,
  11594. status,
  11595. queuedCount: status === "queued" ? 1 : 0,
  11596. ...(failedReason ? { failedReason } : {}),
  11597. },
  11598. }),
  11599. );
  11600. wakeBus?.();
  11601. wakeBus = undefined;
  11602. };
  11603. const app = createTuiApp({
  11604. runtime,
  11605. terminal,
  11606. version: "0.1.0",
  11607. workspaceDir: "/workspace",
  11608. productFeatures: { queue: true },
  11609. });
  11610. app.start();
  11611. await app.ready;
  11612. await app.submit("/resume session-existing");
  11613. expect(app.tui.render(80).join("\n")).toContain("Queue · 2 next");
  11614. expect(app.tui.render(80).join("\n")).toContain("Review the attached plan");
  11615. expect(app.transcript.get("queue:queue-with-attachment")).toBeUndefined();
  11616. emitQueueStatus("queue-with-attachment", "running");
  11617. await vi.waitFor(() =>
  11618. expect(app.transcript.get("queue:queue-with-attachment")).toMatchObject({
  11619. kind: "user",
  11620. status: "succeeded",
  11621. content: expect.stringContaining("Review the attached plan"),
  11622. }),
  11623. );
  11624. expect(app.tui.render(80).join("\n")).not.toContain("SENDING");
  11625. expect(app.tui.render(80).join("\n")).toContain(
  11626. "Next · after current response",
  11627. );
  11628. expect(app.tui.render(80).join("\n")).toContain(
  11629. "Run the failing follow-up",
  11630. );
  11631. expect(
  11632. app.transcript.get("queue:queue-with-attachment")?.attachments,
  11633. ).toEqual([
  11634. expect.objectContaining({
  11635. fileName: "plan.md",
  11636. mimeType: "text/markdown",
  11637. sizeBytes: 42,
  11638. }),
  11639. ]);
  11640. emitQueueStatus("queue-with-attachment", "completed");
  11641. await vi.waitFor(() =>
  11642. expect(app.transcript.get("queue:queue-with-attachment")).toMatchObject({
  11643. kind: "user",
  11644. status: "succeeded",
  11645. content: expect.stringContaining("Review the attached plan"),
  11646. }),
  11647. );
  11648. emitQueueStatus("queue-that-fails", "running");
  11649. await vi.waitFor(() =>
  11650. expect(app.transcript.get("queue:queue-that-fails")).toMatchObject({
  11651. kind: "user",
  11652. status: "succeeded",
  11653. }),
  11654. );
  11655. emitQueueStatus(
  11656. "queue-that-fails",
  11657. "admission-rejected",
  11658. "provider unavailable",
  11659. );
  11660. await vi.waitFor(() =>
  11661. expect(app.editor.getText()).toBe("Run the failing follow-up"),
  11662. );
  11663. expect(app.tui.render(80).join("\n")).toContain(
  11664. "Error Message was not added to the Queue: provider unavailable.",
  11665. );
  11666. expect(app.transcript.get("queue:queue-that-fails")).toMatchObject({
  11667. kind: "user",
  11668. status: "succeeded",
  11669. });
  11670. expect(app.tui.render(80).join("\n")).toContain(
  11671. "Run the failing follow-up",
  11672. );
  11673. await app.stop();
  11674. });
  11675. it("refreshes history when Desktop Runtime finishes an auto-drained queued turn", async () => {
  11676. const terminal = new FakeTerminal();
  11677. const runtime = createRuntime();
  11678. const busEvents: TuiRuntimeEvent[] = [];
  11679. let wakeBus: (() => void) | undefined;
  11680. const waitForNextBusEvent = (signal: AbortSignal) =>
  11681. new Promise<void>((resolve) => {
  11682. wakeBus = resolve;
  11683. signal.addEventListener("abort", resolve, { once: true });
  11684. });
  11685. vi.mocked(runtime.listSessions).mockResolvedValue([
  11686. {
  11687. sessionId: "session-existing",
  11688. title: "Existing",
  11689. workspaceDir: "/workspace",
  11690. },
  11691. ]);
  11692. vi.mocked(runtime.getMessages)
  11693. .mockResolvedValueOnce([])
  11694. .mockResolvedValue([
  11695. {
  11696. id: "message-user-queued",
  11697. turnId: "turn-queued",
  11698. role: "user",
  11699. content: "Runtime follow-up",
  11700. timestamp: 100,
  11701. },
  11702. {
  11703. id: "message-assistant-queued",
  11704. turnId: "turn-queued",
  11705. role: "assistant",
  11706. content: "Runtime follow-up answer",
  11707. timestamp: 101,
  11708. },
  11709. ]);
  11710. vi.mocked(runtime.watchEvents).mockImplementation(
  11711. async function* watchEvents(signal) {
  11712. while (!signal.aborted) {
  11713. if (busEvents.length === 0) {
  11714. await waitForNextBusEvent(signal);
  11715. }
  11716. if (signal.aborted) return;
  11717. const event = busEvents.shift();
  11718. if (event) yield event;
  11719. }
  11720. },
  11721. );
  11722. const emit = (event: RawTuiRuntimeEvent) => {
  11723. busEvents.push(runtimeEvent(event));
  11724. wakeBus?.();
  11725. wakeBus = undefined;
  11726. };
  11727. const app = createTuiApp({
  11728. runtime,
  11729. terminal,
  11730. version: "0.1.0",
  11731. workspaceDir: "/workspace",
  11732. });
  11733. app.start();
  11734. await app.ready;
  11735. await app.submit("/resume session-existing");
  11736. emit({
  11737. type: "session.start",
  11738. timestamp: 100,
  11739. source: "runtime",
  11740. payload: {
  11741. sessionId: "session-existing",
  11742. turnId: "turn-queued",
  11743. source: "queued-drain",
  11744. queueItemIds: ["queue-1"],
  11745. },
  11746. });
  11747. await vi.waitFor(() =>
  11748. expect(app.tui.render(80).join("\n")).toContain("Loading"),
  11749. );
  11750. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  11751. expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
  11752. "session-existing",
  11753. "turn-queued",
  11754. expect.any(AbortSignal),
  11755. );
  11756. emit({
  11757. type: "session.finish",
  11758. timestamp: 101,
  11759. source: "runtime",
  11760. payload: {
  11761. sessionId: "session-existing",
  11762. turnId: "turn-queued",
  11763. status: "finished",
  11764. },
  11765. });
  11766. await vi.waitFor(() =>
  11767. expect(app.transcript.snapshot()).toEqual(
  11768. expect.arrayContaining([
  11769. expect.objectContaining({
  11770. kind: "assistant",
  11771. content: "Runtime follow-up answer",
  11772. }),
  11773. ]),
  11774. ),
  11775. );
  11776. const historyProjectionCalls = vi
  11777. .mocked(runtime.getMessages)
  11778. .mock.calls.filter(
  11779. ([sessionId, limit]) =>
  11780. sessionId === "session-existing" && limit === undefined,
  11781. );
  11782. expect(historyProjectionCalls).toHaveLength(2);
  11783. await app.stop();
  11784. });
  11785. it("writes one structured result when an auto-drained queued turn finishes", async () => {
  11786. const dataDir = await mkdtemp(join(tmpdir(), "mcode-queued-result-"));
  11787. const resultPath = join(dataDir, "results.jsonl");
  11788. const terminal = new FakeTerminal();
  11789. const runtime = createRuntime();
  11790. const busEvents: TuiRuntimeEvent[] = [];
  11791. let wakeBus: (() => void) | undefined;
  11792. let durableMessages: Awaited<ReturnType<TuiRuntime["getMessages"]>> = [];
  11793. vi.mocked(runtime.listSessions).mockResolvedValue([
  11794. {
  11795. sessionId: "session-existing",
  11796. title: "Existing",
  11797. workspaceDir: "/workspace",
  11798. },
  11799. ]);
  11800. vi.mocked(runtime.getMessages).mockImplementation(
  11801. async () => durableMessages,
  11802. );
  11803. const waitForBusEvent = (signal: AbortSignal) =>
  11804. new Promise<void>((resolve) => {
  11805. wakeBus = resolve;
  11806. signal.addEventListener("abort", resolve, { once: true });
  11807. });
  11808. vi.mocked(runtime.watchEvents).mockImplementation(
  11809. async function* watchEvents(signal) {
  11810. while (!signal.aborted) {
  11811. if (busEvents.length === 0) await waitForBusEvent(signal);
  11812. if (signal.aborted) return;
  11813. const event = busEvents.shift();
  11814. if (event) yield event;
  11815. }
  11816. },
  11817. );
  11818. const emit = (event: RawTuiRuntimeEvent) => {
  11819. busEvents.push(runtimeEvent(event));
  11820. wakeBus?.();
  11821. wakeBus = undefined;
  11822. };
  11823. const app = createTuiApp({
  11824. runtime,
  11825. terminal,
  11826. version: "0.1.0",
  11827. workspaceDir: "/workspace",
  11828. statusLineItems: ["build-mode"],
  11829. automationResultPath: resultPath,
  11830. });
  11831. try {
  11832. app.start();
  11833. await app.ready;
  11834. await app.submit("/resume session-existing");
  11835. emit({
  11836. type: "session.start",
  11837. timestamp: 100,
  11838. source: "runtime",
  11839. payload: {
  11840. sessionId: "session-existing",
  11841. turnId: "turn-queued-result",
  11842. source: "queued-drain",
  11843. queueItemIds: ["queue-result"],
  11844. },
  11845. });
  11846. await vi.waitFor(() =>
  11847. expect(runtime.watchSessionTurn).toHaveBeenCalledWith(
  11848. "session-existing",
  11849. "turn-queued-result",
  11850. expect.any(AbortSignal),
  11851. ),
  11852. );
  11853. durableMessages = [
  11854. {
  11855. id: "message-user-result",
  11856. turnId: "turn-queued-result",
  11857. role: "user",
  11858. content: "Queued request",
  11859. timestamp: 101,
  11860. },
  11861. {
  11862. id: "message-assistant-result",
  11863. turnId: "turn-queued-result",
  11864. role: "assistant",
  11865. content: "Queued structured answer",
  11866. timestamp: 102,
  11867. },
  11868. ];
  11869. emit({
  11870. type: "session.finish",
  11871. timestamp: 103,
  11872. source: "runtime",
  11873. payload: {
  11874. sessionId: "session-existing",
  11875. turnId: "turn-queued-result",
  11876. status: "finished",
  11877. },
  11878. });
  11879. await vi.waitFor(async () => {
  11880. const records = (await readFile(resultPath, "utf8"))
  11881. .trim()
  11882. .split("\n")
  11883. .map(JSON.parse);
  11884. expect(records).toEqual([
  11885. expect.objectContaining({
  11886. type: "exec.result",
  11887. sessionId: "session-existing",
  11888. turnId: "turn-queued-result",
  11889. status: "succeeded",
  11890. answer: "Queued structured answer",
  11891. }),
  11892. ]);
  11893. });
  11894. expect(app.controller.snapshot().lastSettledTurn).toEqual({
  11895. sessionId: "session-existing",
  11896. turnId: "turn-queued-result",
  11897. status: "succeeded",
  11898. });
  11899. } finally {
  11900. await app.stop();
  11901. await rm(dataDir, { recursive: true, force: true });
  11902. }
  11903. });
  11904. it("settles an auto-drained follow-up once and replaces waiting state with run duration", async () => {
  11905. const terminal = new FakeTerminal();
  11906. const runtime = createRuntime();
  11907. const busEvents: TuiRuntimeEvent[] = [];
  11908. const queuedItems: TuiQueuedMessage[] = [];
  11909. let wakeBus: (() => void) | undefined;
  11910. let finishFirstTurn: (() => void) | undefined;
  11911. let finishQueuedStream: (() => void) | undefined;
  11912. const queuedStreamClosed = vi.fn();
  11913. let durableMessages: Awaited<ReturnType<TuiRuntime["getMessages"]>> = [];
  11914. const waitForNextBusEvent = (signal: AbortSignal) =>
  11915. new Promise<void>((resolve) => {
  11916. wakeBus = resolve;
  11917. signal.addEventListener("abort", resolve, { once: true });
  11918. });
  11919. vi.mocked(runtime.sendMessage).mockImplementation(
  11920. async function* sendMessage() {
  11921. await new Promise<void>((resolve) => {
  11922. finishFirstTurn = resolve;
  11923. });
  11924. yield { type: "delta", content: "First answer" };
  11925. yield { type: "done" };
  11926. },
  11927. );
  11928. vi.mocked(runtime.watchSessionTurn).mockImplementation(
  11929. async function* watchSessionTurn() {
  11930. try {
  11931. await new Promise<void>((resolve) => {
  11932. finishQueuedStream = resolve;
  11933. });
  11934. yield { type: "delta", content: "Queued answer" };
  11935. yield { type: "done" };
  11936. } finally {
  11937. queuedStreamClosed();
  11938. }
  11939. },
  11940. );
  11941. vi.mocked(runtime.enqueueMessage).mockImplementation(
  11942. async (sessionId, content) => {
  11943. const item: TuiQueuedMessage = {
  11944. itemId: "queue-b",
  11945. sessionId,
  11946. status: "queued",
  11947. content,
  11948. };
  11949. queuedItems.push(item);
  11950. return { itemId: item.itemId, status: item.status, position: 1 };
  11951. },
  11952. );
  11953. vi.mocked(runtime.listQueuedMessages).mockImplementation(async () => [
  11954. ...queuedItems,
  11955. ]);
  11956. vi.mocked(runtime.getMessages).mockImplementation(
  11957. async () => durableMessages,
  11958. );
  11959. vi.mocked(runtime.watchEvents).mockImplementation(
  11960. async function* watchEvents(signal) {
  11961. while (!signal.aborted) {
  11962. if (busEvents.length === 0) await waitForNextBusEvent(signal);
  11963. if (signal.aborted) return;
  11964. const event = busEvents.shift();
  11965. if (event) yield event;
  11966. }
  11967. },
  11968. );
  11969. const emit = (event: RawTuiRuntimeEvent) => {
  11970. busEvents.push(runtimeEvent(event));
  11971. wakeBus?.();
  11972. wakeBus = undefined;
  11973. };
  11974. const app = createTuiApp({
  11975. runtime,
  11976. terminal,
  11977. version: "0.1.0",
  11978. workspaceDir: "/workspace",
  11979. productFeatures: { queue: true },
  11980. });
  11981. app.start();
  11982. await app.ready;
  11983. const first = app.submit("A");
  11984. await vi.waitFor(() =>
  11985. expect(app.controller.snapshot().activeTurnId).toBeDefined(),
  11986. );
  11987. await app.submit("B");
  11988. expect(app.tui.render(80).join("\n")).toContain(
  11989. "Next · after current response",
  11990. );
  11991. expect(app.tui.render(80).join("\n")).toContain("B");
  11992. finishFirstTurn?.();
  11993. await first;
  11994. const queuedItem = queuedItems[0];
  11995. expect(queuedItem).toBeDefined();
  11996. if (!queuedItem) throw new Error("Expected B to be queued.");
  11997. queuedItems[0] = { ...queuedItem, status: "running" };
  11998. emit({
  11999. type: "session.queue.updated",
  12000. timestamp: 200,
  12001. source: "runtime",
  12002. payload: {
  12003. sessionId: "session-1",
  12004. itemId: "queue-b",
  12005. status: "running",
  12006. queuedCount: 0,
  12007. },
  12008. });
  12009. emit({
  12010. type: "session.start",
  12011. timestamp: 201,
  12012. source: "runtime",
  12013. payload: {
  12014. sessionId: "session-1",
  12015. turnId: "turn_queue_b",
  12016. source: "queued-drain",
  12017. queueItemIds: ["queue-b"],
  12018. },
  12019. });
  12020. await vi.waitFor(() =>
  12021. expect(app.tui.render(80).join("\n")).toContain("Loading"),
  12022. );
  12023. expect(app.tui.render(80).join("\n")).not.toContain("Loading · 0s");
  12024. queuedItems.length = 0;
  12025. durableMessages = [
  12026. {
  12027. id: "history-user-b",
  12028. turnId: "turn_queue_b",
  12029. role: "user",
  12030. content: "B",
  12031. timestamp: 202,
  12032. },
  12033. {
  12034. id: "history-assistant-b",
  12035. turnId: "turn_queue_b",
  12036. role: "assistant",
  12037. content: "Queued answer",
  12038. timestamp: 203,
  12039. },
  12040. ];
  12041. finishQueuedStream?.();
  12042. await vi.waitFor(() => expect(queuedStreamClosed).toHaveBeenCalledOnce());
  12043. emit({
  12044. type: "session.finish",
  12045. timestamp: 3_201,
  12046. source: "runtime",
  12047. payload: {
  12048. sessionId: "session-1",
  12049. turnId: "turn_queue_b",
  12050. status: "finished",
  12051. },
  12052. });
  12053. await vi.waitFor(() =>
  12054. expect(
  12055. app.transcript
  12056. .snapshot()
  12057. .filter((cell) => cell.content === "Queued answer"),
  12058. ).toHaveLength(1),
  12059. );
  12060. await vi.waitFor(() =>
  12061. expect(app.transcript.get("turn-duration:turn_queue_b")).toMatchObject({
  12062. status: "succeeded",
  12063. durationMs: 3_000,
  12064. }),
  12065. );
  12066. const settledUi = app.tui.render(80).join("\n");
  12067. expect(settledUi).toContain("Completed in 3s");
  12068. expect(settledUi.indexOf("Completed in 3s")).toBeGreaterThan(
  12069. settledUi.indexOf("Queued answer"),
  12070. );
  12071. expect(settledUi).not.toContain("message waiting");
  12072. expect(settledUi).not.toContain("Next · after current response");
  12073. await app.stop();
  12074. });
  12075. it("records submitted drafts in editor history", async () => {
  12076. const terminal = new FakeTerminal();
  12077. const runtime = createRuntime();
  12078. const app = createTuiApp({
  12079. runtime,
  12080. terminal,
  12081. version: "0.1.0",
  12082. workspaceDir: "/workspace",
  12083. });
  12084. await app.ready;
  12085. app.editor.setText("Remember this draft");
  12086. app.editor.handleInput("\r");
  12087. await vi.waitFor(() =>
  12088. expect(runtime.sendMessage).toHaveBeenCalledTimes(1),
  12089. );
  12090. app.editor.handleInput("\u001b[A");
  12091. expect(app.editor.getText()).toBe("Remember this draft");
  12092. });
  12093. it("continues sending and switching sessions when draft cleanup fails", async () => {
  12094. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-warning-"));
  12095. const runtime = createRuntime();
  12096. const app = createTuiApp({
  12097. runtime,
  12098. terminal: new FakeTerminal(),
  12099. version: "0.1.0",
  12100. dataDir,
  12101. workspaceDir: "/workspace",
  12102. });
  12103. const flush = vi.spyOn(TuiDraftRecovery.prototype, "flush");
  12104. try {
  12105. await app.ready;
  12106. flush.mockRejectedValue(
  12107. new TuiDraftRecoveryError("cleanup", new Error("deletion denied")),
  12108. );
  12109. app.editor.setText("hello");
  12110. app.editor.handleInput("\r");
  12111. await vi.waitFor(() =>
  12112. expect(
  12113. app.transcript.snapshot().filter((cell) => cell.kind === "warning"),
  12114. ).toHaveLength(1),
  12115. );
  12116. const warnings = app.transcript
  12117. .snapshot()
  12118. .filter((cell) => cell.kind === "warning");
  12119. expect(warnings[0]?.content).toContain(
  12120. composerText("draftCleanupNextStep"),
  12121. );
  12122. expect(warnings[0]?.content).not.toContain(
  12123. composerText("draftRecoveryUnavailable"),
  12124. );
  12125. expect(warnings[0]?.content).toContain("deletion denied");
  12126. await vi.waitFor(() =>
  12127. expect(runtime.sendMessage).toHaveBeenCalledOnce(),
  12128. );
  12129. await vi.waitFor(() =>
  12130. expect(app.controller.snapshot().activeTurnId).toBeUndefined(),
  12131. );
  12132. await expect(app.openSession("session-2")).resolves.toBeUndefined();
  12133. expect(app.controller.snapshot().session?.sessionId).toBe("session-2");
  12134. app.editor.setText("after switching");
  12135. app.editor.handleInput("\r");
  12136. await vi.waitFor(() =>
  12137. expect(runtime.sendMessage).toHaveBeenCalledTimes(2),
  12138. );
  12139. await expect(app.stop()).resolves.toBeUndefined();
  12140. } finally {
  12141. await app.stop();
  12142. flush.mockRestore();
  12143. await rm(dataDir, { recursive: true, force: true });
  12144. }
  12145. });
  12146. it("does not read or restore a persisted Draft during TUI startup", async () => {
  12147. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-"));
  12148. try {
  12149. const first = createTuiApp({
  12150. runtime: createRuntime(),
  12151. terminal: new FakeTerminal(),
  12152. version: "0.1.0",
  12153. dataDir,
  12154. workspaceDir: "/workspace/recovery",
  12155. });
  12156. await first.ready;
  12157. first.editor.setText("/exit");
  12158. await first.stop();
  12159. const loadDraft = vi.spyOn(TuiDraftRecovery.prototype, "load");
  12160. const restored = createTuiApp({
  12161. runtime: createRuntime(),
  12162. terminal: new FakeTerminal(),
  12163. version: "0.1.0",
  12164. dataDir,
  12165. workspaceDir: "/workspace/recovery",
  12166. });
  12167. await restored.ready;
  12168. expect(loadDraft).not.toHaveBeenCalled();
  12169. expect(restored.editor.getText()).toBe("");
  12170. expect(restored.tui.render(80).join("\n")).not.toContain(
  12171. "Draft restored",
  12172. );
  12173. loadDraft.mockRestore();
  12174. restored.editor.setText("");
  12175. await restored.stop();
  12176. } finally {
  12177. await rm(dataDir, { recursive: true, force: true });
  12178. }
  12179. });
  12180. it("does not resume a persisted Draft during startup when login recovery is enabled", async () => {
  12181. const dataDir = await mkdtemp(join(tmpdir(), "mcode-login-restart-draft-"));
  12182. try {
  12183. const first = createTuiApp({
  12184. runtime: createRuntime(),
  12185. terminal: new FakeTerminal(),
  12186. version: "0.1.0",
  12187. dataDir,
  12188. workspaceDir: "/workspace/login-recovery",
  12189. });
  12190. await first.ready;
  12191. first.editor.setText("send after Global login");
  12192. await first.stop();
  12193. const restored = createTuiApp({
  12194. runtime: createRuntime(),
  12195. terminal: new FakeTerminal(),
  12196. version: "0.1.0",
  12197. dataDir,
  12198. workspaceDir: "/workspace/login-recovery",
  12199. resumeDraftAfterLogin: true,
  12200. });
  12201. await restored.ready;
  12202. restored.start();
  12203. expect(restored.editor.getText()).toBe("");
  12204. expect(restored.getSurface()).toBe("welcome");
  12205. expect(restored.tui.render(80).join("\n")).toContain(
  12206. "Tips for getting started",
  12207. );
  12208. await restored.stop();
  12209. } finally {
  12210. await rm(dataDir, { recursive: true, force: true });
  12211. }
  12212. });
  12213. it("keeps the submitted Draft recoverable when shutdown wins before Runtime admission", async () => {
  12214. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-pending-draft-"));
  12215. try {
  12216. const runtime = createRuntime();
  12217. vi.spyOn(runtime, "sendMessage").mockImplementation(
  12218. async function* sendMessage(
  12219. _req: SendMessageReq,
  12220. signal?: AbortSignal,
  12221. ) {
  12222. yield* [];
  12223. await new Promise<void>((_resolve, reject) => {
  12224. signal?.addEventListener(
  12225. "abort",
  12226. () => reject(new Error("admission aborted")),
  12227. {
  12228. once: true,
  12229. },
  12230. );
  12231. });
  12232. throw new Error("unreachable");
  12233. },
  12234. );
  12235. const first = createTuiApp({
  12236. runtime,
  12237. terminal: new FakeTerminal(),
  12238. version: "0.1.0",
  12239. dataDir,
  12240. workspaceDir: "/workspace/pending-recovery",
  12241. });
  12242. await first.ready;
  12243. first.editor.setText("recover me until Runtime accepts");
  12244. await new Promise((resolve) => setTimeout(resolve, 300));
  12245. first.editor.handleInput("\r");
  12246. await vi.waitFor(() =>
  12247. expect(runtime.sendMessage).toHaveBeenCalledOnce(),
  12248. );
  12249. await first.stop();
  12250. const restored = createTuiApp({
  12251. runtime: createRuntime(),
  12252. terminal: new FakeTerminal(),
  12253. version: "0.1.0",
  12254. dataDir,
  12255. workspaceDir: "/workspace/pending-recovery",
  12256. });
  12257. await restored.ready;
  12258. await restored.openSession("session-1");
  12259. expect(restored.editor.getText()).toBe(
  12260. "recover me until Runtime accepts",
  12261. );
  12262. const rendered = restored.tui.render(80).join("\n");
  12263. expect(rendered).toContain("recover me until Runtime accepts");
  12264. expect(rendered).not.toContain("Message kept under Failed");
  12265. await restored.stop();
  12266. } finally {
  12267. await rm(dataDir, { recursive: true, force: true });
  12268. }
  12269. });
  12270. it("does not restore a submitted Draft after Runtime accepts the turn", async () => {
  12271. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-accepted-draft-"));
  12272. try {
  12273. const runtime = createRuntime();
  12274. vi.mocked(runtime.sendMessage).mockImplementation(
  12275. async function* sendMessage(
  12276. _req: SendMessageReq,
  12277. signal?: AbortSignal,
  12278. ) {
  12279. await new Promise<void>((resolve) => {
  12280. signal?.addEventListener("abort", resolve, { once: true });
  12281. });
  12282. yield { type: "done" };
  12283. },
  12284. );
  12285. const first = createTuiApp({
  12286. runtime,
  12287. terminal: new FakeTerminal(),
  12288. version: "0.1.0",
  12289. dataDir,
  12290. workspaceDir: "/workspace/accepted-recovery",
  12291. });
  12292. await first.ready;
  12293. first.editor.setText("already accepted by Runtime");
  12294. await new Promise((resolve) => setTimeout(resolve, 300));
  12295. first.editor.handleInput("\r");
  12296. await vi.waitFor(() =>
  12297. expect(runtime.sendMessage).toHaveBeenCalledOnce(),
  12298. );
  12299. await first.stop();
  12300. const restored = createTuiApp({
  12301. runtime: createRuntime(),
  12302. terminal: new FakeTerminal(),
  12303. version: "0.1.0",
  12304. dataDir,
  12305. workspaceDir: "/workspace/accepted-recovery",
  12306. });
  12307. await restored.ready;
  12308. expect(restored.editor.getText()).toBe("");
  12309. await restored.stop();
  12310. } finally {
  12311. await rm(dataDir, { recursive: true, force: true });
  12312. }
  12313. });
  12314. it("serializes rapid Session switches without mixing their Drafts", async () => {
  12315. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-"));
  12316. try {
  12317. const app = createTuiApp({
  12318. runtime: createRuntime(),
  12319. terminal: new FakeTerminal(),
  12320. version: "0.1.0",
  12321. dataDir,
  12322. workspaceDir: "/workspace/recovery",
  12323. });
  12324. await app.ready;
  12325. await app.openSession("session-a");
  12326. app.editor.setText("Draft for Session A");
  12327. await app.openSession("session-b");
  12328. app.editor.setText("Draft for Session B");
  12329. await Promise.all([
  12330. app.openSession("session-a"),
  12331. app.openSession("session-b"),
  12332. ]);
  12333. expect(app.controller.snapshot().session?.sessionId).toBe("session-b");
  12334. expect(app.editor.getText()).toBe("Draft for Session B");
  12335. await app.openSession("session-a");
  12336. expect(app.editor.getText()).toBe("Draft for Session A");
  12337. await app.openSession("session-b");
  12338. expect(app.editor.getText()).toBe("Draft for Session B");
  12339. await app.stop();
  12340. } finally {
  12341. await rm(dataDir, { recursive: true, force: true });
  12342. }
  12343. });
  12344. it("moves to the new-session Draft namespace after archiving the current Session", async () => {
  12345. const dataDir = await mkdtemp(join(tmpdir(), "mcode-app-draft-"));
  12346. try {
  12347. const app = createTuiApp({
  12348. runtime: createRuntime(),
  12349. terminal: new FakeTerminal(),
  12350. version: "0.1.0",
  12351. dataDir,
  12352. workspaceDir: "/workspace/recovery",
  12353. });
  12354. await app.ready;
  12355. await app.openSession("session-a");
  12356. app.editor.setText("Archived Session Draft");
  12357. await app.submit("/archive");
  12358. app.editor.setText("Fresh Session Draft");
  12359. await app.openSession("session-a");
  12360. expect(app.editor.getText()).toBe("Archived Session Draft");
  12361. await app.submit("/new");
  12362. expect(app.editor.getText()).toBe("Fresh Session Draft");
  12363. await app.stop();
  12364. } finally {
  12365. await rm(dataDir, { recursive: true, force: true });
  12366. }
  12367. });
  12368. });