acp-agent.test.ts 218 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276
  1. import * as acp from '@agentclientprotocol/sdk';
  2. import { describe, expect, it, vi } from 'vitest';
  3. import { TUI_ACP_AVAILABLE_COMMANDS } from '../../src/acp/commands.js';
  4. import { createTuiAcpAgent } from '../../src/acp/agent.js';
  5. import { TuiAcpPromptContinuation } from '../../src/acp/prompt-continuation.js';
  6. import type { TuiAcpRuntime } from '../../src/acp/runtime.js';
  7. import type { TuiContextSnapshotResponse, TuiRuntimeDiagnostics } from '../../src/runtime/port.js';
  8. import type { TuiStreamEvent } from '../../src/runtime/stream-events.js';
  9. import type {
  10. TuiMcpServer,
  11. TuiModel,
  12. TuiSessionUsage,
  13. TuiSkillList,
  14. } from '../../src/types/runtime-models.js';
  15. import type { TuiRuntimeEvent } from '../../src/types/runtime-events.js';
  16. function createRuntime(
  17. events: readonly TuiStreamEvent[] = [],
  18. options: {
  19. holdRunUntilAbort?: boolean;
  20. holdRunAfterEvents?: boolean;
  21. accountStatus?: {
  22. status: 'ready' | 'needs-login' | 'warning' | 'unknown';
  23. modelSource?: 'token-plan' | 'byok';
  24. authMode?: string;
  25. managedTokenPresent?: boolean;
  26. warnings: string[];
  27. };
  28. models?: readonly TuiModel[];
  29. runtimeDiagnostics?: TuiRuntimeDiagnostics;
  30. contextSnapshot?: TuiContextSnapshotResponse;
  31. sessionUsage?: TuiSessionUsage;
  32. skills?: TuiSkillList;
  33. mcpServers?: readonly TuiMcpServer[];
  34. goalEnabled?: boolean;
  35. } = {},
  36. ) {
  37. const queuedRuntimeEvents: TuiRuntimeEvent[] = [];
  38. let deliverRuntimeEvent: ((event: TuiRuntimeEvent | undefined) => void) | undefined;
  39. let aborted = false;
  40. let releaseRun: (() => void) | undefined;
  41. const runGate =
  42. options.holdRunUntilAbort || options.holdRunAfterEvents
  43. ? new Promise<void>((resolve) => {
  44. releaseRun = resolve;
  45. })
  46. : Promise.resolve();
  47. const nextRuntimeEvent = (signal: AbortSignal): Promise<TuiRuntimeEvent | undefined> => {
  48. const queued = queuedRuntimeEvents.shift();
  49. if (queued) return Promise.resolve(queued);
  50. return new Promise((resolve) => {
  51. deliverRuntimeEvent = resolve;
  52. signal.addEventListener('abort', () => resolve(undefined), { once: true });
  53. });
  54. };
  55. const createSession = vi.fn(async ({ workspaceDir }: { workspaceDir: string }) => ({
  56. sessionId: 'session-1',
  57. workspaceDir,
  58. }));
  59. const clearSessionMcpServers = vi.fn(async () => undefined);
  60. const configureSessionMcpServers = vi.fn(async () => undefined);
  61. const deleteSession = vi.fn(async () => undefined);
  62. const listSessionPage = vi.fn(async () => ({ sessions: [], hasMore: false }));
  63. const getSession = vi.fn(async (sessionId: string) => ({
  64. sessionId,
  65. workspaceDir: '/workspace',
  66. }));
  67. const listMessagePage = vi.fn(async () => ({ messages: [], hasMore: false }));
  68. const sendMessageCall = vi.fn(async () => undefined);
  69. const abortSession = vi.fn(async () => {
  70. aborted = true;
  71. releaseRun?.();
  72. return true;
  73. });
  74. const listModels = vi.fn(async () => [...(options.models ?? [])]);
  75. const selectModel = vi.fn(async () => true);
  76. const selectSessionModel = vi.fn(async () => true);
  77. const getContextSnapshot = vi.fn(async () =>
  78. Promise.resolve(options.contextSnapshot ?? { status: 'empty' as const }),
  79. );
  80. const getSessionUsage = vi.fn(async () => options.sessionUsage ?? {});
  81. const listSkills = vi.fn<TuiAcpRuntime['listSkills']>(async () => options.skills ?? {});
  82. const listMcpServers = vi.fn(async () => [...(options.mcpServers ?? [])]);
  83. const requestCompaction = vi.fn(async () => ({ success: true }));
  84. const getPlanModeCapabilities = vi.fn(async () => ({ entryEnabled: true }));
  85. const getPermissionMode = vi.fn(async () => 'default' as const);
  86. const setPermissionMode = vi.fn(
  87. async (mode: 'default' | 'auto' | 'bypassPermissions' | 'off') => mode,
  88. );
  89. const steer = vi.fn(async (input: Parameters<TuiAcpRuntime['steer']>[0]) => {
  90. const result = { turnId: 'turn-active', mode: 'steered' as const };
  91. await input.preDelivery?.accept(result);
  92. return result;
  93. });
  94. const listQueuedMessages = vi.fn(async () => []);
  95. const enqueueMessage = vi.fn(async () => ({ itemId: 'queue-1', position: 1 }));
  96. const updateQueuedMessageContent = vi.fn(async () => undefined);
  97. const deleteQueuedMessage = vi.fn(async () => undefined);
  98. const steerQueuedMessage = vi.fn(async () => ({ queueItemId: 'queue-1', turnId: 'turn-2' }));
  99. const getGoal = vi.fn(async () => undefined);
  100. const createGoal = vi.fn(async ({ sessionId, objective, tokenBudget }) => ({
  101. goalId: 'goal-1',
  102. sessionId,
  103. objective,
  104. status: 'active' as const,
  105. createdAt: 1,
  106. updatedAt: 1,
  107. tokensUsed: 0,
  108. timeUsedSeconds: 0,
  109. tokenBudget: tokenBudget ?? null,
  110. hasKickoffAttachments: false,
  111. }));
  112. const patchGoal = vi.fn(async (sessionId, patch) => ({
  113. goalId: 'goal-1',
  114. sessionId,
  115. objective: patch.objective ?? 'Ship ACP',
  116. status: patch.status ?? ('active' as const),
  117. createdAt: 1,
  118. updatedAt: 2,
  119. tokensUsed: 0,
  120. timeUsedSeconds: 0,
  121. tokenBudget: patch.tokenBudget ?? null,
  122. hasKickoffAttachments: false,
  123. }));
  124. const clearGoal = vi.fn(async () => true);
  125. const getDelegationSnapshot = vi.fn(async (rootSessionId: string) => ({
  126. schemaVersion: 1 as const,
  127. rootSessionId,
  128. members: [],
  129. }));
  130. const stopDelegation = vi.fn(async (rootSessionId: string) => ({
  131. schemaVersion: 1 as const,
  132. rootSessionId,
  133. rootStopped: true,
  134. stoppedSessionIds: [],
  135. activeSessionIds: [],
  136. failedSessionIds: [],
  137. }));
  138. const getSessionForkOptions = vi.fn(async () => ({
  139. canFork: true,
  140. worktreeVisible: false,
  141. worktreeEligible: false,
  142. }));
  143. const forkSession = vi.fn(async () => ({
  144. session: { sessionId: 'session-fork', workspaceDir: '/workspace' },
  145. }));
  146. const runtime = {
  147. createSession,
  148. configureSessionMcpServers,
  149. clearSessionMcpServers,
  150. deleteSession,
  151. listSessionPage,
  152. getSession,
  153. listMessagePage,
  154. getAccountStatus: vi.fn(
  155. async () => options.accountStatus ?? { status: 'ready' as const, warnings: [] },
  156. ),
  157. getRuntimeDiagnostics: vi.fn(async () => options.runtimeDiagnostics ?? { warnings: [] }),
  158. getContextSnapshot,
  159. getSessionUsage,
  160. listSkills,
  161. listMcpServers,
  162. requestCompaction,
  163. getPlanModeCapabilities,
  164. getPermissionMode,
  165. setPermissionMode,
  166. steer,
  167. listQueuedMessages,
  168. enqueueMessage,
  169. updateQueuedMessageContent,
  170. deleteQueuedMessage,
  171. steerQueuedMessage,
  172. isGoalEnabled: vi.fn(() => options.goalEnabled ?? true),
  173. getGoal,
  174. createGoal,
  175. patchGoal,
  176. clearGoal,
  177. getDelegationSnapshot,
  178. stopDelegation,
  179. getSessionForkOptions,
  180. forkSession,
  181. sendMessage: vi.fn(async function* sendMessage(req, signal) {
  182. await sendMessageCall(req, signal);
  183. if (!options.holdRunAfterEvents) {
  184. await runGate;
  185. if (aborted) {
  186. yield { type: 'session-status', status: 'aborted', turnId: req.turnId } as const;
  187. return;
  188. }
  189. }
  190. for (const event of events) yield event;
  191. if (options.holdRunAfterEvents) {
  192. await runGate;
  193. if (aborted) {
  194. yield { type: 'session-status', status: 'aborted', turnId: req.turnId } as const;
  195. }
  196. }
  197. }),
  198. abortSession,
  199. listModels,
  200. selectModel,
  201. selectSessionModel,
  202. replyPermission: vi.fn(async () => true),
  203. replyQuestionnaire: vi.fn(async () => true),
  204. dismissQuestionnaire: vi.fn(async () => true),
  205. watchEvents: vi.fn((signal: AbortSignal) =>
  206. (async function* runtimeEvents() {
  207. while (!signal.aborted) {
  208. const event = await nextRuntimeEvent(signal);
  209. if (!event) return;
  210. yield event;
  211. }
  212. })(),
  213. ),
  214. watchSessionTurn: vi.fn(() =>
  215. (async function* sessionEvents() {
  216. yield { type: 'session-status', status: 'finished' } as const;
  217. })(),
  218. ),
  219. };
  220. return {
  221. runtime: runtime as unknown as TuiAcpRuntime,
  222. createSession,
  223. configureSessionMcpServers,
  224. clearSessionMcpServers,
  225. deleteSession,
  226. listSessionPage,
  227. getSession,
  228. listMessagePage,
  229. sendMessage: sendMessageCall,
  230. abortSession,
  231. listModels,
  232. selectModel,
  233. selectSessionModel,
  234. getContextSnapshot,
  235. getSessionUsage,
  236. listSkills,
  237. listMcpServers,
  238. requestCompaction,
  239. getPlanModeCapabilities,
  240. getPermissionMode,
  241. setPermissionMode,
  242. steer,
  243. listQueuedMessages,
  244. enqueueMessage,
  245. updateQueuedMessageContent,
  246. deleteQueuedMessage,
  247. steerQueuedMessage,
  248. getGoal,
  249. createGoal,
  250. patchGoal,
  251. clearGoal,
  252. getDelegationSnapshot,
  253. stopDelegation,
  254. getSessionForkOptions,
  255. forkSession,
  256. replyPermission: runtime.replyPermission,
  257. replyQuestionnaire: runtime.replyQuestionnaire,
  258. dismissQuestionnaire: runtime.dismissQuestionnaire,
  259. emitRuntimeEvent(event: TuiRuntimeEvent) {
  260. const deliver = deliverRuntimeEvent;
  261. deliverRuntimeEvent = undefined;
  262. if (deliver) deliver(event);
  263. else queuedRuntimeEvents.push(event);
  264. },
  265. };
  266. }
  267. describe('MiniMax Code ACP agent', () => {
  268. it.each(['new', 'load', 'resume', 'fork'] as const)(
  269. 'advertises session Skills on %s and forwards Skill instructions to the Runtime',
  270. async (method) => {
  271. const { runtime, listSkills, sendMessage, getSession, forkSession } = createRuntime(
  272. [{ type: 'session-status', status: 'finished' }],
  273. {
  274. skills: {
  275. skills: [
  276. {
  277. name: 'matt:review',
  278. description: 'Review changes',
  279. enabled: true,
  280. },
  281. { name: 'repo-test', displayDescription: 'Test the project' },
  282. { name: 'MATT:REVIEW', description: 'Duplicate' },
  283. {
  284. name: 'Compact',
  285. description: 'Must not replace a native command',
  286. },
  287. { name: 'disabled', enabled: false },
  288. { name: 'invalid/name' },
  289. { name: 'invalid name' },
  290. { name: '' },
  291. { name: 'x'.repeat(129) },
  292. { name: 'bad\u001b[31m' },
  293. ],
  294. },
  295. },
  296. );
  297. getSession.mockImplementation(async (sessionId) => ({
  298. sessionId,
  299. workspaceDir: '/project',
  300. agentName: 'reviewer',
  301. }));
  302. forkSession.mockResolvedValue({
  303. session: {
  304. sessionId: 'session-fork',
  305. workspaceDir: '/project',
  306. agentName: 'reviewer',
  307. },
  308. });
  309. const updates: acp.SessionNotification[] = [];
  310. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  311. const client = acp
  312. .client({ name: 'zed' })
  313. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
  314. await client.connectWith(agent, async (connection) => {
  315. await connection.request(acp.methods.agent.initialize, {
  316. protocolVersion: acp.PROTOCOL_VERSION,
  317. clientCapabilities: {},
  318. });
  319. const response = await connection.request(acp.methods.agent.session[method], {
  320. sessionId: 'session-1',
  321. cwd: '/project',
  322. mcpServers: [],
  323. });
  324. const sessionId = 'sessionId' in response ? response.sessionId : 'session-1';
  325. const roster = () =>
  326. updates
  327. .filter(
  328. (update) =>
  329. update.sessionId === sessionId &&
  330. update.update.sessionUpdate === 'available_commands_update',
  331. )
  332. .at(-1)?.update;
  333. const expected = {
  334. sessionUpdate: 'available_commands_update',
  335. availableCommands: [
  336. ...TUI_ACP_AVAILABLE_COMMANDS,
  337. {
  338. name: 'matt:review',
  339. description: '[Skill] Review changes',
  340. input: { hint: '[instructions]' },
  341. },
  342. {
  343. name: 'repo-test',
  344. description: '[Skill] Test the project',
  345. input: { hint: '[instructions]' },
  346. },
  347. ],
  348. };
  349. await vi.waitFor(() => expect(roster()).toEqual(expected));
  350. expect(listSkills).toHaveBeenCalledWith(
  351. method === 'new' ? undefined : 'reviewer',
  352. undefined,
  353. '/project',
  354. );
  355. // A delayed listener retry must retain the complete Skill roster.
  356. await new Promise((resolve) => setTimeout(resolve, 130));
  357. expect(roster()).toEqual(expected);
  358. await expect(
  359. connection.request(acp.methods.agent.session.prompt, {
  360. sessionId,
  361. prompt: [{ type: 'text', text: '/matt:review focus on error handling' }],
  362. }),
  363. ).resolves.toEqual({ stopReason: 'end_turn' });
  364. expect(sendMessage).toHaveBeenCalledWith(
  365. expect.objectContaining({
  366. id: sessionId,
  367. content: '/matt:review focus on error handling',
  368. }),
  369. expect.any(AbortSignal),
  370. );
  371. });
  372. },
  373. );
  374. it.each(['reject', 'stall'] as const)(
  375. 'keeps native commands available when Skill discovery can %s',
  376. async (failure) => {
  377. const { runtime, listSkills } = createRuntime();
  378. if (failure === 'reject') listSkills.mockRejectedValue(new Error('Unavailable'));
  379. else listSkills.mockImplementation(() => new Promise(() => undefined));
  380. const updates: acp.SessionNotification[] = [];
  381. const client = acp
  382. .client({ name: 'zed' })
  383. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
  384. await client.connectWith(
  385. createTuiAcpAgent({ runtime, version: '1.2.3' }),
  386. async (connection) => {
  387. await connection.request(acp.methods.agent.initialize, {
  388. protocolVersion: acp.PROTOCOL_VERSION,
  389. clientCapabilities: {},
  390. });
  391. const { sessionId } = await connection.request(acp.methods.agent.session.new, {
  392. cwd: '/workspace',
  393. mcpServers: [],
  394. });
  395. await vi.waitFor(() =>
  396. expect(updates).toContainEqual({
  397. sessionId,
  398. update: {
  399. sessionUpdate: 'available_commands_update',
  400. availableCommands: TUI_ACP_AVAILABLE_COMMANDS,
  401. },
  402. }),
  403. );
  404. await expect(
  405. connection.request(acp.methods.agent.session.prompt, {
  406. sessionId,
  407. prompt: [{ type: 'text', text: '/help' }],
  408. }),
  409. ).resolves.toEqual({ stopReason: 'end_turn' });
  410. },
  411. );
  412. },
  413. );
  414. it.each(['close', 'resume'] as const)(
  415. 'ignores late Skill discovery after session %s',
  416. async (method) => {
  417. const { runtime, listSkills } = createRuntime([], {
  418. skills: { skills: [{ name: 'current' }] },
  419. });
  420. let resolveSkills!: (skills: TuiSkillList) => void;
  421. listSkills.mockImplementationOnce(
  422. () =>
  423. new Promise((resolve) => {
  424. resolveSkills = resolve;
  425. }),
  426. );
  427. const updates: acp.SessionNotification[] = [];
  428. const client = acp
  429. .client({ name: 'zed' })
  430. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
  431. await client.connectWith(
  432. createTuiAcpAgent({ runtime, version: '1.2.3' }),
  433. async (connection) => {
  434. await connection.request(acp.methods.agent.initialize, {
  435. protocolVersion: acp.PROTOCOL_VERSION,
  436. clientCapabilities: {},
  437. });
  438. const { sessionId } = await connection.request(acp.methods.agent.session.new, {
  439. cwd: '/workspace',
  440. mcpServers: [],
  441. });
  442. await vi.waitFor(() => expect(listSkills).toHaveBeenCalledOnce());
  443. await connection.request(acp.methods.agent.session[method], {
  444. sessionId,
  445. cwd: '/workspace',
  446. mcpServers: [],
  447. });
  448. if (method === 'resume') {
  449. await vi.waitFor(() =>
  450. expect(updates).toContainEqual({
  451. sessionId,
  452. update: {
  453. sessionUpdate: 'available_commands_update',
  454. availableCommands: [
  455. ...TUI_ACP_AVAILABLE_COMMANDS,
  456. {
  457. name: 'current',
  458. description: '[Skill]',
  459. input: { hint: '[instructions]' },
  460. },
  461. ],
  462. },
  463. }),
  464. );
  465. }
  466. resolveSkills({ skills: [{ name: 'stale' }] });
  467. const count = updates.length;
  468. await new Promise((resolve) => setTimeout(resolve, 130));
  469. const rosters = updates.flatMap(({ update }) =>
  470. update.sessionUpdate === 'available_commands_update' ? update.availableCommands : [],
  471. );
  472. expect(rosters.some((command) => command.name === 'stale')).toBe(false);
  473. if (method === 'close') expect(updates).toHaveLength(count);
  474. },
  475. );
  476. },
  477. );
  478. it('advertises and executes native help and model commands without starting an Agent turn', async () => {
  479. const { runtime, sendMessage, listModels, selectModel } = createRuntime([], {
  480. models: [
  481. {
  482. providerId: 'minimax',
  483. modelId: 'm3',
  484. displayName: 'MiniMax M3',
  485. selected: true,
  486. },
  487. { providerId: 'custom', modelId: 'coder', displayName: 'Coder' },
  488. ],
  489. });
  490. const updates: acp.SessionNotification[] = [];
  491. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  492. const client = acp
  493. .client({ name: 'zed' })
  494. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
  495. await client.connectWith(agent, async (connection) => {
  496. await connection.request(acp.methods.agent.initialize, {
  497. protocolVersion: acp.PROTOCOL_VERSION,
  498. clientCapabilities: {},
  499. });
  500. const session = await connection.request(acp.methods.agent.session.new, {
  501. cwd: '/workspace',
  502. mcpServers: [],
  503. });
  504. await vi.waitFor(() =>
  505. expect(updates).toContainEqual({
  506. sessionId: session.sessionId,
  507. update: {
  508. sessionUpdate: 'available_commands_update',
  509. availableCommands: [
  510. {
  511. name: 'help',
  512. description: 'Show available commands',
  513. },
  514. {
  515. name: 'new',
  516. description: 'Start a fresh session in the current workspace',
  517. },
  518. {
  519. name: 'model',
  520. description: 'Choose a model',
  521. input: { hint: '[provider/model[#variant]]' },
  522. },
  523. {
  524. name: 'status',
  525. description: 'Show account and model status',
  526. },
  527. {
  528. name: 'doctor',
  529. description: 'Check the local config file',
  530. },
  531. {
  532. name: 'context',
  533. description: 'Show the Runtime-owned context snapshot',
  534. },
  535. {
  536. name: 'skills',
  537. description: 'List built-in and user Skills',
  538. input: { hint: '[filter]' },
  539. },
  540. {
  541. name: 'mcp',
  542. description: 'Inspect MCP capabilities and project configuration',
  543. input: { hint: '[filter]' },
  544. },
  545. {
  546. name: 'usage',
  547. description: 'Show session usage',
  548. },
  549. {
  550. name: 'compact',
  551. description: 'Shorten the active conversation',
  552. input: { hint: '[instructions]' },
  553. },
  554. ],
  555. },
  556. }),
  557. );
  558. await expect(
  559. connection.request(acp.methods.agent.session.prompt, {
  560. sessionId: session.sessionId,
  561. prompt: [{ type: 'text', text: '/help' }],
  562. }),
  563. ).resolves.toEqual({ stopReason: 'end_turn' });
  564. await expect(
  565. connection.request(acp.methods.agent.session.prompt, {
  566. sessionId: session.sessionId,
  567. prompt: [{ type: 'text', text: '/model' }],
  568. }),
  569. ).resolves.toEqual({ stopReason: 'end_turn' });
  570. await expect(
  571. connection.request(acp.methods.agent.session.prompt, {
  572. sessionId: session.sessionId,
  573. prompt: [{ type: 'text', text: '/model custom/coder' }],
  574. }),
  575. ).resolves.toEqual({ stopReason: 'end_turn' });
  576. });
  577. expect(listModels).toHaveBeenCalledTimes(3);
  578. expect(listModels).toHaveBeenNthCalledWith(1, 'session-1');
  579. expect(listModels).toHaveBeenNthCalledWith(2, 'session-1');
  580. expect(listModels).toHaveBeenNthCalledWith(3, 'session-1');
  581. expect(selectModel).toHaveBeenCalledWith(
  582. { providerId: 'custom', modelId: 'coder' },
  583. 'session-1',
  584. );
  585. expect(sendMessage).not.toHaveBeenCalled();
  586. expect(updates).toEqual(
  587. expect.arrayContaining([
  588. {
  589. sessionId: 'session-1',
  590. update: {
  591. sessionUpdate: 'agent_message_chunk',
  592. content: {
  593. type: 'text',
  594. text: [
  595. 'Available commands:',
  596. '- /help — Show available commands',
  597. '- /new — Start a fresh session in the current workspace',
  598. '- /model [provider/model[#variant]] — Choose a model',
  599. '- /status — Show account and model status',
  600. '- /doctor — Check the local config file',
  601. '- /context — Show the Runtime-owned context snapshot',
  602. '- /skills [filter] — List built-in and user Skills',
  603. '- /mcp [filter] — Inspect MCP capabilities and project configuration',
  604. '- /usage — Show session usage',
  605. '- /compact [instructions] — Shorten the active conversation',
  606. ].join('\n'),
  607. },
  608. },
  609. },
  610. {
  611. sessionId: 'session-1',
  612. update: {
  613. sessionUpdate: 'agent_message_chunk',
  614. content: {
  615. type: 'text',
  616. text: [
  617. 'Available models:',
  618. '- minimax/m3 (MiniMax M3) [selected]',
  619. '- custom/coder (Coder)',
  620. '',
  621. 'Use `/model <provider/model[#variant]>` to switch.',
  622. ].join('\n'),
  623. },
  624. },
  625. },
  626. {
  627. sessionId: 'session-1',
  628. update: {
  629. sessionUpdate: 'agent_message_chunk',
  630. content: { type: 'text', text: 'Model selected: custom/coder' },
  631. },
  632. },
  633. ]),
  634. );
  635. });
  636. it('compacts the Runtime session and reports unchanged conversations locally', async () => {
  637. const { runtime, sendMessage, requestCompaction } = createRuntime();
  638. requestCompaction
  639. .mockResolvedValueOnce({ success: false, code: 'NOTHING_TO_COMPACT' })
  640. .mockResolvedValueOnce({
  641. success: true,
  642. messagesBefore: 20,
  643. messagesAfter: 8,
  644. tokensBefore: 12_000,
  645. tokensAfter: 5_000,
  646. });
  647. const updates: acp.SessionNotification[] = [];
  648. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  649. const client = acp
  650. .client({ name: 'zed' })
  651. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
  652. await client.connectWith(agent, async (connection) => {
  653. await connection.request(acp.methods.agent.initialize, {
  654. protocolVersion: acp.PROTOCOL_VERSION,
  655. clientCapabilities: {},
  656. });
  657. const session = await connection.request(acp.methods.agent.session.new, {
  658. cwd: '/workspace',
  659. mcpServers: [],
  660. });
  661. for (const text of ['/compact', '/compact keep decisions']) {
  662. await expect(
  663. connection.request(acp.methods.agent.session.prompt, {
  664. sessionId: session.sessionId,
  665. prompt: [{ type: 'text', text }],
  666. }),
  667. ).resolves.toEqual({ stopReason: 'end_turn' });
  668. }
  669. });
  670. expect(requestCompaction).toHaveBeenNthCalledWith(1, 'session-1', undefined, undefined);
  671. expect(requestCompaction).toHaveBeenNthCalledWith(2, 'session-1', undefined, 'keep decisions');
  672. expect(sendMessage).not.toHaveBeenCalled();
  673. const texts = updates.flatMap((notification) =>
  674. notification.update.sessionUpdate === 'agent_message_chunk' &&
  675. notification.update.content.type === 'text'
  676. ? [notification.update.content.text]
  677. : [],
  678. );
  679. expect(texts).toEqual(
  680. expect.arrayContaining([
  681. 'No compaction is needed for this conversation yet.',
  682. ['Compaction completed.', 'Messages: 20 → 8', 'Tokens: 12,000 → 5,000'].join('\n'),
  683. ]),
  684. );
  685. });
  686. it('renders Runtime-backed context, skills, MCP, and usage inspections', async () => {
  687. const {
  688. runtime,
  689. sendMessage,
  690. getContextSnapshot,
  691. getSessionUsage,
  692. listSkills,
  693. listMcpServers,
  694. } = createRuntime([], {
  695. contextSnapshot: {
  696. status: 'live',
  697. model: { provider: 'minimax', id: 'm3', contextWindow: 10_000 },
  698. contextUsage: {
  699. contextWindowTokens: 10_000,
  700. usedTokens: 4_000,
  701. totalCountSource: 'LOCAL_ESTIMATE',
  702. components: [
  703. { kind: 'SYSTEM_PROMPT', tokens: 1_000 },
  704. { kind: 'MESSAGES', tokens: 3_000 },
  705. ],
  706. },
  707. compaction: { state: 'never' },
  708. },
  709. sessionUsage: {
  710. summary: {
  711. inputTokens: 100,
  712. outputTokens: 25,
  713. reasoningTokens: 5,
  714. cacheReadTokens: 20,
  715. totalTokens: 150,
  716. turns: 2,
  717. costUsd: 0.0123,
  718. },
  719. },
  720. skills: {
  721. skills: [
  722. { name: 'repo-review', description: 'Review repository changes' },
  723. { name: 'tdd', displayName: 'TDD', displayDescription: 'Develop test-first' },
  724. ],
  725. hasMore: true,
  726. },
  727. mcpServers: [
  728. { name: 'github', enabled: true, transport: 'stdio', description: 'GitHub tools' },
  729. { name: 'disabled-one', enabled: false, transport: 'http' },
  730. ],
  731. });
  732. const updates: acp.SessionNotification[] = [];
  733. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  734. const client = acp
  735. .client({ name: 'zed' })
  736. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
  737. await client.connectWith(agent, async (connection) => {
  738. await connection.request(acp.methods.agent.initialize, {
  739. protocolVersion: acp.PROTOCOL_VERSION,
  740. clientCapabilities: {},
  741. });
  742. const session = await connection.request(acp.methods.agent.session.new, {
  743. cwd: '/workspace',
  744. mcpServers: [],
  745. });
  746. for (const text of ['/context', '/skills review', '/mcp git', '/usage']) {
  747. await expect(
  748. connection.request(acp.methods.agent.session.prompt, {
  749. sessionId: session.sessionId,
  750. prompt: [{ type: 'text', text }],
  751. }),
  752. ).resolves.toEqual({ stopReason: 'end_turn' });
  753. }
  754. });
  755. expect(getContextSnapshot).toHaveBeenCalledWith('session-1');
  756. expect(listSkills).toHaveBeenCalledWith(undefined, 'review', '/workspace');
  757. expect(listMcpServers).toHaveBeenCalledWith('git', 'session-1');
  758. expect(getSessionUsage).toHaveBeenCalledWith('session-1');
  759. expect(sendMessage).not.toHaveBeenCalled();
  760. const texts = updates.flatMap((notification) =>
  761. notification.update.sessionUpdate === 'agent_message_chunk' &&
  762. notification.update.content.type === 'text'
  763. ? [notification.update.content.text]
  764. : [],
  765. );
  766. expect(texts).toEqual(
  767. expect.arrayContaining([
  768. [
  769. 'Context: live',
  770. 'Model: minimax/m3',
  771. 'Budget: 4,000 / 10,000 tokens (40%)',
  772. 'Compaction: never',
  773. 'Components:',
  774. '- System prompt: 1,000 tokens',
  775. '- Messages: 3,000 tokens',
  776. ].join('\n'),
  777. [
  778. 'Skills · 2+',
  779. '- repo-review — Review repository changes',
  780. '- TDD — Develop test-first',
  781. 'More Skills exist; narrow the list with /skills <filter>.',
  782. ].join('\n'),
  783. [
  784. 'MCP servers · 2',
  785. '- github — enabled · stdio — GitHub tools',
  786. '- disabled-one — disabled · http',
  787. ].join('\n'),
  788. [
  789. 'Session usage:',
  790. 'Input tokens: 100',
  791. 'Output tokens: 25',
  792. 'Reasoning tokens: 5',
  793. 'Cache read tokens: 20',
  794. 'Cache write tokens: 0',
  795. 'Total tokens: 150',
  796. 'Turns: 2',
  797. 'Cost: $0.0123',
  798. ].join('\n'),
  799. ]),
  800. );
  801. });
  802. it('shows Runtime diagnostics for /doctor without exposing credential values', async () => {
  803. const { runtime, sendMessage } = createRuntime([], {
  804. runtimeDiagnostics: {
  805. status: 'ready',
  806. configPath: '/workspace/config.yaml',
  807. configPresent: true,
  808. defaultModel: 'minimax/m3',
  809. providerId: 'minimax',
  810. authMode: 'managed-login',
  811. managedTokenPresent: true,
  812. apiKeyPresent: false,
  813. warnings: [],
  814. },
  815. });
  816. const updates: acp.SessionNotification[] = [];
  817. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  818. const client = acp
  819. .client({ name: 'zed' })
  820. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
  821. await client.connectWith(agent, async (connection) => {
  822. await connection.request(acp.methods.agent.initialize, {
  823. protocolVersion: acp.PROTOCOL_VERSION,
  824. clientCapabilities: {},
  825. });
  826. const session = await connection.request(acp.methods.agent.session.new, {
  827. cwd: '/workspace',
  828. mcpServers: [],
  829. });
  830. await expect(
  831. connection.request(acp.methods.agent.session.prompt, {
  832. sessionId: session.sessionId,
  833. prompt: [{ type: 'text', text: '/doctor' }],
  834. }),
  835. ).resolves.toEqual({ stopReason: 'end_turn' });
  836. });
  837. expect(sendMessage).not.toHaveBeenCalled();
  838. expect(updates).toContainEqual({
  839. sessionId: 'session-1',
  840. update: {
  841. sessionUpdate: 'agent_message_chunk',
  842. content: {
  843. type: 'text',
  844. text: [
  845. 'Configuration status: ready',
  846. 'Config path: /workspace/config.yaml',
  847. 'Config file: present',
  848. 'Default model: minimax/m3',
  849. 'Provider: minimax',
  850. 'Authentication: managed-login',
  851. 'Managed token: present',
  852. 'API key: missing',
  853. 'Warnings: none',
  854. ].join('\n'),
  855. },
  856. },
  857. });
  858. });
  859. it('shows account and model status from Runtime without starting an Agent turn', async () => {
  860. const { runtime, sendMessage, listModels } = createRuntime([], {
  861. accountStatus: {
  862. status: 'ready',
  863. modelSource: 'token-plan',
  864. authMode: 'managed-login',
  865. managedTokenPresent: true,
  866. warnings: [],
  867. },
  868. models: [
  869. {
  870. providerId: 'minimax',
  871. modelId: 'm3',
  872. displayName: 'MiniMax M3',
  873. selected: true,
  874. },
  875. ],
  876. });
  877. const updates: acp.SessionNotification[] = [];
  878. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  879. const client = acp
  880. .client({ name: 'zed' })
  881. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
  882. await client.connectWith(agent, async (connection) => {
  883. await connection.request(acp.methods.agent.initialize, {
  884. protocolVersion: acp.PROTOCOL_VERSION,
  885. clientCapabilities: {},
  886. });
  887. const session = await connection.request(acp.methods.agent.session.new, {
  888. cwd: '/workspace',
  889. mcpServers: [],
  890. });
  891. await expect(
  892. connection.request(acp.methods.agent.session.prompt, {
  893. sessionId: session.sessionId,
  894. prompt: [{ type: 'text', text: '/status' }],
  895. }),
  896. ).resolves.toEqual({ stopReason: 'end_turn' });
  897. });
  898. expect(listModels).toHaveBeenCalledWith('session-1');
  899. expect(sendMessage).not.toHaveBeenCalled();
  900. expect(updates).toContainEqual({
  901. sessionId: 'session-1',
  902. update: {
  903. sessionUpdate: 'agent_message_chunk',
  904. content: {
  905. type: 'text',
  906. text: [
  907. 'Account status: ready',
  908. 'Model: minimax/m3 (MiniMax M3)',
  909. 'Model source: token-plan',
  910. 'Authentication: managed-login',
  911. 'Managed token: present',
  912. 'Warnings: none',
  913. ].join('\n'),
  914. },
  915. },
  916. });
  917. });
  918. it('keeps the Runtime session identity stable when /new asks for a client thread', async () => {
  919. const { runtime, createSession, sendMessage } = createRuntime([
  920. {
  921. type: 'delta',
  922. messageId: 'message-after-new',
  923. role: 'assistant',
  924. content: 'Same session.',
  925. },
  926. { type: 'session-status', status: 'finished' },
  927. ]);
  928. createSession.mockResolvedValueOnce({ sessionId: 'session-1', workspaceDir: '/workspace' });
  929. const updates: acp.SessionNotification[] = [];
  930. const agent = createTuiAcpAgent({
  931. runtime,
  932. version: '1.2.3',
  933. createTurnId: () => 'turn-after-new',
  934. });
  935. const client = acp
  936. .client({ name: 'zed' })
  937. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
  938. await client.connectWith(agent, async (connection) => {
  939. await connection.request(acp.methods.agent.initialize, {
  940. protocolVersion: acp.PROTOCOL_VERSION,
  941. clientCapabilities: {},
  942. });
  943. const session = await connection.request(acp.methods.agent.session.new, {
  944. cwd: '/workspace',
  945. mcpServers: [],
  946. });
  947. expect(session.sessionId).toBe('session-1');
  948. await expect(
  949. connection.request(acp.methods.agent.session.prompt, {
  950. sessionId: session.sessionId,
  951. prompt: [{ type: 'text', text: '/new later' }],
  952. }),
  953. ).rejects.toThrow('Use `/new` without arguments.');
  954. await expect(
  955. connection.request(acp.methods.agent.session.prompt, {
  956. sessionId: session.sessionId,
  957. prompt: [{ type: 'text', text: '/new' }],
  958. }),
  959. ).resolves.toEqual({ stopReason: 'end_turn' });
  960. await expect(
  961. connection.request(acp.methods.agent.session.prompt, {
  962. sessionId: session.sessionId,
  963. prompt: [{ type: 'text', text: 'Continue in the existing session' }],
  964. }),
  965. ).resolves.toEqual({ stopReason: 'end_turn' });
  966. });
  967. expect(createSession).toHaveBeenCalledOnce();
  968. expect(sendMessage).toHaveBeenCalledOnce();
  969. expect(sendMessage).toHaveBeenCalledWith(
  970. {
  971. id: 'session-1',
  972. turnId: 'turn-after-new',
  973. content: 'Continue in the existing session',
  974. },
  975. expect.any(AbortSignal),
  976. );
  977. expect(updates).toContainEqual({
  978. sessionId: 'session-1',
  979. update: {
  980. sessionUpdate: 'agent_message_chunk',
  981. content: {
  982. type: 'text',
  983. text: 'Start a new thread in your ACP client to begin a fresh session.',
  984. },
  985. },
  986. });
  987. });
  988. it('rejects an unknown model locally without starting an Agent turn', async () => {
  989. const { runtime, sendMessage, selectModel } = createRuntime([], {
  990. models: [{ providerId: 'minimax', modelId: 'm3' }],
  991. });
  992. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  993. const client = acp.client({ name: 'zed' });
  994. await client.connectWith(agent, async (connection) => {
  995. await connection.request(acp.methods.agent.initialize, {
  996. protocolVersion: acp.PROTOCOL_VERSION,
  997. clientCapabilities: {},
  998. });
  999. const session = await connection.request(acp.methods.agent.session.new, {
  1000. cwd: '/workspace',
  1001. mcpServers: [],
  1002. });
  1003. await expect(
  1004. connection.request(acp.methods.agent.session.prompt, {
  1005. sessionId: session.sessionId,
  1006. prompt: [{ type: 'text', text: '/model custom/missing' }],
  1007. }),
  1008. ).rejects.toThrow('Unknown model custom/missing');
  1009. });
  1010. expect(selectModel).not.toHaveBeenCalled();
  1011. expect(sendMessage).not.toHaveBeenCalled();
  1012. });
  1013. it('rejects an unsupported model variant locally', async () => {
  1014. const { runtime, sendMessage, selectModel } = createRuntime([], {
  1015. models: [
  1016. {
  1017. providerId: 'minimax',
  1018. modelId: 'm3',
  1019. supportedVariants: ['low', 'high'],
  1020. },
  1021. ],
  1022. });
  1023. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  1024. const client = acp.client({ name: 'zed' });
  1025. await client.connectWith(agent, async (connection) => {
  1026. await connection.request(acp.methods.agent.initialize, {
  1027. protocolVersion: acp.PROTOCOL_VERSION,
  1028. clientCapabilities: {},
  1029. });
  1030. const session = await connection.request(acp.methods.agent.session.new, {
  1031. cwd: '/workspace',
  1032. mcpServers: [],
  1033. });
  1034. await expect(
  1035. connection.request(acp.methods.agent.session.prompt, {
  1036. sessionId: session.sessionId,
  1037. prompt: [{ type: 'text', text: '/model minimax/m3#turbo' }],
  1038. }),
  1039. ).rejects.toThrow('Unknown variant turbo for minimax/m3');
  1040. });
  1041. expect(selectModel).not.toHaveBeenCalled();
  1042. expect(sendMessage).not.toHaveBeenCalled();
  1043. });
  1044. it('keeps unadvertised slash text as an ordinary Runtime prompt', async () => {
  1045. const { runtime, sendMessage, listModels } = createRuntime([
  1046. {
  1047. type: 'delta',
  1048. messageId: 'message-unknown-command',
  1049. role: 'assistant',
  1050. content: 'Handled as a prompt.',
  1051. },
  1052. { type: 'session-status', status: 'finished' },
  1053. ]);
  1054. const agent = createTuiAcpAgent({
  1055. runtime,
  1056. version: '1.2.3',
  1057. createTurnId: () => 'turn-unknown-command',
  1058. });
  1059. const client = acp.client({ name: 'test-client' });
  1060. await client.connectWith(agent, async (connection) => {
  1061. await connection.request(acp.methods.agent.initialize, {
  1062. protocolVersion: acp.PROTOCOL_VERSION,
  1063. clientCapabilities: {},
  1064. });
  1065. const session = await connection.request(acp.methods.agent.session.new, {
  1066. cwd: '/workspace',
  1067. mcpServers: [],
  1068. });
  1069. await expect(
  1070. connection.request(acp.methods.agent.session.prompt, {
  1071. sessionId: session.sessionId,
  1072. prompt: [{ type: 'text', text: '/not-advertised keep this' }],
  1073. }),
  1074. ).resolves.toEqual({ stopReason: 'end_turn' });
  1075. });
  1076. expect(listModels).toHaveBeenCalledOnce();
  1077. expect(sendMessage).toHaveBeenCalledWith(
  1078. {
  1079. id: 'session-1',
  1080. turnId: 'turn-unknown-command',
  1081. content: '/not-advertised keep this',
  1082. },
  1083. expect.any(AbortSignal),
  1084. );
  1085. });
  1086. it('negotiates truthful capabilities and runs a prompt through the local Runtime', async () => {
  1087. const { runtime, createSession, sendMessage } = createRuntime([
  1088. {
  1089. type: 'delta',
  1090. messageId: 'message-1',
  1091. role: 'assistant',
  1092. content: 'Done.',
  1093. },
  1094. { type: 'session-status', status: 'finished' },
  1095. ]);
  1096. const updates: acp.SessionNotification[] = [];
  1097. const agent = createTuiAcpAgent({
  1098. runtime,
  1099. version: '1.2.3',
  1100. createTurnId: () => 'turn-1',
  1101. });
  1102. const client = acp
  1103. .client({ name: 'test-client' })
  1104. .onNotification(acp.methods.client.session.update, ({ params }) => {
  1105. updates.push(params);
  1106. });
  1107. await client.connectWith(agent, async (connection) => {
  1108. const initialized = await connection.request(acp.methods.agent.initialize, {
  1109. protocolVersion: acp.PROTOCOL_VERSION,
  1110. clientCapabilities: { auth: { terminal: true } },
  1111. clientInfo: { name: 'test-client', version: '0.1.0' },
  1112. });
  1113. expect(initialized).toEqual({
  1114. protocolVersion: acp.PROTOCOL_VERSION,
  1115. agentCapabilities: {
  1116. loadSession: true,
  1117. mcpCapabilities: {
  1118. http: true,
  1119. sse: true,
  1120. },
  1121. promptCapabilities: {
  1122. image: false,
  1123. audio: false,
  1124. embeddedContext: false,
  1125. },
  1126. sessionCapabilities: {
  1127. list: {},
  1128. fork: {},
  1129. resume: {},
  1130. close: {},
  1131. },
  1132. },
  1133. authMethods: [
  1134. {
  1135. type: 'terminal',
  1136. id: 'minimax-code-login',
  1137. name: 'Sign in to MiniMax Code',
  1138. args: ['login'],
  1139. },
  1140. ],
  1141. agentInfo: { name: 'minimax-code', title: 'MiniMax Code', version: '1.2.3' },
  1142. _meta: {
  1143. 'minimax-code/extensions': {
  1144. version: 1,
  1145. methods: expect.arrayContaining([
  1146. 'session/activate',
  1147. 'mcode/session/steer',
  1148. 'mcode/session/goal/create',
  1149. 'mcode/session/delegation/get',
  1150. ]),
  1151. notifications: [
  1152. 'mcode/session/current_session_update',
  1153. 'mcode/session/queue_update',
  1154. 'mcode/session/goal_update',
  1155. 'mcode/session/delegation_update',
  1156. ],
  1157. },
  1158. },
  1159. });
  1160. const session = await connection.request(acp.methods.agent.session.new, {
  1161. cwd: '/workspace',
  1162. mcpServers: [],
  1163. });
  1164. expect(session).toMatchObject({
  1165. sessionId: 'session-1',
  1166. modes: { currentModeId: 'default' },
  1167. configOptions: expect.arrayContaining([expect.objectContaining({ id: 'permissionMode' })]),
  1168. });
  1169. await expect(
  1170. connection.request(acp.methods.agent.session.prompt, {
  1171. sessionId: session.sessionId,
  1172. prompt: [
  1173. { type: 'text', text: 'Fix it' },
  1174. {
  1175. type: 'resource_link',
  1176. name: 'README',
  1177. uri: 'file:///workspace/README.md',
  1178. },
  1179. ],
  1180. }),
  1181. ).resolves.toEqual({ stopReason: 'end_turn' });
  1182. });
  1183. expect(createSession).toHaveBeenCalledWith({ workspaceDir: '/workspace' });
  1184. expect(sendMessage).toHaveBeenCalledWith(
  1185. {
  1186. id: 'session-1',
  1187. turnId: 'turn-1',
  1188. content: 'Fix it\n\nReferenced resource: README (file:///workspace/README.md)',
  1189. },
  1190. expect.any(AbortSignal),
  1191. );
  1192. expect(updates).toEqual([
  1193. {
  1194. sessionId: 'session-1',
  1195. update: {
  1196. sessionUpdate: 'agent_message_chunk',
  1197. messageId: 'message-1',
  1198. content: { type: 'text', text: 'Done.' },
  1199. },
  1200. },
  1201. ]);
  1202. });
  1203. it('cleans up cancelled new Sessions and bounds stalled creation generations', async () => {
  1204. const { runtime, createSession, deleteSession, listModels } = createRuntime();
  1205. let nextSession = 0;
  1206. createSession.mockImplementation(async ({ workspaceDir }: { workspaceDir: string }) => ({
  1207. sessionId: `session-new-${nextSession++}`,
  1208. workspaceDir,
  1209. }));
  1210. listModels.mockImplementation(() => new Promise(() => undefined));
  1211. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  1212. const client = acp.client({ name: 'test-client' });
  1213. await client.connectWith(agent, async (connection) => {
  1214. await connection.request(acp.methods.agent.initialize, {
  1215. protocolVersion: acp.PROTOCOL_VERSION,
  1216. clientCapabilities: {},
  1217. });
  1218. const cancellations = Array.from({ length: 8 }, () => new AbortController());
  1219. const creations = cancellations.map((cancellation, index) =>
  1220. connection.request(
  1221. acp.methods.agent.session.new,
  1222. { cwd: `/workspace/${index}`, mcpServers: [] },
  1223. { cancellationSignal: cancellation.signal },
  1224. ),
  1225. );
  1226. for (const creation of creations) void creation.catch(() => undefined);
  1227. await vi.waitFor(() => expect(listModels).toHaveBeenCalledTimes(8));
  1228. for (const cancellation of cancellations) cancellation.abort();
  1229. await Promise.all(creations.map((creation) => expect(creation).rejects.toThrow('cancel')));
  1230. await vi.waitFor(() => expect(deleteSession).toHaveBeenCalledTimes(8));
  1231. await expect(
  1232. connection.request(acp.methods.agent.session.new, {
  1233. cwd: '/workspace/overflow',
  1234. mcpServers: [],
  1235. }),
  1236. ).rejects.toThrow('Too many ACP Session creation operations');
  1237. for (let index = 0; index < 8; index += 1) {
  1238. await expect(
  1239. connection.request(acp.methods.agent.session.close, {
  1240. sessionId: `session-new-${index}`,
  1241. }),
  1242. ).rejects.toThrow();
  1243. }
  1244. });
  1245. });
  1246. it('does not publish a new Session attachment before control initialization commits', async () => {
  1247. const { runtime, deleteSession, listModels } = createRuntime();
  1248. let releaseModels!: () => void;
  1249. listModels.mockImplementationOnce(
  1250. () =>
  1251. new Promise((resolve) => {
  1252. releaseModels = () => resolve([]);
  1253. }),
  1254. );
  1255. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  1256. const client = acp.client({ name: 'test-client' });
  1257. await client.connectWith(agent, async (connection) => {
  1258. await connection.request(acp.methods.agent.initialize, {
  1259. protocolVersion: acp.PROTOCOL_VERSION,
  1260. clientCapabilities: {},
  1261. });
  1262. const creation = connection.request(acp.methods.agent.session.new, {
  1263. cwd: '/workspace',
  1264. mcpServers: [],
  1265. });
  1266. await vi.waitFor(() => expect(listModels).toHaveBeenCalledOnce());
  1267. await expect(
  1268. connection.request(acp.methods.agent.session.close, { sessionId: 'session-1' }),
  1269. ).rejects.toThrow();
  1270. releaseModels();
  1271. await expect(creation).resolves.toMatchObject({ sessionId: 'session-1' });
  1272. await expect(
  1273. connection.request(acp.methods.agent.session.close, { sessionId: 'session-1' }),
  1274. ).resolves.toEqual({});
  1275. });
  1276. expect(deleteSession).not.toHaveBeenCalled();
  1277. });
  1278. it('serializes resume behind cancelled new Session deletion', async () => {
  1279. const { runtime, deleteSession, getSession, listModels } = createRuntime();
  1280. listModels.mockImplementationOnce(() => new Promise(() => undefined));
  1281. getSession.mockRejectedValueOnce(new Error('deleted'));
  1282. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  1283. const client = acp.client({ name: 'test-client' });
  1284. await client.connectWith(agent, async (connection) => {
  1285. await connection.request(acp.methods.agent.initialize, {
  1286. protocolVersion: acp.PROTOCOL_VERSION,
  1287. clientCapabilities: {},
  1288. });
  1289. const cancellation = new AbortController();
  1290. const creation = connection.request(
  1291. acp.methods.agent.session.new,
  1292. { cwd: '/workspace', mcpServers: [] },
  1293. { cancellationSignal: cancellation.signal },
  1294. );
  1295. void creation.catch(() => undefined);
  1296. await vi.waitFor(() => expect(listModels).toHaveBeenCalledOnce());
  1297. const resume = connection.request(acp.methods.agent.session.resume, {
  1298. sessionId: 'session-1',
  1299. cwd: '/workspace',
  1300. mcpServers: [],
  1301. });
  1302. void resume.catch(() => undefined);
  1303. await new Promise<void>((resolve) => setImmediate(resolve));
  1304. expect(getSession).not.toHaveBeenCalled();
  1305. cancellation.abort();
  1306. await expect(creation).rejects.toThrow('cancel');
  1307. await vi.waitFor(() => expect(deleteSession).toHaveBeenCalledWith('session-1'));
  1308. await expect(resume).rejects.toThrow();
  1309. expect(getSession).toHaveBeenCalledWith('session-1');
  1310. });
  1311. });
  1312. it('lists, loads, resumes, and closes persisted Runtime sessions', async () => {
  1313. const {
  1314. runtime,
  1315. configureSessionMcpServers,
  1316. clearSessionMcpServers,
  1317. listSessionPage,
  1318. getSession,
  1319. listMessagePage,
  1320. sendMessage,
  1321. } = createRuntime([
  1322. {
  1323. type: 'delta',
  1324. messageId: 'message-new',
  1325. role: 'assistant',
  1326. content: 'Continued.',
  1327. },
  1328. { type: 'session-status', status: 'finished' },
  1329. ]);
  1330. listSessionPage.mockResolvedValueOnce({
  1331. sessions: [
  1332. {
  1333. sessionId: 'session-existing',
  1334. workspaceDir: '/workspace',
  1335. title: 'Existing chat',
  1336. updatedAt: 1_725_000_000_000,
  1337. },
  1338. ],
  1339. hasMore: true,
  1340. nextCursor: 'cursor-next',
  1341. });
  1342. getSession.mockResolvedValue({
  1343. sessionId: 'session-existing',
  1344. agentName: 'mcode',
  1345. workspaceDir: '/workspace',
  1346. });
  1347. listMessagePage
  1348. .mockResolvedValueOnce({
  1349. messages: [
  1350. {
  1351. id: 'message-assistant',
  1352. role: 'assistant',
  1353. content: 'Earlier answer.',
  1354. },
  1355. ],
  1356. hasMore: true,
  1357. nextCursor: 'message-assistant',
  1358. })
  1359. .mockResolvedValueOnce({
  1360. messages: [
  1361. {
  1362. id: 'message-user',
  1363. role: 'user',
  1364. content: 'Earlier question.',
  1365. },
  1366. ],
  1367. hasMore: false,
  1368. });
  1369. const updates: acp.SessionNotification[] = [];
  1370. const agent = createTuiAcpAgent({
  1371. runtime,
  1372. version: '1.2.3',
  1373. createTurnId: () => 'turn-loaded',
  1374. });
  1375. const client = acp
  1376. .client({ name: 'test-client' })
  1377. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
  1378. await client.connectWith(agent, async (connection) => {
  1379. await connection.request(acp.methods.agent.initialize, {
  1380. protocolVersion: acp.PROTOCOL_VERSION,
  1381. clientCapabilities: {},
  1382. });
  1383. await expect(
  1384. connection.request(acp.methods.agent.session.list, {
  1385. cwd: '/workspace',
  1386. cursor: 'cursor-current',
  1387. }),
  1388. ).resolves.toEqual({
  1389. sessions: [
  1390. {
  1391. sessionId: 'session-existing',
  1392. cwd: '/workspace',
  1393. title: 'Existing chat',
  1394. updatedAt: '2024-08-30T06:40:00.000Z',
  1395. },
  1396. ],
  1397. nextCursor: 'cursor-next',
  1398. });
  1399. await expect(
  1400. connection.request(acp.methods.agent.session.load, {
  1401. sessionId: 'session-existing',
  1402. cwd: '/workspace',
  1403. mcpServers: [
  1404. {
  1405. name: 'client-tools',
  1406. command: '/usr/local/bin/client-tools',
  1407. args: ['serve'],
  1408. env: [],
  1409. },
  1410. ],
  1411. }),
  1412. ).resolves.toMatchObject({
  1413. modes: { currentModeId: 'default' },
  1414. configOptions: expect.arrayContaining([expect.objectContaining({ id: 'permissionMode' })]),
  1415. });
  1416. await expect(
  1417. connection.request(acp.methods.agent.session.prompt, {
  1418. sessionId: 'session-existing',
  1419. prompt: [{ type: 'text', text: 'Continue' }],
  1420. }),
  1421. ).resolves.toEqual({ stopReason: 'end_turn' });
  1422. await expect(
  1423. connection.request(acp.methods.agent.session.close, {
  1424. sessionId: 'session-existing',
  1425. }),
  1426. ).resolves.toEqual({});
  1427. await expect(
  1428. connection.request(acp.methods.agent.session.prompt, {
  1429. sessionId: 'session-existing',
  1430. prompt: [{ type: 'text', text: 'After close' }],
  1431. }),
  1432. ).rejects.toThrow();
  1433. updates.length = 0;
  1434. await expect(
  1435. connection.request(acp.methods.agent.session.resume, {
  1436. sessionId: 'session-existing',
  1437. cwd: '/workspace',
  1438. mcpServers: [],
  1439. }),
  1440. ).resolves.toMatchObject({
  1441. modes: { currentModeId: 'default' },
  1442. configOptions: expect.arrayContaining([expect.objectContaining({ id: 'permissionMode' })]),
  1443. });
  1444. await new Promise<void>((resolve) => setImmediate(resolve));
  1445. expect(
  1446. updates.filter(({ update }) => update.sessionUpdate.endsWith('message_chunk')),
  1447. ).toEqual([]);
  1448. });
  1449. expect(listSessionPage).toHaveBeenCalledWith({
  1450. cursor: 'cursor-current',
  1451. includeArchived: true,
  1452. workspaceDir: '/workspace',
  1453. });
  1454. expect(getSession).toHaveBeenCalledWith('session-existing');
  1455. expect(listMessagePage).toHaveBeenNthCalledWith(1, 'session-existing', { limit: 100 });
  1456. expect(listMessagePage).toHaveBeenNthCalledWith(2, 'session-existing', {
  1457. before: 'message-assistant',
  1458. limit: 100,
  1459. });
  1460. expect(clearSessionMcpServers).toHaveBeenCalledWith('session-existing');
  1461. expect(configureSessionMcpServers).toHaveBeenCalledWith('session-existing', [
  1462. {
  1463. name: 'client-tools',
  1464. type: 'stdio',
  1465. command: '/usr/local/bin/client-tools',
  1466. args: ['serve'],
  1467. },
  1468. ]);
  1469. expect(sendMessage).toHaveBeenCalledWith(
  1470. {
  1471. id: 'session-existing',
  1472. turnId: 'turn-loaded',
  1473. content: 'Continue',
  1474. },
  1475. expect.any(AbortSignal),
  1476. );
  1477. });
  1478. it('replays loaded history in chronological order before advertising commands', async () => {
  1479. const { runtime, getSession, listMessagePage } = createRuntime();
  1480. getSession.mockResolvedValue({
  1481. sessionId: 'session-existing',
  1482. workspaceDir: '/workspace',
  1483. });
  1484. listMessagePage
  1485. .mockResolvedValueOnce({
  1486. messages: [
  1487. { id: 'user-2', role: 'user', content: 'Newest question.' },
  1488. { id: 'assistant-2', role: 'assistant', content: 'Newest answer.' },
  1489. ],
  1490. hasMore: true,
  1491. nextCursor: 'user-2',
  1492. })
  1493. .mockResolvedValueOnce({
  1494. messages: [
  1495. { id: 'user-1', role: 'user', content: 'Oldest question.' },
  1496. { id: 'assistant-1', role: 'assistant', content: 'Oldest answer.' },
  1497. ],
  1498. hasMore: false,
  1499. });
  1500. const updates: acp.SessionNotification[] = [];
  1501. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  1502. const client = acp
  1503. .client({ name: 'test-client' })
  1504. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
  1505. await client.connectWith(agent, async (connection) => {
  1506. await connection.request(acp.methods.agent.initialize, {
  1507. protocolVersion: acp.PROTOCOL_VERSION,
  1508. clientCapabilities: {},
  1509. });
  1510. await connection.request(acp.methods.agent.session.load, {
  1511. sessionId: 'session-existing',
  1512. cwd: '/workspace',
  1513. mcpServers: [],
  1514. });
  1515. });
  1516. expect(
  1517. updates
  1518. .filter(({ update }) => update.sessionUpdate.endsWith('message_chunk'))
  1519. .map(({ update }) => ({
  1520. kind: update.sessionUpdate,
  1521. text: 'content' in update && update.content.type === 'text' ? update.content.text : '',
  1522. })),
  1523. ).toEqual([
  1524. { kind: 'user_message_chunk', text: 'Oldest question.' },
  1525. { kind: 'agent_message_chunk', text: 'Oldest answer.' },
  1526. { kind: 'user_message_chunk', text: 'Newest question.' },
  1527. { kind: 'agent_message_chunk', text: 'Newest answer.' },
  1528. ]);
  1529. });
  1530. it('stops old history work after close and reattachment', async () => {
  1531. const { runtime, listMessagePage } = createRuntime();
  1532. let releaseHistory!: () => void;
  1533. const historyGate = new Promise<void>((resolve) => {
  1534. releaseHistory = resolve;
  1535. });
  1536. listMessagePage
  1537. .mockResolvedValueOnce({
  1538. messages: [{ id: 'old-2', role: 'user', content: 'Second old message.' }],
  1539. hasMore: true,
  1540. nextCursor: 'older',
  1541. })
  1542. .mockImplementationOnce(async () => {
  1543. await historyGate;
  1544. return {
  1545. messages: [{ id: 'old-1', role: 'user', content: 'First old message.' }],
  1546. hasMore: false,
  1547. };
  1548. });
  1549. const replayed: string[] = [];
  1550. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  1551. const client = acp
  1552. .client({ name: 'test-client' })
  1553. .onNotification(acp.methods.client.session.update, async ({ params }) => {
  1554. if (
  1555. params.update.sessionUpdate !== 'user_message_chunk' ||
  1556. params.update.content.type !== 'text'
  1557. ) {
  1558. return;
  1559. }
  1560. replayed.push(params.update.content.text);
  1561. });
  1562. await client.connectWith(agent, async (connection) => {
  1563. await connection.request(acp.methods.agent.initialize, {
  1564. protocolVersion: acp.PROTOCOL_VERSION,
  1565. clientCapabilities: {},
  1566. });
  1567. const load = connection.request(acp.methods.agent.session.load, {
  1568. sessionId: 'session-existing',
  1569. cwd: '/workspace',
  1570. mcpServers: [],
  1571. });
  1572. void load.catch(() => undefined);
  1573. await vi.waitFor(() => expect(listMessagePage).toHaveBeenCalledTimes(2));
  1574. await connection.request(acp.methods.agent.session.close, {
  1575. sessionId: 'session-existing',
  1576. });
  1577. await connection.request(acp.methods.agent.session.resume, {
  1578. sessionId: 'session-existing',
  1579. cwd: '/workspace',
  1580. mcpServers: [],
  1581. });
  1582. releaseHistory();
  1583. await expect(load).rejects.toThrow('cancelled');
  1584. });
  1585. expect(replayed).toEqual([]);
  1586. });
  1587. it('cancels active work and releases session-scoped resources on close', async () => {
  1588. const { runtime, sendMessage, abortSession, clearSessionMcpServers } = createRuntime([], {
  1589. holdRunUntilAbort: true,
  1590. });
  1591. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  1592. const client = acp.client({ name: 'test-client' });
  1593. await client.connectWith(agent, async (connection) => {
  1594. await connection.request(acp.methods.agent.initialize, {
  1595. protocolVersion: acp.PROTOCOL_VERSION,
  1596. clientCapabilities: {},
  1597. });
  1598. const session = await connection.request(acp.methods.agent.session.new, {
  1599. cwd: '/workspace',
  1600. mcpServers: [],
  1601. });
  1602. const prompt = connection.request(acp.methods.agent.session.prompt, {
  1603. sessionId: session.sessionId,
  1604. prompt: [{ type: 'text', text: 'Keep working' }],
  1605. });
  1606. await vi.waitFor(() => expect(sendMessage).toHaveBeenCalledOnce());
  1607. await expect(
  1608. connection.request(acp.methods.agent.session.close, {
  1609. sessionId: session.sessionId,
  1610. }),
  1611. ).resolves.toEqual({});
  1612. await expect(prompt).resolves.toEqual({ stopReason: 'cancelled' });
  1613. });
  1614. expect(abortSession).toHaveBeenCalledWith(
  1615. expect.objectContaining({ id: 'session-1', reason: 'user_stop' }),
  1616. );
  1617. expect(clearSessionMcpServers).toHaveBeenCalledWith('session-1');
  1618. });
  1619. it('serializes close, resume, and prompt admission for the same Session', async () => {
  1620. const { runtime, clearSessionMcpServers, getSession, sendMessage } = createRuntime([
  1621. { type: 'delta', messageId: 'message-1', role: 'assistant', content: 'Attached.' },
  1622. { type: 'session-status', status: 'finished' },
  1623. ]);
  1624. let releaseCloseCleanup!: () => void;
  1625. const closeCleanup = new Promise<void>((resolve) => {
  1626. releaseCloseCleanup = resolve;
  1627. });
  1628. clearSessionMcpServers.mockImplementationOnce(() => closeCleanup).mockResolvedValue(undefined);
  1629. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  1630. const client = acp.client({ name: 'test-client' });
  1631. await client.connectWith(agent, async (connection) => {
  1632. await connection.request(acp.methods.agent.initialize, {
  1633. protocolVersion: acp.PROTOCOL_VERSION,
  1634. clientCapabilities: {},
  1635. });
  1636. const session = await connection.request(acp.methods.agent.session.new, {
  1637. cwd: '/workspace',
  1638. mcpServers: [],
  1639. });
  1640. const close = connection.request(acp.methods.agent.session.close, {
  1641. sessionId: session.sessionId,
  1642. });
  1643. await vi.waitFor(() => expect(clearSessionMcpServers).toHaveBeenCalledOnce());
  1644. const resume = connection.request(acp.methods.agent.session.resume, {
  1645. sessionId: session.sessionId,
  1646. cwd: '/workspace',
  1647. mcpServers: [],
  1648. });
  1649. const prompt = connection.request(acp.methods.agent.session.prompt, {
  1650. sessionId: session.sessionId,
  1651. prompt: [{ type: 'text', text: 'Use the replacement attachment' }],
  1652. });
  1653. await new Promise<void>((resolve) => setImmediate(resolve));
  1654. expect(getSession).not.toHaveBeenCalled();
  1655. expect(sendMessage).not.toHaveBeenCalled();
  1656. releaseCloseCleanup();
  1657. await expect(close).resolves.toEqual({});
  1658. await expect(resume).resolves.toMatchObject({ modes: { currentModeId: 'default' } });
  1659. await expect(prompt).resolves.toEqual({ stopReason: 'end_turn' });
  1660. });
  1661. expect(clearSessionMcpServers).toHaveBeenCalledTimes(2);
  1662. expect(sendMessage).toHaveBeenCalledOnce();
  1663. });
  1664. it('consumes cancel while a Prompt is waiting for Session admission', async () => {
  1665. const { runtime, getSession, sendMessage } = createRuntime();
  1666. let releaseConfiguration!: (session: {
  1667. sessionId: string;
  1668. workspaceDir: string;
  1669. interactionMode: 'default';
  1670. }) => void;
  1671. getSession.mockImplementationOnce(
  1672. () =>
  1673. new Promise((resolve) => {
  1674. releaseConfiguration = resolve;
  1675. }),
  1676. );
  1677. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  1678. const client = acp.client({ name: 'test-client' });
  1679. await client.connectWith(agent, async (connection) => {
  1680. await connection.request(acp.methods.agent.initialize, {
  1681. protocolVersion: acp.PROTOCOL_VERSION,
  1682. clientCapabilities: {},
  1683. });
  1684. const session = await connection.request(acp.methods.agent.session.new, {
  1685. cwd: '/workspace',
  1686. mcpServers: [],
  1687. });
  1688. const configuration = connection.request(acp.methods.agent.session.setMode, {
  1689. sessionId: session.sessionId,
  1690. modeId: 'plan',
  1691. });
  1692. await vi.waitFor(() => expect(getSession).toHaveBeenCalledOnce());
  1693. const prompt = connection.request(acp.methods.agent.session.prompt, {
  1694. sessionId: session.sessionId,
  1695. prompt: [{ type: 'text', text: 'Do not start after cancellation' }],
  1696. });
  1697. await connection.notify(acp.methods.agent.session.cancel, { sessionId: session.sessionId });
  1698. await new Promise<void>((resolve) => setImmediate(resolve));
  1699. releaseConfiguration({
  1700. sessionId: 'session-1',
  1701. workspaceDir: '/workspace',
  1702. interactionMode: 'default',
  1703. });
  1704. await expect(configuration).resolves.toEqual({
  1705. _meta: { 'minimax-code/transition': 'next_prompt' },
  1706. });
  1707. await expect(prompt).resolves.toEqual({ stopReason: 'cancelled' });
  1708. });
  1709. expect(sendMessage).not.toHaveBeenCalled();
  1710. });
  1711. it('consumes JSON-RPC cancellation while a Prompt is waiting for Session admission', async () => {
  1712. const { runtime, getSession, requestCompaction, sendMessage } = createRuntime();
  1713. let releaseConfiguration!: (session: {
  1714. sessionId: string;
  1715. workspaceDir: string;
  1716. interactionMode: 'default';
  1717. }) => void;
  1718. getSession.mockImplementationOnce(
  1719. () =>
  1720. new Promise((resolve) => {
  1721. releaseConfiguration = resolve;
  1722. }),
  1723. );
  1724. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  1725. const client = acp.client({ name: 'test-client' });
  1726. await client.connectWith(agent, async (connection) => {
  1727. await connection.request(acp.methods.agent.initialize, {
  1728. protocolVersion: acp.PROTOCOL_VERSION,
  1729. clientCapabilities: {},
  1730. });
  1731. const session = await connection.request(acp.methods.agent.session.new, {
  1732. cwd: '/workspace',
  1733. mcpServers: [],
  1734. });
  1735. const configuration = connection.request(acp.methods.agent.session.setMode, {
  1736. sessionId: session.sessionId,
  1737. modeId: 'plan',
  1738. });
  1739. await vi.waitFor(() => expect(getSession).toHaveBeenCalledOnce());
  1740. const cancellation = new AbortController();
  1741. const prompt = connection.request(
  1742. acp.methods.agent.session.prompt,
  1743. {
  1744. sessionId: session.sessionId,
  1745. prompt: [{ type: 'text', text: '/compact' }],
  1746. },
  1747. { cancellationSignal: cancellation.signal },
  1748. );
  1749. cancellation.abort();
  1750. releaseConfiguration({
  1751. sessionId: 'session-1',
  1752. workspaceDir: '/workspace',
  1753. interactionMode: 'default',
  1754. });
  1755. await expect(configuration).resolves.toEqual({
  1756. _meta: { 'minimax-code/transition': 'next_prompt' },
  1757. });
  1758. await expect(prompt).resolves.toEqual({ stopReason: 'cancelled' });
  1759. });
  1760. expect(requestCompaction).not.toHaveBeenCalled();
  1761. expect(sendMessage).not.toHaveBeenCalled();
  1762. });
  1763. it('lets close clean up MCP state while a loaded history page is stalled', async () => {
  1764. const { runtime, clearSessionMcpServers, getSession, listMessagePage } = createRuntime();
  1765. getSession.mockResolvedValue({
  1766. sessionId: 'session-existing',
  1767. workspaceDir: '/workspace',
  1768. });
  1769. listMessagePage.mockImplementation(() => new Promise(() => undefined));
  1770. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  1771. const client = acp.client({ name: 'test-client' });
  1772. await client.connectWith(agent, async (connection) => {
  1773. await connection.request(acp.methods.agent.initialize, {
  1774. protocolVersion: acp.PROTOCOL_VERSION,
  1775. clientCapabilities: {},
  1776. });
  1777. const load = connection.request(acp.methods.agent.session.load, {
  1778. sessionId: 'session-existing',
  1779. cwd: '/workspace',
  1780. mcpServers: [],
  1781. });
  1782. void load.catch(() => undefined);
  1783. await vi.waitFor(() => expect(listMessagePage).toHaveBeenCalledOnce());
  1784. await expect(
  1785. connection.request(acp.methods.agent.session.close, {
  1786. sessionId: 'session-existing',
  1787. }),
  1788. ).resolves.toEqual({});
  1789. await vi.waitFor(() => expect(clearSessionMcpServers).toHaveBeenCalledTimes(2));
  1790. });
  1791. });
  1792. it('bounds repeatedly detached lifecycle generations for one Session', async () => {
  1793. const { runtime, listMessagePage } = createRuntime();
  1794. listMessagePage.mockImplementation(() => new Promise(() => undefined));
  1795. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  1796. const client = acp.client({ name: 'test-client' });
  1797. await client.connectWith(agent, async (connection) => {
  1798. await connection.request(acp.methods.agent.initialize, {
  1799. protocolVersion: acp.PROTOCOL_VERSION,
  1800. clientCapabilities: {},
  1801. });
  1802. for (let generation = 0; generation < 2; generation += 1) {
  1803. const load = connection.request(acp.methods.agent.session.load, {
  1804. sessionId: 'session-existing',
  1805. cwd: '/workspace',
  1806. mcpServers: [],
  1807. });
  1808. void load.catch(() => undefined);
  1809. await vi.waitFor(() => expect(listMessagePage).toHaveBeenCalledTimes(generation + 1));
  1810. await connection.request(acp.methods.agent.session.close, {
  1811. sessionId: 'session-existing',
  1812. });
  1813. }
  1814. await expect(
  1815. connection.request(acp.methods.agent.session.load, {
  1816. sessionId: 'session-existing',
  1817. cwd: '/workspace',
  1818. mcpServers: [],
  1819. }),
  1820. ).rejects.toThrow('Too many cancelled ACP Session operations');
  1821. });
  1822. expect(listMessagePage).toHaveBeenCalledTimes(2);
  1823. });
  1824. it('bounds normally queued lifecycle operations for one stalled Session', async () => {
  1825. const { runtime, getSession } = createRuntime();
  1826. getSession.mockImplementation(() => new Promise(() => undefined));
  1827. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  1828. const client = acp.client({ name: 'test-client' });
  1829. await client.connectWith(agent, async (connection) => {
  1830. await connection.request(acp.methods.agent.initialize, {
  1831. protocolVersion: acp.PROTOCOL_VERSION,
  1832. clientCapabilities: {},
  1833. });
  1834. const session = await connection.request(acp.methods.agent.session.new, {
  1835. cwd: '/workspace',
  1836. mcpServers: [],
  1837. });
  1838. const admitted = Array.from({ length: 64 }, () =>
  1839. connection.request(acp.methods.agent.session.setMode, {
  1840. sessionId: session.sessionId,
  1841. modeId: 'plan',
  1842. }),
  1843. );
  1844. for (const request of admitted) void request.catch(() => undefined);
  1845. await vi.waitFor(() => expect(getSession).toHaveBeenCalledOnce());
  1846. await expect(
  1847. connection.request(acp.methods.agent.session.setMode, {
  1848. sessionId: session.sessionId,
  1849. modeId: 'plan',
  1850. }),
  1851. ).rejects.toThrow('Too many ACP Session operations');
  1852. await connection.request(acp.methods.agent.session.close, {
  1853. sessionId: session.sessionId,
  1854. });
  1855. });
  1856. });
  1857. it('lets close return while an ACP command is stalled before Prompt admission', async () => {
  1858. const { runtime, requestCompaction } = createRuntime();
  1859. requestCompaction.mockImplementation(() => new Promise(() => undefined));
  1860. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  1861. const client = acp.client({ name: 'test-client' });
  1862. await client.connectWith(agent, async (connection) => {
  1863. await connection.request(acp.methods.agent.initialize, {
  1864. protocolVersion: acp.PROTOCOL_VERSION,
  1865. clientCapabilities: {},
  1866. });
  1867. const session = await connection.request(acp.methods.agent.session.new, {
  1868. cwd: '/workspace',
  1869. mcpServers: [],
  1870. });
  1871. const command = connection.request(acp.methods.agent.session.prompt, {
  1872. sessionId: session.sessionId,
  1873. prompt: [{ type: 'text', text: '/compact' }],
  1874. });
  1875. void command.catch(() => undefined);
  1876. await vi.waitFor(() => expect(requestCompaction).toHaveBeenCalledOnce());
  1877. await expect(
  1878. connection.request(acp.methods.agent.session.close, {
  1879. sessionId: session.sessionId,
  1880. }),
  1881. ).resolves.toEqual({});
  1882. });
  1883. });
  1884. it('detaches a Session when replacing its MCP overlay fails', async () => {
  1885. const { runtime, getSession, configureSessionMcpServers, clearSessionMcpServers } =
  1886. createRuntime();
  1887. getSession.mockResolvedValue({
  1888. sessionId: 'session-1',
  1889. workspaceDir: '/workspace',
  1890. });
  1891. configureSessionMcpServers.mockRejectedValueOnce(new Error('MCP configuration failed'));
  1892. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  1893. const client = acp.client({ name: 'test-client' });
  1894. await client.connectWith(agent, async (connection) => {
  1895. await connection.request(acp.methods.agent.initialize, {
  1896. protocolVersion: acp.PROTOCOL_VERSION,
  1897. clientCapabilities: {},
  1898. });
  1899. const session = await connection.request(acp.methods.agent.session.new, {
  1900. cwd: '/workspace',
  1901. mcpServers: [
  1902. {
  1903. name: 'old-tools',
  1904. command: '/usr/local/bin/old-tools',
  1905. args: [],
  1906. env: [],
  1907. },
  1908. ],
  1909. });
  1910. await expect(
  1911. connection.request(acp.methods.agent.session.resume, {
  1912. sessionId: session.sessionId,
  1913. cwd: '/workspace',
  1914. mcpServers: [
  1915. {
  1916. name: 'new-tools',
  1917. command: '/usr/local/bin/new-tools',
  1918. args: [],
  1919. env: [],
  1920. },
  1921. ],
  1922. }),
  1923. ).rejects.toThrow();
  1924. await expect(
  1925. connection.request(acp.methods.agent.session.prompt, {
  1926. sessionId: session.sessionId,
  1927. prompt: [{ type: 'text', text: 'Must remain detached' }],
  1928. }),
  1929. ).rejects.toThrow();
  1930. });
  1931. expect(clearSessionMcpServers).toHaveBeenCalledTimes(2);
  1932. expect(configureSessionMcpServers).toHaveBeenCalledOnce();
  1933. });
  1934. it('detaches immediately when MCP recovery cleanup remains stalled', async () => {
  1935. const {
  1936. runtime,
  1937. configureSessionMcpServers,
  1938. clearSessionMcpServers,
  1939. emitRuntimeEvent,
  1940. replyPermission,
  1941. } = createRuntime();
  1942. configureSessionMcpServers.mockRejectedValueOnce(new Error('MCP configuration failed'));
  1943. clearSessionMcpServers
  1944. .mockResolvedValueOnce(undefined)
  1945. .mockImplementationOnce(() => new Promise(() => undefined));
  1946. const permissionRequest = vi.fn(() => ({
  1947. outcome: { outcome: 'selected' as const, optionId: 'allow-once' },
  1948. }));
  1949. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  1950. const client = acp
  1951. .client({ name: 'test-client' })
  1952. .onRequest(acp.methods.client.session.requestPermission, permissionRequest);
  1953. await client.connectWith(agent, async (connection) => {
  1954. await connection.request(acp.methods.agent.initialize, {
  1955. protocolVersion: acp.PROTOCOL_VERSION,
  1956. clientCapabilities: {},
  1957. });
  1958. const session = await connection.request(acp.methods.agent.session.new, {
  1959. cwd: '/workspace',
  1960. mcpServers: [],
  1961. });
  1962. const resume = connection.request(acp.methods.agent.session.resume, {
  1963. sessionId: session.sessionId,
  1964. cwd: '/workspace',
  1965. mcpServers: [
  1966. {
  1967. name: 'broken-tools',
  1968. command: '/usr/local/bin/broken-tools',
  1969. args: [],
  1970. env: [],
  1971. },
  1972. ],
  1973. });
  1974. void resume.catch(() => undefined);
  1975. await vi.waitFor(() => expect(clearSessionMcpServers).toHaveBeenCalledTimes(2));
  1976. await expect(
  1977. connection.request<{ sessionId: string }, { sessionId: string }>('session/activate', {
  1978. sessionId: session.sessionId,
  1979. }),
  1980. ).rejects.toThrow();
  1981. emitRuntimeEvent(permissionEvent('permission-after-mcp-failure'));
  1982. await new Promise<void>((resolve) => setImmediate(resolve));
  1983. });
  1984. expect(permissionRequest).not.toHaveBeenCalled();
  1985. expect(replyPermission).not.toHaveBeenCalled();
  1986. });
  1987. it('detaches immediately when initial MCP clear recovery remains stalled', async () => {
  1988. const { runtime, clearSessionMcpServers, configureSessionMcpServers } = createRuntime();
  1989. clearSessionMcpServers
  1990. .mockRejectedValueOnce(new Error('MCP clear failed'))
  1991. .mockImplementationOnce(() => new Promise(() => undefined));
  1992. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  1993. const client = acp.client({ name: 'test-client' });
  1994. await client.connectWith(agent, async (connection) => {
  1995. await connection.request(acp.methods.agent.initialize, {
  1996. protocolVersion: acp.PROTOCOL_VERSION,
  1997. clientCapabilities: {},
  1998. });
  1999. const session = await connection.request(acp.methods.agent.session.new, {
  2000. cwd: '/workspace',
  2001. mcpServers: [],
  2002. });
  2003. const resume = connection.request(acp.methods.agent.session.resume, {
  2004. sessionId: session.sessionId,
  2005. cwd: '/workspace',
  2006. mcpServers: [],
  2007. });
  2008. void resume.catch(() => undefined);
  2009. await vi.waitFor(() => expect(clearSessionMcpServers).toHaveBeenCalledTimes(2));
  2010. await expect(
  2011. connection.request<{ sessionId: string }, { sessionId: string }>('session/activate', {
  2012. sessionId: session.sessionId,
  2013. }),
  2014. ).rejects.toThrow();
  2015. });
  2016. expect(configureSessionMcpServers).not.toHaveBeenCalled();
  2017. });
  2018. it('rejects existing-session cwd mismatches and unsupported additional directories', async () => {
  2019. const { runtime, getSession } = createRuntime();
  2020. getSession.mockResolvedValue({
  2021. sessionId: 'session-existing',
  2022. workspaceDir: '/workspace',
  2023. });
  2024. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  2025. const client = acp.client({ name: 'test-client' });
  2026. await client.connectWith(agent, async (connection) => {
  2027. await connection.request(acp.methods.agent.initialize, {
  2028. protocolVersion: acp.PROTOCOL_VERSION,
  2029. clientCapabilities: {},
  2030. });
  2031. await expect(
  2032. connection.request(acp.methods.agent.session.resume, {
  2033. sessionId: 'session-existing',
  2034. cwd: '/other',
  2035. mcpServers: [],
  2036. }),
  2037. ).rejects.toThrow('does not match');
  2038. await expect(
  2039. connection.request(acp.methods.agent.session.load, {
  2040. sessionId: 'session-existing',
  2041. cwd: '/workspace',
  2042. additionalDirectories: ['/other'],
  2043. mcpServers: [],
  2044. }),
  2045. ).rejects.toThrow('Additional directories are not supported');
  2046. await expect(
  2047. connection.request(acp.methods.agent.session.list, {
  2048. cwd: 'relative/workspace',
  2049. }),
  2050. ).rejects.toThrow('must be absolute');
  2051. });
  2052. });
  2053. it('does not expose or attach internal sub-agent sessions', async () => {
  2054. const { runtime, listSessionPage, getSession, clearSessionMcpServers } = createRuntime();
  2055. const internalSession = {
  2056. sessionId: 'session-worker',
  2057. workspaceDir: '/workspace',
  2058. sessionType: 'branch' as const,
  2059. parentSessionId: 'session-root',
  2060. sessionKind: 'task',
  2061. visibility: 'hidden' as const,
  2062. };
  2063. listSessionPage.mockResolvedValue({
  2064. sessions: [
  2065. internalSession,
  2066. { sessionId: 'session-root', workspaceDir: '/workspace', title: 'Public session' },
  2067. ],
  2068. hasMore: false,
  2069. });
  2070. getSession.mockResolvedValue(internalSession);
  2071. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  2072. const client = acp.client({ name: 'test-client' });
  2073. await client.connectWith(agent, async (connection) => {
  2074. await connection.request(acp.methods.agent.initialize, {
  2075. protocolVersion: acp.PROTOCOL_VERSION,
  2076. clientCapabilities: {},
  2077. });
  2078. await expect(
  2079. connection.request(acp.methods.agent.session.list, { cwd: '/workspace' }),
  2080. ).resolves.toEqual({
  2081. sessions: [{ sessionId: 'session-root', cwd: '/workspace', title: 'Public session' }],
  2082. });
  2083. await expect(
  2084. connection.request(acp.methods.agent.session.load, {
  2085. sessionId: 'session-worker',
  2086. cwd: '/workspace',
  2087. mcpServers: [],
  2088. }),
  2089. ).rejects.toThrow('Sub-agent Sessions are internal');
  2090. await expect(
  2091. connection.request(acp.methods.agent.session.resume, {
  2092. sessionId: 'session-worker',
  2093. cwd: '/workspace',
  2094. mcpServers: [],
  2095. }),
  2096. ).rejects.toThrow('Sub-agent Sessions are internal');
  2097. });
  2098. expect(clearSessionMcpServers).not.toHaveBeenCalled();
  2099. });
  2100. it.each([
  2101. {
  2102. name: 'standard terminal authentication capability',
  2103. clientCapabilities: { auth: { terminal: true } },
  2104. advertisesTerminalAuth: true,
  2105. },
  2106. {
  2107. name: 'legacy Registry terminal authentication metadata',
  2108. clientCapabilities: { _meta: { 'terminal-auth': true } },
  2109. advertisesTerminalAuth: true,
  2110. },
  2111. {
  2112. name: 'generic terminal capability without an authentication declaration',
  2113. clientCapabilities: { terminal: true },
  2114. advertisesTerminalAuth: false,
  2115. },
  2116. {
  2117. name: 'no authentication capability',
  2118. clientCapabilities: {},
  2119. advertisesTerminalAuth: false,
  2120. },
  2121. ] satisfies readonly {
  2122. readonly name: string;
  2123. readonly clientCapabilities: acp.ClientCapabilities;
  2124. readonly advertisesTerminalAuth: boolean;
  2125. }[])('advertises terminal authentication for $name', async (testCase) => {
  2126. const { runtime } = createRuntime();
  2127. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  2128. const client = acp.client({ name: 'test-client' });
  2129. await client.connectWith(agent, async (connection) => {
  2130. const initialized = await connection.request(acp.methods.agent.initialize, {
  2131. protocolVersion: acp.PROTOCOL_VERSION,
  2132. clientCapabilities: testCase.clientCapabilities,
  2133. });
  2134. if (testCase.advertisesTerminalAuth) {
  2135. expect(initialized.authMethods).toEqual([
  2136. {
  2137. type: 'terminal',
  2138. id: 'minimax-code-login',
  2139. name: 'Sign in to MiniMax Code',
  2140. args: ['login'],
  2141. },
  2142. ]);
  2143. } else {
  2144. expect(initialized.authMethods).toBeUndefined();
  2145. }
  2146. });
  2147. });
  2148. it('bridges Runtime permission requests to the ACP client and returns its decision', async () => {
  2149. const { runtime, emitRuntimeEvent, replyPermission } = createRuntime();
  2150. const permissionRequests: acp.RequestPermissionRequest[] = [];
  2151. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  2152. const client = acp
  2153. .client({ name: 'test-client' })
  2154. .onRequest(acp.methods.client.session.requestPermission, ({ params }) => {
  2155. permissionRequests.push(params);
  2156. return { outcome: { outcome: 'selected', optionId: 'allow-once' } };
  2157. });
  2158. await client.connectWith(agent, async (connection) => {
  2159. await connection.request(acp.methods.agent.initialize, {
  2160. protocolVersion: acp.PROTOCOL_VERSION,
  2161. clientCapabilities: {},
  2162. });
  2163. await connection.request(acp.methods.agent.session.new, {
  2164. cwd: '/workspace',
  2165. mcpServers: [],
  2166. });
  2167. emitRuntimeEvent({
  2168. type: 'permission.ask',
  2169. timestampMs: 1,
  2170. source: 'runtime',
  2171. sessionId: 'session-1',
  2172. request: {
  2173. requestId: 'permission-1',
  2174. sessionId: 'session-1',
  2175. agentName: 'mcode',
  2176. toolName: 'edit_file',
  2177. toolDescription: 'Edit C:\\workspace\\a.ts',
  2178. toolInput: '{"path":"C:\\\\workspace\\\\a.ts"}',
  2179. allowAlwaysSupported: true,
  2180. },
  2181. });
  2182. await vi.waitFor(() => expect(replyPermission).toHaveBeenCalledOnce());
  2183. });
  2184. expect(permissionRequests).toEqual([
  2185. {
  2186. sessionId: 'session-1',
  2187. toolCall: {
  2188. toolCallId: 'permission-1',
  2189. title: 'Edit C:\\workspace\\a.ts',
  2190. name: 'edit_file',
  2191. kind: 'edit',
  2192. status: 'pending',
  2193. rawInput: { path: 'C:\\workspace\\a.ts' },
  2194. locations: [{ path: 'C:\\workspace\\a.ts' }],
  2195. },
  2196. options: [
  2197. { optionId: 'allow-once', name: 'Allow once', kind: 'allow_once' },
  2198. { optionId: 'allow-always', name: 'Always allow', kind: 'allow_always' },
  2199. { optionId: 'deny', name: 'Deny', kind: 'reject_once' },
  2200. ],
  2201. },
  2202. ]);
  2203. expect(replyPermission).toHaveBeenCalledWith('mcode', 'permission-1', 'allowOnce');
  2204. });
  2205. it('denies a forged allow-always decision when Runtime did not offer it', async () => {
  2206. const { runtime, emitRuntimeEvent, replyPermission } = createRuntime();
  2207. const permissionRequests: acp.RequestPermissionRequest[] = [];
  2208. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  2209. const client = acp
  2210. .client({ name: 'test-client' })
  2211. .onRequest(acp.methods.client.session.requestPermission, ({ params }) => {
  2212. permissionRequests.push(params);
  2213. return { outcome: { outcome: 'selected', optionId: 'allow-always' } };
  2214. });
  2215. await client.connectWith(agent, async (connection) => {
  2216. await connection.request(acp.methods.agent.initialize, {
  2217. protocolVersion: acp.PROTOCOL_VERSION,
  2218. clientCapabilities: {},
  2219. });
  2220. await connection.request(acp.methods.agent.session.new, {
  2221. cwd: '/workspace',
  2222. mcpServers: [],
  2223. });
  2224. emitRuntimeEvent(permissionEvent('permission-forged-always'));
  2225. await vi.waitFor(() => expect(replyPermission).toHaveBeenCalledOnce());
  2226. });
  2227. expect(permissionRequests[0]?.options).not.toContainEqual(
  2228. expect.objectContaining({ optionId: 'allow-always' }),
  2229. );
  2230. expect(replyPermission).toHaveBeenCalledWith('mcode', 'permission-forged-always', 'deny');
  2231. });
  2232. it('routes descendant interactions to their attached root and ignores unrelated Sessions', async () => {
  2233. const { runtime, emitRuntimeEvent, replyPermission, dismissQuestionnaire } = createRuntime();
  2234. const permissionRequests: acp.RequestPermissionRequest[] = [];
  2235. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  2236. const client = acp
  2237. .client({ name: 'test-client' })
  2238. .onRequest(acp.methods.client.session.requestPermission, ({ params }) => {
  2239. permissionRequests.push(params);
  2240. return { outcome: { outcome: 'selected', optionId: 'allow-once' } };
  2241. });
  2242. await client.connectWith(agent, async (connection) => {
  2243. await connection.request(acp.methods.agent.initialize, {
  2244. protocolVersion: acp.PROTOCOL_VERSION,
  2245. clientCapabilities: {},
  2246. });
  2247. await connection.request(acp.methods.agent.session.new, {
  2248. cwd: '/workspace',
  2249. mcpServers: [],
  2250. });
  2251. emitRuntimeEvent({
  2252. type: 'session.created',
  2253. timestampMs: 1,
  2254. source: 'runtime',
  2255. sessionId: 'session-child',
  2256. agentName: 'worker',
  2257. sessionType: 'branch',
  2258. parentSessionId: 'session-1',
  2259. });
  2260. emitRuntimeEvent(permissionEvent('permission-child', 'session-child'));
  2261. emitRuntimeEvent(permissionEvent('permission-unrelated', 'session-unrelated'));
  2262. const unrelatedQuestionnaire = questionnaireEvent('questionnaire-unrelated');
  2263. emitRuntimeEvent({
  2264. ...unrelatedQuestionnaire,
  2265. sessionId: 'session-unrelated',
  2266. request: {
  2267. ...unrelatedQuestionnaire.request,
  2268. requester: { sessionId: 'session-unrelated', agentName: 'mcode' },
  2269. },
  2270. });
  2271. await vi.waitFor(() =>
  2272. expect(replyPermission).toHaveBeenCalledWith('mcode', 'permission-child', 'allowOnce'),
  2273. );
  2274. await new Promise<void>((resolve) => setImmediate(resolve));
  2275. });
  2276. expect(permissionRequests).toHaveLength(1);
  2277. expect(permissionRequests[0]?.sessionId).toBe('session-1');
  2278. expect(replyPermission).not.toHaveBeenCalledWith(
  2279. 'mcode',
  2280. 'permission-unrelated',
  2281. expect.anything(),
  2282. );
  2283. expect(dismissQuestionnaire).not.toHaveBeenCalledWith('mcode', 'questionnaire-unrelated');
  2284. });
  2285. it('hydrates existing descendant ownership when attaching a persisted root Session', async () => {
  2286. const { runtime, emitRuntimeEvent, getDelegationSnapshot, replyPermission } = createRuntime();
  2287. getDelegationSnapshot.mockResolvedValue({
  2288. schemaVersion: 1,
  2289. rootSessionId: 'session-root',
  2290. members: [
  2291. {
  2292. sessionId: 'session-child',
  2293. parentSessionId: 'session-root',
  2294. agentName: 'worker',
  2295. status: 'running',
  2296. },
  2297. ],
  2298. });
  2299. const permissionRequests: acp.RequestPermissionRequest[] = [];
  2300. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  2301. const client = acp
  2302. .client({ name: 'test-client' })
  2303. .onRequest(acp.methods.client.session.requestPermission, ({ params }) => {
  2304. permissionRequests.push(params);
  2305. return { outcome: { outcome: 'selected', optionId: 'allow-once' } };
  2306. });
  2307. await client.connectWith(agent, async (connection) => {
  2308. await connection.request(acp.methods.agent.initialize, {
  2309. protocolVersion: acp.PROTOCOL_VERSION,
  2310. clientCapabilities: {},
  2311. });
  2312. await connection.request(acp.methods.agent.session.resume, {
  2313. sessionId: 'session-root',
  2314. cwd: '/workspace',
  2315. mcpServers: [],
  2316. });
  2317. emitRuntimeEvent(permissionEvent('permission-existing-child', 'session-child'));
  2318. await vi.waitFor(() =>
  2319. expect(replyPermission).toHaveBeenCalledWith(
  2320. 'mcode',
  2321. 'permission-existing-child',
  2322. 'allowOnce',
  2323. ),
  2324. );
  2325. });
  2326. expect(permissionRequests).toHaveLength(1);
  2327. expect(permissionRequests[0]?.sessionId).toBe('session-root');
  2328. });
  2329. it('fails a pending permission closed with its ACP attachment instead of applying a late grant', async () => {
  2330. const { runtime, emitRuntimeEvent, replyPermission } = createRuntime();
  2331. let markPermissionRequested!: () => void;
  2332. const permissionRequested = new Promise<void>((resolve) => {
  2333. markPermissionRequested = resolve;
  2334. });
  2335. let answerPermission: ((response: acp.RequestPermissionResponse) => void) | undefined;
  2336. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  2337. const client = acp.client({ name: 'test-client' }).onRequest(
  2338. acp.methods.client.session.requestPermission,
  2339. () =>
  2340. new Promise<acp.RequestPermissionResponse>((answer) => {
  2341. answerPermission = answer;
  2342. markPermissionRequested();
  2343. }),
  2344. );
  2345. await client.connectWith(agent, async (connection) => {
  2346. await connection.request(acp.methods.agent.initialize, {
  2347. protocolVersion: acp.PROTOCOL_VERSION,
  2348. clientCapabilities: {},
  2349. });
  2350. const session = await connection.request(acp.methods.agent.session.new, {
  2351. cwd: '/workspace',
  2352. mcpServers: [],
  2353. });
  2354. emitRuntimeEvent(permissionEvent('permission-close-race'));
  2355. await permissionRequested;
  2356. await connection.request(acp.methods.agent.session.close, { sessionId: session.sessionId });
  2357. answerPermission?.({
  2358. outcome: { outcome: 'selected', optionId: 'allow-always' },
  2359. });
  2360. await vi.waitFor(() => expect(replyPermission).toHaveBeenCalledOnce());
  2361. });
  2362. expect(replyPermission).toHaveBeenCalledWith('mcode', 'permission-close-race', 'deny');
  2363. });
  2364. it('keeps ingesting another Session while one permission request is unanswered', async () => {
  2365. const { runtime, createSession, emitRuntimeEvent, replyPermission } = createRuntime();
  2366. let nextSession = 1;
  2367. createSession.mockImplementation(async ({ workspaceDir }: { workspaceDir: string }) => ({
  2368. sessionId: `session-${nextSession++}`,
  2369. workspaceDir,
  2370. }));
  2371. const permissionRequests: string[] = [];
  2372. const updates: acp.SessionNotification[] = [];
  2373. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  2374. const client = acp
  2375. .client({ name: 'test-client' })
  2376. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params))
  2377. .onRequest(acp.methods.client.session.requestPermission, ({ params }) => {
  2378. permissionRequests.push(params.sessionId);
  2379. if (params.sessionId === 'session-1') {
  2380. return new Promise<acp.RequestPermissionResponse>(() => undefined);
  2381. }
  2382. return { outcome: { outcome: 'selected', optionId: 'deny' } };
  2383. });
  2384. await client.connectWith(agent, async (connection) => {
  2385. await connection.request(acp.methods.agent.initialize, {
  2386. protocolVersion: acp.PROTOCOL_VERSION,
  2387. clientCapabilities: {},
  2388. });
  2389. await connection.request(acp.methods.agent.session.new, {
  2390. cwd: '/workspace/one',
  2391. mcpServers: [],
  2392. });
  2393. await connection.request(acp.methods.agent.session.new, {
  2394. cwd: '/workspace/two',
  2395. mcpServers: [],
  2396. });
  2397. emitRuntimeEvent(permissionEvent('permission-a', 'session-1'));
  2398. await vi.waitFor(() => expect(permissionRequests).toEqual(['session-1']));
  2399. emitRuntimeEvent({
  2400. type: 'session.title_updated',
  2401. timestampMs: 2,
  2402. source: 'runtime',
  2403. sessionId: 'session-2',
  2404. title: 'Still responsive',
  2405. });
  2406. emitRuntimeEvent(permissionEvent('permission-b', 'session-2'));
  2407. await vi.waitFor(() =>
  2408. expect(replyPermission).toHaveBeenCalledWith('mcode', 'permission-b', 'deny'),
  2409. );
  2410. await vi.waitFor(() =>
  2411. expect(updates).toContainEqual({
  2412. sessionId: 'session-2',
  2413. update: {
  2414. sessionUpdate: 'session_info_update',
  2415. title: 'Still responsive',
  2416. updatedAt: new Date(2).toISOString(),
  2417. },
  2418. }),
  2419. );
  2420. });
  2421. });
  2422. it('bounds concurrent fail-closed replies before closing an overflowing interaction stream', async () => {
  2423. const { runtime, createSession, emitRuntimeEvent, replyPermission } = createRuntime();
  2424. let nextSession = 0;
  2425. createSession.mockImplementation(async ({ workspaceDir }: { workspaceDir: string }) => ({
  2426. sessionId: `session-${nextSession++}`,
  2427. workspaceDir,
  2428. }));
  2429. replyPermission.mockImplementation(async (_agentName, requestId) => {
  2430. if (requestId === 'permission-8') await new Promise(() => undefined);
  2431. return true;
  2432. });
  2433. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  2434. const client = acp
  2435. .client({ name: 'test-client' })
  2436. .onRequest(
  2437. acp.methods.client.session.requestPermission,
  2438. () => new Promise<acp.RequestPermissionResponse>(() => undefined),
  2439. );
  2440. await client
  2441. .connectWith(agent, async (connection) => {
  2442. await connection.request(acp.methods.agent.initialize, {
  2443. protocolVersion: acp.PROTOCOL_VERSION,
  2444. clientCapabilities: {},
  2445. });
  2446. for (let index = 0; index < 73; index += 1) {
  2447. await connection.request(acp.methods.agent.session.new, {
  2448. cwd: `/workspace/${index}`,
  2449. mcpServers: [],
  2450. });
  2451. }
  2452. for (let index = 0; index < 73; index += 1) {
  2453. emitRuntimeEvent(permissionEvent(`permission-${index}`, `session-${index}`));
  2454. }
  2455. await vi.waitFor(() => expect(connection.signal.aborted).toBe(true), { timeout: 3_000 });
  2456. })
  2457. .catch(() => undefined);
  2458. expect(replyPermission).toHaveBeenCalledWith('mcode', 'permission-72', 'deny');
  2459. });
  2460. it('keeps watching interactions after one Runtime permission reply fails', async () => {
  2461. const { runtime, emitRuntimeEvent, replyPermission } = createRuntime();
  2462. replyPermission.mockRejectedValueOnce(new Error('permission reply unavailable'));
  2463. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  2464. const client = acp
  2465. .client({ name: 'test-client' })
  2466. .onRequest(acp.methods.client.session.requestPermission, () => ({
  2467. outcome: { outcome: 'selected', optionId: 'deny' },
  2468. }));
  2469. await client.connectWith(agent, async (connection) => {
  2470. await connection.request(acp.methods.agent.initialize, {
  2471. protocolVersion: acp.PROTOCOL_VERSION,
  2472. clientCapabilities: {},
  2473. });
  2474. await connection.request(acp.methods.agent.session.new, {
  2475. cwd: '/workspace',
  2476. mcpServers: [],
  2477. });
  2478. emitRuntimeEvent(permissionEvent('permission-1'));
  2479. await vi.waitFor(() => expect(replyPermission).toHaveBeenCalledTimes(1));
  2480. emitRuntimeEvent(permissionEvent('permission-2'));
  2481. await vi.waitFor(() => expect(replyPermission).toHaveBeenCalledTimes(2));
  2482. });
  2483. expect(replyPermission).toHaveBeenLastCalledWith('mcode', 'permission-2', 'deny');
  2484. });
  2485. it('bridges Runtime questionnaires through ACP form elicitation when the client supports it', async () => {
  2486. const { runtime, emitRuntimeEvent, replyQuestionnaire } = createRuntime();
  2487. const elicitationRequests: acp.CreateElicitationRequest[] = [];
  2488. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  2489. const client = acp
  2490. .client({ name: 'test-client' })
  2491. .onRequest(acp.methods.client.elicitation.create, ({ params }) => {
  2492. elicitationRequests.push(params);
  2493. return {
  2494. action: 'accept',
  2495. content: {
  2496. approach: 'safe',
  2497. checks: ['unit'],
  2498. checks__other: 'Manual smoke',
  2499. note: 'keep it small',
  2500. },
  2501. };
  2502. });
  2503. await client.connectWith(agent, async (connection) => {
  2504. await connection.request(acp.methods.agent.initialize, {
  2505. protocolVersion: acp.PROTOCOL_VERSION,
  2506. clientCapabilities: { elicitation: { form: {} } },
  2507. });
  2508. await connection.request(acp.methods.agent.session.new, {
  2509. cwd: '/workspace',
  2510. mcpServers: [],
  2511. });
  2512. emitRuntimeEvent({
  2513. type: 'questionnaire.ask',
  2514. timestampMs: 1,
  2515. source: 'runtime',
  2516. sessionId: 'session-1',
  2517. agentName: 'mcode',
  2518. request: {
  2519. schemaVersion: 1,
  2520. id: 'questionnaire-1',
  2521. title: 'Choose settings',
  2522. requester: { sessionId: 'session-1', agentName: 'mcode' },
  2523. presentation: {
  2524. replaceComposer: false,
  2525. showProgress: false,
  2526. allowBackNavigation: false,
  2527. },
  2528. steps: [
  2529. {
  2530. id: 'approach',
  2531. question: 'Which approach?',
  2532. selectionMode: 'single',
  2533. options: [
  2534. { id: 'safe', label: 'Safe' },
  2535. { id: 'fast', label: 'Fast', description: 'Less verification' },
  2536. ],
  2537. allowOther: false,
  2538. otherPlaceholder: '',
  2539. required: true,
  2540. },
  2541. {
  2542. id: 'checks',
  2543. question: 'Which checks?',
  2544. selectionMode: 'multiple',
  2545. options: [
  2546. { id: 'unit', label: 'Unit' },
  2547. { id: 'integration', label: 'Integration' },
  2548. ],
  2549. allowOther: true,
  2550. otherPlaceholder: 'Other check',
  2551. required: false,
  2552. },
  2553. {
  2554. id: 'note',
  2555. question: 'Anything else?',
  2556. selectionMode: 'single',
  2557. allowOther: true,
  2558. otherPlaceholder: 'Notes',
  2559. required: false,
  2560. },
  2561. ],
  2562. },
  2563. });
  2564. await vi.waitFor(() => expect(replyQuestionnaire).toHaveBeenCalledOnce());
  2565. });
  2566. expect(elicitationRequests).toEqual([
  2567. {
  2568. mode: 'form',
  2569. sessionId: 'session-1',
  2570. message: 'Choose settings',
  2571. requestedSchema: {
  2572. type: 'object',
  2573. properties: {
  2574. approach: {
  2575. type: 'string',
  2576. title: 'Which approach?',
  2577. oneOf: [
  2578. { const: 'safe', title: 'Safe' },
  2579. { const: 'fast', title: 'Fast', description: 'Less verification' },
  2580. ],
  2581. },
  2582. checks: {
  2583. type: 'array',
  2584. title: 'Which checks?',
  2585. items: {
  2586. anyOf: [
  2587. { const: 'unit', title: 'Unit' },
  2588. { const: 'integration', title: 'Integration' },
  2589. ],
  2590. },
  2591. },
  2592. checks__other: {
  2593. type: 'string',
  2594. title: 'Which checks? — Other',
  2595. description: 'Other check',
  2596. },
  2597. note: {
  2598. type: 'string',
  2599. title: 'Anything else?',
  2600. description: 'Notes',
  2601. },
  2602. },
  2603. required: ['approach'],
  2604. },
  2605. },
  2606. ]);
  2607. expect(replyQuestionnaire).toHaveBeenCalledWith('mcode', 'questionnaire-1', [
  2608. { stepId: 'approach', selectedOptionIds: ['safe'] },
  2609. {
  2610. stepId: 'checks',
  2611. selectedOptionIds: ['unit'],
  2612. selectedOther: true,
  2613. otherText: 'Manual smoke',
  2614. },
  2615. { stepId: 'note', selectedOther: true, otherText: 'keep it small' },
  2616. ]);
  2617. });
  2618. it('preserves option identities and Other fields across normalized questionnaire shapes', async () => {
  2619. const { runtime, emitRuntimeEvent, replyQuestionnaire } = createRuntime();
  2620. const requests: acp.CreateElicitationRequest[] = [];
  2621. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  2622. const client = acp
  2623. .client({ name: 'test-client' })
  2624. .onRequest(acp.methods.client.elicitation.create, ({ params }) => {
  2625. requests.push(params);
  2626. return {
  2627. action: 'accept',
  2628. content: {
  2629. channel: 'Shared',
  2630. delivery: 'safe',
  2631. delivery__other: 'Custom delivery',
  2632. legacy: 'Shared',
  2633. tags: 'Manual tag',
  2634. },
  2635. };
  2636. });
  2637. await client.connectWith(agent, async (connection) => {
  2638. await connection.request(acp.methods.agent.initialize, {
  2639. protocolVersion: acp.PROTOCOL_VERSION,
  2640. clientCapabilities: { elicitation: { form: {} } },
  2641. });
  2642. await connection.request(acp.methods.agent.session.new, {
  2643. cwd: '/workspace',
  2644. mcpServers: [],
  2645. });
  2646. emitRuntimeEvent({
  2647. type: 'questionnaire.ask',
  2648. timestampMs: 1,
  2649. source: 'runtime',
  2650. sessionId: 'session-1',
  2651. agentName: 'mcode',
  2652. request: {
  2653. schemaVersion: 1,
  2654. id: 'questionnaire-identities',
  2655. requester: { sessionId: 'session-1', agentName: 'mcode' },
  2656. presentation: {
  2657. replaceComposer: false,
  2658. showProgress: false,
  2659. allowBackNavigation: false,
  2660. },
  2661. steps: [
  2662. {
  2663. id: 'channel',
  2664. question: 'Channel?',
  2665. selectionMode: 'single',
  2666. options: [
  2667. { id: 'stable', label: 'Shared' },
  2668. { id: 'Shared', label: 'Preview' },
  2669. ],
  2670. allowOther: true,
  2671. otherPlaceholder: 'Another channel',
  2672. required: true,
  2673. },
  2674. {
  2675. id: 'delivery',
  2676. question: 'Delivery?',
  2677. selectionMode: 'single',
  2678. options: [{ id: 'safe', label: 'Safe' }],
  2679. allowOther: true,
  2680. otherPlaceholder: 'Another delivery',
  2681. required: true,
  2682. },
  2683. {
  2684. id: 'legacy',
  2685. question: 'Legacy collision?',
  2686. selectionMode: 'single',
  2687. options: [
  2688. { id: 'first', label: 'Shared' },
  2689. { id: 'second', label: 'Shared' },
  2690. ],
  2691. allowOther: true,
  2692. otherPlaceholder: 'Explicit legacy Other',
  2693. required: false,
  2694. },
  2695. {
  2696. id: 'tags',
  2697. question: 'Tags?',
  2698. selectionMode: 'multiple',
  2699. options: [],
  2700. allowOther: true,
  2701. otherPlaceholder: 'Custom tags',
  2702. required: true,
  2703. },
  2704. ],
  2705. },
  2706. });
  2707. await vi.waitFor(() => expect(replyQuestionnaire).toHaveBeenCalledOnce());
  2708. });
  2709. expect(requests[0]?.requestedSchema.properties).toEqual({
  2710. channel: {
  2711. type: 'string',
  2712. title: 'Channel?',
  2713. oneOf: [
  2714. { const: 'stable', title: 'Shared' },
  2715. { const: 'Shared', title: 'Preview' },
  2716. ],
  2717. },
  2718. channel__other: {
  2719. type: 'string',
  2720. title: 'Channel? — Other',
  2721. description: 'Another channel',
  2722. },
  2723. delivery: {
  2724. type: 'string',
  2725. title: 'Delivery?',
  2726. oneOf: [{ const: 'safe', title: 'Safe' }],
  2727. },
  2728. delivery__other: {
  2729. type: 'string',
  2730. title: 'Delivery? — Other',
  2731. description: 'Another delivery',
  2732. },
  2733. legacy: {
  2734. type: 'string',
  2735. title: 'Legacy collision?',
  2736. oneOf: [
  2737. { const: 'first', title: 'Shared' },
  2738. { const: 'second', title: 'Shared' },
  2739. ],
  2740. },
  2741. legacy__other: {
  2742. type: 'string',
  2743. title: 'Legacy collision? — Other',
  2744. description: 'Explicit legacy Other',
  2745. },
  2746. tags: {
  2747. type: 'string',
  2748. title: 'Tags?',
  2749. description: 'Custom tags',
  2750. },
  2751. });
  2752. expect(replyQuestionnaire).toHaveBeenCalledWith('mcode', 'questionnaire-identities', [
  2753. { stepId: 'channel', selectedOptionIds: ['Shared'] },
  2754. { stepId: 'delivery', selectedOther: true, otherText: 'Custom delivery' },
  2755. { stepId: 'legacy', skipped: true },
  2756. { stepId: 'tags', selectedOther: true, otherText: 'Manual tag' },
  2757. ]);
  2758. });
  2759. it('dismisses a pending questionnaire when its ACP attachment closes', async () => {
  2760. const { runtime, emitRuntimeEvent, replyQuestionnaire, dismissQuestionnaire } = createRuntime();
  2761. let markQuestionnaireRequested!: () => void;
  2762. const questionnaireRequested = new Promise<void>((resolve) => {
  2763. markQuestionnaireRequested = resolve;
  2764. });
  2765. let answerQuestionnaire: ((response: acp.CreateElicitationResponse) => void) | undefined;
  2766. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  2767. const client = acp.client({ name: 'test-client' }).onRequest(
  2768. acp.methods.client.elicitation.create,
  2769. () =>
  2770. new Promise<acp.CreateElicitationResponse>((answer) => {
  2771. answerQuestionnaire = answer;
  2772. markQuestionnaireRequested();
  2773. }),
  2774. );
  2775. await client.connectWith(agent, async (connection) => {
  2776. await connection.request(acp.methods.agent.initialize, {
  2777. protocolVersion: acp.PROTOCOL_VERSION,
  2778. clientCapabilities: { elicitation: { form: {} } },
  2779. });
  2780. const session = await connection.request(acp.methods.agent.session.new, {
  2781. cwd: '/workspace',
  2782. mcpServers: [],
  2783. });
  2784. emitRuntimeEvent(questionnaireEvent('questionnaire-close-race'));
  2785. await questionnaireRequested;
  2786. await connection.request(acp.methods.agent.session.close, { sessionId: session.sessionId });
  2787. answerQuestionnaire?.({ action: 'accept', content: { approach: 'Safe' } });
  2788. await vi.waitFor(() =>
  2789. expect(dismissQuestionnaire).toHaveBeenCalledWith('mcode', 'questionnaire-close-race'),
  2790. );
  2791. });
  2792. expect(replyQuestionnaire).not.toHaveBeenCalled();
  2793. });
  2794. it('continues a questionnaire-blocked prompt after the ACP client answers', async () => {
  2795. const { runtime, emitRuntimeEvent, replyQuestionnaire, steer } = createRuntime([
  2796. {
  2797. type: 'delta',
  2798. toolCalls: [
  2799. {
  2800. id: 'ask-user-call-1',
  2801. name: 'ask_user',
  2802. input: { mode: 'questionnaire' },
  2803. output: 'Questionnaire is waiting for the local user.',
  2804. status: 'completed',
  2805. },
  2806. ],
  2807. },
  2808. { type: 'session-status', status: 'finished' },
  2809. ]);
  2810. let releaseBlockedRun: (() => void) | undefined;
  2811. const blockedRunGate = new Promise<void>((resolve) => {
  2812. releaseBlockedRun = resolve;
  2813. });
  2814. vi.mocked(runtime.sendMessage).mockImplementation(() =>
  2815. (async function* blockedRunEvents() {
  2816. await blockedRunGate;
  2817. yield {
  2818. type: 'generic',
  2819. eventType: 'runtime.action-required',
  2820. data: { kind: 'questionnaire' },
  2821. turnId: 'turn-1',
  2822. } as const;
  2823. })(),
  2824. );
  2825. vi.mocked(runtime.replyQuestionnaire).mockImplementation(async () => {
  2826. emitRuntimeEvent({
  2827. type: 'session.start',
  2828. timestampMs: 3,
  2829. source: 'runtime',
  2830. sessionId: 'session-1',
  2831. turnId: 'turn-2',
  2832. queueItemIds: [],
  2833. });
  2834. return true;
  2835. });
  2836. vi.mocked(runtime.watchSessionTurn).mockImplementation((_sessionId, turnId) =>
  2837. (async function* continuedTurnEvents() {
  2838. expect(turnId).toBe('turn-2');
  2839. yield {
  2840. type: 'delta',
  2841. messageId: 'message-continued',
  2842. role: 'assistant',
  2843. content: 'Continuing after your answer.',
  2844. } as const;
  2845. emitRuntimeEvent({
  2846. type: 'session.finish',
  2847. timestampMs: 4,
  2848. source: 'runtime',
  2849. sessionId: 'session-1',
  2850. turnId: 'turn-2',
  2851. queueItemIds: [],
  2852. });
  2853. yield { type: 'session-status', status: 'finished' } as const;
  2854. })(),
  2855. );
  2856. const updates: acp.SessionNotification[] = [];
  2857. const agent = createTuiAcpAgent({
  2858. runtime,
  2859. version: '1.2.3',
  2860. createTurnId: () => 'turn-1',
  2861. });
  2862. const client = acp
  2863. .client({ name: 'test-client' })
  2864. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params))
  2865. .onRequest(acp.methods.client.elicitation.create, () => ({
  2866. action: 'accept',
  2867. content: { approach: 'safe' },
  2868. }));
  2869. await client.connectWith(agent, async (connection) => {
  2870. await connection.request(acp.methods.agent.initialize, {
  2871. protocolVersion: acp.PROTOCOL_VERSION,
  2872. clientCapabilities: { elicitation: { form: {} } },
  2873. });
  2874. const session = await connection.request(acp.methods.agent.session.new, {
  2875. cwd: '/workspace',
  2876. mcpServers: [],
  2877. });
  2878. const prompt = connection.request(acp.methods.agent.session.prompt, {
  2879. sessionId: session.sessionId,
  2880. prompt: [{ type: 'text', text: 'Ask me a question' }],
  2881. });
  2882. await vi.waitFor(() => expect(runtime.sendMessage).toHaveBeenCalledOnce());
  2883. emitRuntimeEvent({
  2884. type: 'questionnaire.ask',
  2885. timestampMs: 1,
  2886. source: 'runtime',
  2887. sessionId: 'session-1',
  2888. agentName: 'mcode',
  2889. request: {
  2890. schemaVersion: 1,
  2891. id: 'questionnaire-continuation',
  2892. title: 'Choose an approach',
  2893. requester: { sessionId: 'session-1', agentName: 'mcode' },
  2894. presentation: {
  2895. replaceComposer: false,
  2896. showProgress: false,
  2897. allowBackNavigation: false,
  2898. },
  2899. steps: [
  2900. {
  2901. id: 'approach',
  2902. question: 'Which approach?',
  2903. selectionMode: 'single',
  2904. options: [{ id: 'safe', label: 'Safe' }],
  2905. allowOther: false,
  2906. otherPlaceholder: '',
  2907. required: true,
  2908. },
  2909. ],
  2910. },
  2911. });
  2912. await vi.waitFor(() => expect(replyQuestionnaire).toHaveBeenCalledOnce());
  2913. await expect(
  2914. connection.request('mcode/session/steer', {
  2915. sessionId: session.sessionId,
  2916. text: 'Do not activate another turn',
  2917. }),
  2918. ).rejects.toThrow('admitted, active ACP prompt Turn');
  2919. expect(steer).not.toHaveBeenCalled();
  2920. releaseBlockedRun?.();
  2921. await expect(prompt).resolves.toEqual({ stopReason: 'end_turn' });
  2922. });
  2923. expect(updates).toContainEqual({
  2924. sessionId: 'session-1',
  2925. update: {
  2926. sessionUpdate: 'agent_message_chunk',
  2927. messageId: 'message-continued',
  2928. content: { type: 'text', text: 'Continuing after your answer.' },
  2929. },
  2930. });
  2931. });
  2932. it('falls back to an ACP permission choice when form elicitation fails', async () => {
  2933. const { runtime, emitRuntimeEvent, replyQuestionnaire } = createRuntime();
  2934. const permissionRequests: acp.RequestPermissionRequest[] = [];
  2935. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  2936. const client = acp
  2937. .client({ name: 'test-client' })
  2938. .onRequest(acp.methods.client.elicitation.create, () => {
  2939. throw new Error('elicitation method unavailable');
  2940. })
  2941. .onRequest(acp.methods.client.session.requestPermission, ({ params }) => {
  2942. permissionRequests.push(params);
  2943. return {
  2944. outcome: {
  2945. outcome: 'selected',
  2946. optionId: 'questionnaire:questionnaire-form-fallback:safe',
  2947. },
  2948. };
  2949. });
  2950. await client.connectWith(agent, async (connection) => {
  2951. await connection.request(acp.methods.agent.initialize, {
  2952. protocolVersion: acp.PROTOCOL_VERSION,
  2953. clientCapabilities: { elicitation: { form: {} } },
  2954. });
  2955. await connection.request(acp.methods.agent.session.new, {
  2956. cwd: '/workspace',
  2957. mcpServers: [],
  2958. });
  2959. emitRuntimeEvent({
  2960. type: 'questionnaire.ask',
  2961. timestampMs: 1,
  2962. source: 'runtime',
  2963. sessionId: 'session-1',
  2964. agentName: 'mcode',
  2965. request: {
  2966. schemaVersion: 1,
  2967. id: 'questionnaire-form-fallback',
  2968. requester: { sessionId: 'session-1', agentName: 'mcode' },
  2969. presentation: {
  2970. replaceComposer: false,
  2971. showProgress: false,
  2972. allowBackNavigation: false,
  2973. },
  2974. steps: [
  2975. {
  2976. id: 'approach',
  2977. question: 'Which approach?',
  2978. selectionMode: 'single',
  2979. options: [{ id: 'safe', label: 'Safe' }],
  2980. allowOther: false,
  2981. otherPlaceholder: '',
  2982. required: true,
  2983. },
  2984. ],
  2985. },
  2986. });
  2987. await vi.waitFor(() => expect(replyQuestionnaire).toHaveBeenCalledOnce());
  2988. });
  2989. expect(permissionRequests).toHaveLength(1);
  2990. expect(replyQuestionnaire).toHaveBeenCalledWith('mcode', 'questionnaire-form-fallback', [
  2991. { stepId: 'approach', selectedOptionIds: ['safe'] },
  2992. ]);
  2993. });
  2994. it('falls back to the first ACP permission choice for a multi-step questionnaire', async () => {
  2995. const { runtime, emitRuntimeEvent, replyQuestionnaire, dismissQuestionnaire } = createRuntime();
  2996. const permissionRequests: acp.RequestPermissionRequest[] = [];
  2997. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  2998. const client = acp
  2999. .client({ name: 'test-client' })
  3000. .onRequest(acp.methods.client.session.requestPermission, ({ params }) => {
  3001. permissionRequests.push(params);
  3002. return {
  3003. outcome: {
  3004. outcome: 'selected',
  3005. optionId: 'questionnaire:questionnaire-2:fast',
  3006. },
  3007. };
  3008. });
  3009. await client.connectWith(agent, async (connection) => {
  3010. await connection.request(acp.methods.agent.initialize, {
  3011. protocolVersion: acp.PROTOCOL_VERSION,
  3012. clientCapabilities: {},
  3013. });
  3014. await connection.request(acp.methods.agent.session.new, {
  3015. cwd: '/workspace',
  3016. mcpServers: [],
  3017. });
  3018. emitRuntimeEvent({
  3019. type: 'questionnaire.ask',
  3020. timestampMs: 1,
  3021. source: 'runtime',
  3022. sessionId: 'session-1',
  3023. agentName: 'mcode',
  3024. request: {
  3025. schemaVersion: 1,
  3026. id: 'questionnaire-2',
  3027. requester: { sessionId: 'session-1', agentName: 'mcode' },
  3028. presentation: {
  3029. replaceComposer: false,
  3030. showProgress: false,
  3031. allowBackNavigation: false,
  3032. },
  3033. steps: [
  3034. {
  3035. id: 'approach',
  3036. question: 'Which approach?',
  3037. selectionMode: 'single',
  3038. options: [
  3039. { id: 'safe', label: 'Safe' },
  3040. { id: 'fast', label: 'Fast' },
  3041. ],
  3042. allowOther: false,
  3043. otherPlaceholder: '',
  3044. required: true,
  3045. },
  3046. {
  3047. id: 'depth',
  3048. question: 'How deep should the review go?',
  3049. selectionMode: 'single',
  3050. options: [
  3051. { id: 'overview', label: 'Overview' },
  3052. { id: 'deep', label: 'Deep' },
  3053. ],
  3054. allowOther: false,
  3055. otherPlaceholder: '',
  3056. required: true,
  3057. },
  3058. ],
  3059. },
  3060. });
  3061. await vi.waitFor(() => expect(replyQuestionnaire).toHaveBeenCalledOnce());
  3062. });
  3063. expect(permissionRequests).toEqual([
  3064. {
  3065. sessionId: 'session-1',
  3066. toolCall: {
  3067. toolCallId: 'questionnaire-2',
  3068. title: 'Which approach?',
  3069. kind: 'other',
  3070. status: 'pending',
  3071. },
  3072. options: [
  3073. {
  3074. optionId: 'questionnaire:questionnaire-2:safe',
  3075. name: 'Safe',
  3076. kind: 'allow_once',
  3077. },
  3078. {
  3079. optionId: 'questionnaire:questionnaire-2:fast',
  3080. name: 'Fast',
  3081. kind: 'allow_once',
  3082. },
  3083. { optionId: 'questionnaire:questionnaire-2:cancel', name: 'Cancel', kind: 'reject_once' },
  3084. ],
  3085. },
  3086. ]);
  3087. expect(replyQuestionnaire).toHaveBeenCalledWith('mcode', 'questionnaire-2', [
  3088. { stepId: 'approach', selectedOptionIds: ['fast'] },
  3089. { stepId: 'depth', skipped: true },
  3090. ]);
  3091. expect(dismissQuestionnaire).not.toHaveBeenCalled();
  3092. });
  3093. it('cancels an active prompt when the client sends session/cancel', async () => {
  3094. const { runtime, sendMessage, abortSession } = createRuntime([], { holdRunUntilAbort: true });
  3095. const agent = createTuiAcpAgent({
  3096. runtime,
  3097. version: '1.2.3',
  3098. createTurnId: () => 'turn-1',
  3099. });
  3100. const client = acp.client({ name: 'test-client' });
  3101. await client.connectWith(agent, async (connection) => {
  3102. await connection.request(acp.methods.agent.initialize, {
  3103. protocolVersion: acp.PROTOCOL_VERSION,
  3104. clientCapabilities: {},
  3105. });
  3106. const session = await connection.request(acp.methods.agent.session.new, {
  3107. cwd: '/workspace',
  3108. mcpServers: [],
  3109. });
  3110. const prompt = connection.request(acp.methods.agent.session.prompt, {
  3111. sessionId: session.sessionId,
  3112. prompt: [{ type: 'text', text: 'Keep running' }],
  3113. });
  3114. await vi.waitFor(() => expect(sendMessage).toHaveBeenCalledOnce());
  3115. await connection.notify(acp.methods.agent.session.cancel, { sessionId: session.sessionId });
  3116. await expect(prompt).resolves.toEqual({ stopReason: 'cancelled' });
  3117. });
  3118. expect(abortSession).toHaveBeenCalledWith({
  3119. id: 'session-1',
  3120. turnId: 'turn-1',
  3121. reason: 'user_stop',
  3122. });
  3123. });
  3124. it('rejects managed login when the account is warning but the token is missing', async () => {
  3125. const { runtime, createSession } = createRuntime([], {
  3126. accountStatus: {
  3127. status: 'warning',
  3128. modelSource: 'token-plan',
  3129. authMode: 'managed-login',
  3130. managedTokenPresent: false,
  3131. warnings: ['Managed token is missing.'],
  3132. },
  3133. });
  3134. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  3135. const client = acp.client({ name: 'test-client' });
  3136. await client.connectWith(agent, async (connection) => {
  3137. await connection.request(acp.methods.agent.initialize, {
  3138. protocolVersion: acp.PROTOCOL_VERSION,
  3139. clientCapabilities: { auth: { terminal: true } },
  3140. });
  3141. await expect(
  3142. connection.request(acp.methods.agent.session.new, {
  3143. cwd: '/workspace',
  3144. mcpServers: [],
  3145. }),
  3146. ).rejects.toThrow('mcode login');
  3147. });
  3148. expect(createSession).not.toHaveBeenCalled();
  3149. });
  3150. it('honors JSON-RPC request cancellation for session/prompt', async () => {
  3151. const { runtime, sendMessage, abortSession } = createRuntime([], { holdRunUntilAbort: true });
  3152. const agent = createTuiAcpAgent({
  3153. runtime,
  3154. version: '1.2.3',
  3155. createTurnId: () => 'turn-1',
  3156. });
  3157. const client = acp.client({ name: 'test-client' });
  3158. await client.connectWith(agent, async (connection) => {
  3159. await connection.request(acp.methods.agent.initialize, {
  3160. protocolVersion: acp.PROTOCOL_VERSION,
  3161. clientCapabilities: {},
  3162. });
  3163. const session = await connection.request(acp.methods.agent.session.new, {
  3164. cwd: '/workspace',
  3165. mcpServers: [],
  3166. });
  3167. const cancellation = new AbortController();
  3168. const prompt = connection.request(
  3169. acp.methods.agent.session.prompt,
  3170. {
  3171. sessionId: session.sessionId,
  3172. prompt: [{ type: 'text', text: 'Keep running' }],
  3173. },
  3174. { cancellationSignal: cancellation.signal },
  3175. );
  3176. await vi.waitFor(() => expect(sendMessage).toHaveBeenCalledOnce());
  3177. cancellation.abort();
  3178. await expect(prompt).resolves.toEqual({ stopReason: 'cancelled' });
  3179. });
  3180. expect(abortSession).toHaveBeenCalledWith({
  3181. id: 'session-1',
  3182. turnId: 'turn-1',
  3183. reason: 'user_stop',
  3184. });
  3185. });
  3186. it('suppresses command output when JSON-RPC cancellation arrives during command execution', async () => {
  3187. const { runtime, requestCompaction, sendMessage } = createRuntime();
  3188. let releaseCompaction!: () => void;
  3189. requestCompaction.mockImplementation(
  3190. () =>
  3191. new Promise((resolve) => {
  3192. releaseCompaction = () => resolve({ success: true });
  3193. }),
  3194. );
  3195. const updates: acp.SessionNotification[] = [];
  3196. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  3197. const client = acp
  3198. .client({ name: 'test-client' })
  3199. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
  3200. await client.connectWith(agent, async (connection) => {
  3201. await connection.request(acp.methods.agent.initialize, {
  3202. protocolVersion: acp.PROTOCOL_VERSION,
  3203. clientCapabilities: {},
  3204. });
  3205. const session = await connection.request(acp.methods.agent.session.new, {
  3206. cwd: '/workspace',
  3207. mcpServers: [],
  3208. });
  3209. const cancellation = new AbortController();
  3210. const prompt = connection.request(
  3211. acp.methods.agent.session.prompt,
  3212. {
  3213. sessionId: session.sessionId,
  3214. prompt: [{ type: 'text', text: '/compact' }],
  3215. },
  3216. { cancellationSignal: cancellation.signal },
  3217. );
  3218. await vi.waitFor(() => expect(requestCompaction).toHaveBeenCalledOnce());
  3219. cancellation.abort();
  3220. releaseCompaction();
  3221. await expect(prompt).resolves.toEqual({ stopReason: 'cancelled' });
  3222. });
  3223. expect(sendMessage).not.toHaveBeenCalled();
  3224. expect(updates).not.toContainEqual(
  3225. expect.objectContaining({
  3226. update: expect.objectContaining({ sessionUpdate: 'agent_message_chunk' }),
  3227. }),
  3228. );
  3229. });
  3230. it('passes client-provided stdio MCP servers into the Runtime session', async () => {
  3231. const { runtime, createSession } = createRuntime();
  3232. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  3233. const client = acp.client({ name: 'test-client' });
  3234. await client.connectWith(agent, async (connection) => {
  3235. await connection.request(acp.methods.agent.initialize, {
  3236. protocolVersion: acp.PROTOCOL_VERSION,
  3237. clientCapabilities: {},
  3238. });
  3239. await expect(
  3240. connection.request(acp.methods.agent.session.new, {
  3241. cwd: '/workspace',
  3242. mcpServers: [
  3243. {
  3244. name: 'client-tools',
  3245. command: '/usr/local/bin/client-tools',
  3246. args: ['serve'],
  3247. env: [{ name: 'CLIENT_TOKEN', value: 'test-token' }],
  3248. },
  3249. ],
  3250. }),
  3251. ).resolves.toMatchObject({
  3252. sessionId: 'session-1',
  3253. modes: { currentModeId: 'default' },
  3254. configOptions: expect.arrayContaining([expect.objectContaining({ id: 'permissionMode' })]),
  3255. });
  3256. });
  3257. expect(createSession).toHaveBeenCalledWith({
  3258. workspaceDir: '/workspace',
  3259. mcpServers: [
  3260. {
  3261. name: 'client-tools',
  3262. type: 'stdio',
  3263. command: '/usr/local/bin/client-tools',
  3264. args: ['serve'],
  3265. env: { CLIENT_TOKEN: 'test-token' },
  3266. },
  3267. ],
  3268. });
  3269. });
  3270. it('passes client-provided HTTP and SSE MCP servers into the Runtime session', async () => {
  3271. const { runtime, createSession } = createRuntime();
  3272. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  3273. const client = acp.client({ name: 'test-client' });
  3274. await client.connectWith(agent, async (connection) => {
  3275. await connection.request(acp.methods.agent.initialize, {
  3276. protocolVersion: acp.PROTOCOL_VERSION,
  3277. clientCapabilities: {},
  3278. });
  3279. await expect(
  3280. connection.request(acp.methods.agent.session.new, {
  3281. cwd: '/workspace',
  3282. mcpServers: [
  3283. {
  3284. name: 'http-tools',
  3285. type: 'http',
  3286. url: 'https://example.com/mcp',
  3287. headers: [{ name: 'Authorization', value: 'Bearer http-token' }],
  3288. },
  3289. {
  3290. name: 'sse-tools',
  3291. type: 'sse',
  3292. url: 'https://example.com/sse',
  3293. headers: [{ name: 'X-Client', value: 'acp' }],
  3294. },
  3295. ],
  3296. }),
  3297. ).resolves.toMatchObject({
  3298. sessionId: 'session-1',
  3299. modes: { currentModeId: 'default' },
  3300. configOptions: expect.arrayContaining([expect.objectContaining({ id: 'permissionMode' })]),
  3301. });
  3302. });
  3303. expect(createSession).toHaveBeenCalledWith({
  3304. workspaceDir: '/workspace',
  3305. mcpServers: [
  3306. {
  3307. name: 'http-tools',
  3308. type: 'http',
  3309. url: 'https://example.com/mcp',
  3310. headers: { Authorization: 'Bearer http-token' },
  3311. },
  3312. {
  3313. name: 'sse-tools',
  3314. type: 'sse',
  3315. url: 'https://example.com/sse',
  3316. headers: { 'X-Client': 'acp' },
  3317. },
  3318. ],
  3319. });
  3320. });
  3321. it('applies mode intent to the next prompt and exposes Runtime-backed configuration', async () => {
  3322. const { runtime, getSession, sendMessage, setPermissionMode, selectSessionModel } =
  3323. createRuntime(
  3324. [
  3325. { type: 'delta', messageId: 'message-1', role: 'assistant', content: 'Planned.' },
  3326. { type: 'session-status', status: 'finished' },
  3327. ],
  3328. {
  3329. models: [
  3330. {
  3331. providerId: 'minimax',
  3332. modelId: 'm3',
  3333. displayName: 'MiniMax M3',
  3334. selected: true,
  3335. effortOptions: ['low', 'high'],
  3336. thinkingConfig: { defaultValue: 'low' },
  3337. },
  3338. ],
  3339. },
  3340. );
  3341. getSession
  3342. .mockResolvedValueOnce({ sessionId: 'session-1', workspaceDir: '/workspace' })
  3343. .mockResolvedValueOnce({ sessionId: 'session-1', workspaceDir: '/workspace' })
  3344. .mockResolvedValueOnce({ sessionId: 'session-1', workspaceDir: '/workspace' })
  3345. .mockResolvedValueOnce({
  3346. sessionId: 'session-1',
  3347. workspaceDir: '/workspace',
  3348. model: { providerId: 'minimax', modelId: 'm3', thinking: { effort: 'low' } },
  3349. })
  3350. .mockResolvedValueOnce({
  3351. sessionId: 'session-1',
  3352. workspaceDir: '/workspace',
  3353. model: { providerId: 'minimax', modelId: 'm3', thinking: { effort: 'high' } },
  3354. })
  3355. .mockResolvedValue({
  3356. sessionId: 'session-1',
  3357. workspaceDir: '/workspace',
  3358. interactionMode: 'plan',
  3359. model: { providerId: 'minimax', modelId: 'm3', thinking: { effort: 'low' } },
  3360. });
  3361. const updates: acp.SessionNotification[] = [];
  3362. const agent = createTuiAcpAgent({ runtime, version: '1.2.3', createTurnId: () => 'turn-1' });
  3363. const client = acp
  3364. .client({ name: 'test-client' })
  3365. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
  3366. await client.connectWith(agent, async (connection) => {
  3367. await connection.request(acp.methods.agent.initialize, {
  3368. protocolVersion: acp.PROTOCOL_VERSION,
  3369. clientCapabilities: {},
  3370. });
  3371. const session = await connection.request(acp.methods.agent.session.new, {
  3372. cwd: '/workspace',
  3373. mcpServers: [],
  3374. });
  3375. expect(session.configOptions).toEqual(
  3376. expect.arrayContaining([
  3377. expect.objectContaining({ id: 'permissionMode', currentValue: 'default' }),
  3378. expect.objectContaining({ id: 'model' }),
  3379. expect.objectContaining({ id: 'thinkingEffort', currentValue: 'low' }),
  3380. ]),
  3381. );
  3382. await expect(
  3383. connection.request(acp.methods.agent.session.setMode, {
  3384. sessionId: session.sessionId,
  3385. modeId: 'plan',
  3386. }),
  3387. ).resolves.toEqual({ _meta: { 'minimax-code/transition': 'next_prompt' } });
  3388. await expect(
  3389. connection.request(acp.methods.agent.session.setConfigOption, {
  3390. sessionId: session.sessionId,
  3391. configId: 'permissionMode',
  3392. value: 'auto',
  3393. }),
  3394. ).resolves.toEqual(expect.objectContaining({ configOptions: expect.any(Array) }));
  3395. await expect(
  3396. connection.request(acp.methods.agent.session.setConfigOption, {
  3397. sessionId: session.sessionId,
  3398. configId: 'model',
  3399. value: 'm:minimax:m3:u',
  3400. }),
  3401. ).resolves.toEqual(expect.objectContaining({ configOptions: expect.any(Array) }));
  3402. await expect(
  3403. connection.request(acp.methods.agent.session.setConfigOption, {
  3404. sessionId: session.sessionId,
  3405. configId: 'thinkingEffort',
  3406. value: 'high',
  3407. }),
  3408. ).resolves.toEqual(expect.objectContaining({ configOptions: expect.any(Array) }));
  3409. await expect(
  3410. connection.request(acp.methods.agent.session.prompt, {
  3411. sessionId: session.sessionId,
  3412. prompt: [{ type: 'text', text: 'Make a plan' }],
  3413. }),
  3414. ).resolves.toEqual({ stopReason: 'end_turn' });
  3415. });
  3416. expect(setPermissionMode).toHaveBeenCalledWith('auto');
  3417. expect(selectSessionModel).toHaveBeenCalledWith(
  3418. { providerId: 'minimax', modelId: 'm3' },
  3419. 'session-1',
  3420. );
  3421. expect(selectSessionModel).toHaveBeenCalledWith(
  3422. {
  3423. providerId: 'minimax',
  3424. modelId: 'm3',
  3425. thinking: { effort: 'high' },
  3426. },
  3427. 'session-1',
  3428. );
  3429. expect(sendMessage).toHaveBeenCalledWith(
  3430. expect.objectContaining({ id: 'session-1', clientIntent: 'plan-entry' }),
  3431. expect.any(AbortSignal),
  3432. );
  3433. expect(updates).toContainEqual({
  3434. sessionId: 'session-1',
  3435. update: { sessionUpdate: 'current_mode_update', currentModeId: 'plan' },
  3436. });
  3437. });
  3438. it('returns a successful permission-mode change when a background Session broadcast stalls', async () => {
  3439. const { runtime, getPermissionMode, setPermissionMode } = createRuntime();
  3440. const agent = createTuiAcpAgent({
  3441. runtime,
  3442. version: '1.2.3',
  3443. runtimeEventProjectionTimeoutMs: 10,
  3444. });
  3445. const client = acp
  3446. .client({ name: 'test-client' })
  3447. .onNotification(acp.methods.client.session.update, () => undefined);
  3448. await client
  3449. .connectWith(agent, async (connection) => {
  3450. await connection.request(acp.methods.agent.initialize, {
  3451. protocolVersion: acp.PROTOCOL_VERSION,
  3452. clientCapabilities: {},
  3453. });
  3454. const session = await connection.request(acp.methods.agent.session.new, {
  3455. cwd: '/workspace',
  3456. mcpServers: [],
  3457. });
  3458. getPermissionMode
  3459. .mockImplementationOnce(() => new Promise(() => undefined))
  3460. .mockResolvedValue('auto');
  3461. await expect(
  3462. connection.request(acp.methods.agent.session.setConfigOption, {
  3463. sessionId: session.sessionId,
  3464. configId: 'permissionMode',
  3465. value: 'auto',
  3466. }),
  3467. ).resolves.toEqual(expect.objectContaining({ configOptions: expect.any(Array) }));
  3468. await vi.waitFor(() => expect(connection.signal.aborted).toBe(true));
  3469. })
  3470. .catch(() => undefined);
  3471. expect(setPermissionMode).toHaveBeenCalledWith('auto');
  3472. });
  3473. it('serializes process permission writes across close and another Session', async () => {
  3474. const { runtime, createSession, setPermissionMode } = createRuntime();
  3475. let nextSession = 1;
  3476. createSession.mockImplementation(async ({ workspaceDir }: { workspaceDir: string }) => ({
  3477. sessionId: `session-${nextSession++}`,
  3478. workspaceDir,
  3479. }));
  3480. let releaseOldWrite!: () => void;
  3481. const applied: string[] = [];
  3482. setPermissionMode
  3483. .mockImplementationOnce(
  3484. (mode) =>
  3485. new Promise((resolve) => {
  3486. releaseOldWrite = () => {
  3487. applied.push(mode);
  3488. resolve(mode);
  3489. };
  3490. }),
  3491. )
  3492. .mockImplementation(async (mode) => {
  3493. applied.push(mode);
  3494. return mode;
  3495. });
  3496. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  3497. const client = acp.client({ name: 'test-client' });
  3498. await client.connectWith(agent, async (connection) => {
  3499. await connection.request(acp.methods.agent.initialize, {
  3500. protocolVersion: acp.PROTOCOL_VERSION,
  3501. clientCapabilities: {},
  3502. });
  3503. const first = await connection.request(acp.methods.agent.session.new, {
  3504. cwd: '/workspace/first',
  3505. mcpServers: [],
  3506. });
  3507. const second = await connection.request(acp.methods.agent.session.new, {
  3508. cwd: '/workspace/second',
  3509. mcpServers: [],
  3510. });
  3511. const oldWrite = connection.request(acp.methods.agent.session.setConfigOption, {
  3512. sessionId: first.sessionId,
  3513. configId: 'permissionMode',
  3514. value: 'bypassPermissions',
  3515. });
  3516. void oldWrite.catch(() => undefined);
  3517. await vi.waitFor(() => expect(setPermissionMode).toHaveBeenCalledOnce());
  3518. await connection.request(acp.methods.agent.session.close, { sessionId: first.sessionId });
  3519. const newWrite = connection.request(acp.methods.agent.session.setConfigOption, {
  3520. sessionId: second.sessionId,
  3521. configId: 'permissionMode',
  3522. value: 'default',
  3523. });
  3524. await new Promise<void>((resolve) => setImmediate(resolve));
  3525. expect(setPermissionMode).toHaveBeenCalledOnce();
  3526. releaseOldWrite();
  3527. await expect(oldWrite).rejects.toThrow('cancelled');
  3528. await expect(newWrite).resolves.toEqual(
  3529. expect.objectContaining({ configOptions: expect.any(Array) }),
  3530. );
  3531. });
  3532. expect(applied).toEqual(['bypassPermissions', 'default']);
  3533. });
  3534. it('broadcasts a committed permission write even when its initiating Session closes', async () => {
  3535. const { runtime, createSession, getPermissionMode, setPermissionMode } = createRuntime();
  3536. let nextSession = 1;
  3537. createSession.mockImplementation(async ({ workspaceDir }: { workspaceDir: string }) => ({
  3538. sessionId: `session-${nextSession++}`,
  3539. workspaceDir,
  3540. }));
  3541. let currentMode: 'default' | 'auto' | 'bypassPermissions' = 'default';
  3542. let releaseWrite!: () => void;
  3543. setPermissionMode.mockImplementation(
  3544. (mode) =>
  3545. new Promise((resolve) => {
  3546. releaseWrite = () => {
  3547. currentMode = mode === 'off' ? 'default' : mode;
  3548. resolve(mode);
  3549. };
  3550. }),
  3551. );
  3552. getPermissionMode.mockImplementation(async () => currentMode);
  3553. const updates: acp.SessionNotification[] = [];
  3554. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  3555. const client = acp
  3556. .client({ name: 'test-client' })
  3557. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
  3558. await client.connectWith(agent, async (connection) => {
  3559. await connection.request(acp.methods.agent.initialize, {
  3560. protocolVersion: acp.PROTOCOL_VERSION,
  3561. clientCapabilities: {},
  3562. });
  3563. const first = await connection.request(acp.methods.agent.session.new, {
  3564. cwd: '/workspace/first',
  3565. mcpServers: [],
  3566. });
  3567. const second = await connection.request(acp.methods.agent.session.new, {
  3568. cwd: '/workspace/second',
  3569. mcpServers: [],
  3570. });
  3571. const write = connection.request(acp.methods.agent.session.setConfigOption, {
  3572. sessionId: first.sessionId,
  3573. configId: 'permissionMode',
  3574. value: 'bypassPermissions',
  3575. });
  3576. void write.catch(() => undefined);
  3577. await vi.waitFor(() => expect(setPermissionMode).toHaveBeenCalledOnce());
  3578. await connection.request(acp.methods.agent.session.close, { sessionId: first.sessionId });
  3579. releaseWrite();
  3580. await expect(write).rejects.toThrow('cancelled');
  3581. await vi.waitFor(() =>
  3582. expect(updates).toContainEqual({
  3583. sessionId: second.sessionId,
  3584. update: {
  3585. sessionUpdate: 'config_option_update',
  3586. configOptions: expect.arrayContaining([
  3587. expect.objectContaining({
  3588. id: 'permissionMode',
  3589. currentValue: 'bypassPermissions',
  3590. }),
  3591. ]),
  3592. },
  3593. }),
  3594. );
  3595. });
  3596. });
  3597. it('omits unknown permission state and rejects unadvertised model configuration values', async () => {
  3598. const { runtime, getPermissionMode, getSession, selectSessionModel } = createRuntime([], {
  3599. models: [
  3600. {
  3601. providerId: 'minimax',
  3602. modelId: 'm3',
  3603. selected: true,
  3604. effortOptions: ['low', 'high'],
  3605. },
  3606. ],
  3607. });
  3608. getPermissionMode.mockRejectedValue(new Error('permission config unavailable'));
  3609. getSession.mockResolvedValue({
  3610. sessionId: 'session-1',
  3611. workspaceDir: '/workspace',
  3612. model: { providerId: 'minimax', modelId: 'm3', thinking: { effort: 'low' } },
  3613. });
  3614. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  3615. const client = acp.client({ name: 'test-client' });
  3616. await client.connectWith(agent, async (connection) => {
  3617. await connection.request(acp.methods.agent.initialize, {
  3618. protocolVersion: acp.PROTOCOL_VERSION,
  3619. clientCapabilities: {},
  3620. });
  3621. const session = await connection.request(acp.methods.agent.session.new, {
  3622. cwd: '/workspace',
  3623. mcpServers: [],
  3624. });
  3625. expect(session.configOptions).not.toEqual(
  3626. expect.arrayContaining([expect.objectContaining({ id: 'permissionMode' })]),
  3627. );
  3628. await expect(
  3629. connection.request(acp.methods.agent.session.setConfigOption, {
  3630. sessionId: session.sessionId,
  3631. configId: 'model',
  3632. value: 'm:minimax:unknown:u',
  3633. }),
  3634. ).rejects.toThrow('Model selection is not advertised');
  3635. await expect(
  3636. connection.request(acp.methods.agent.session.setConfigOption, {
  3637. sessionId: session.sessionId,
  3638. configId: 'thinkingEffort',
  3639. value: 'ultra',
  3640. }),
  3641. ).rejects.toThrow('Thinking effort is not advertised');
  3642. });
  3643. expect(selectSessionModel).not.toHaveBeenCalled();
  3644. });
  3645. it('round-trips an explicitly empty advertised model variant', async () => {
  3646. const { runtime, selectSessionModel } = createRuntime([], {
  3647. models: [
  3648. {
  3649. providerId: 'minimax',
  3650. modelId: 'm3',
  3651. selected: true,
  3652. variant: '',
  3653. supportedVariants: ['', 'thinking'],
  3654. },
  3655. ],
  3656. });
  3657. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  3658. const client = acp.client({ name: 'test-client' });
  3659. await client.connectWith(agent, async (connection) => {
  3660. await connection.request(acp.methods.agent.initialize, {
  3661. protocolVersion: acp.PROTOCOL_VERSION,
  3662. clientCapabilities: {},
  3663. });
  3664. const session = await connection.request(acp.methods.agent.session.new, {
  3665. cwd: '/workspace',
  3666. mcpServers: [],
  3667. });
  3668. expect(session.configOptions).toEqual(
  3669. expect.arrayContaining([
  3670. expect.objectContaining({
  3671. id: 'model',
  3672. currentValue: 'm:minimax:m3:v:',
  3673. options: expect.arrayContaining([
  3674. expect.objectContaining({ value: 'm:minimax:m3:v:' }),
  3675. expect.objectContaining({ value: 'm:minimax:m3:v:thinking' }),
  3676. ]),
  3677. }),
  3678. ]),
  3679. );
  3680. await expect(
  3681. connection.request(acp.methods.agent.session.setConfigOption, {
  3682. sessionId: session.sessionId,
  3683. configId: 'model',
  3684. value: 'm:minimax:m3:v:',
  3685. }),
  3686. ).resolves.toEqual(expect.objectContaining({ configOptions: expect.any(Array) }));
  3687. });
  3688. expect(selectSessionModel).toHaveBeenCalledWith(
  3689. { providerId: 'minimax', modelId: 'm3', variant: '' },
  3690. 'session-1',
  3691. );
  3692. });
  3693. it('advertises an empty selected variant when supportedVariants is omitted', async () => {
  3694. const { runtime, selectSessionModel } = createRuntime([], {
  3695. models: [
  3696. {
  3697. providerId: 'minimax',
  3698. modelId: 'm3',
  3699. selected: true,
  3700. variant: '',
  3701. effortOptions: ['low'],
  3702. thinkingConfig: { defaultValue: 'low' },
  3703. },
  3704. ],
  3705. });
  3706. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  3707. const client = acp.client({ name: 'test-client' });
  3708. await client.connectWith(agent, async (connection) => {
  3709. await connection.request(acp.methods.agent.initialize, {
  3710. protocolVersion: acp.PROTOCOL_VERSION,
  3711. clientCapabilities: {},
  3712. });
  3713. const session = await connection.request(acp.methods.agent.session.new, {
  3714. cwd: '/workspace',
  3715. mcpServers: [],
  3716. });
  3717. expect(session.configOptions).toEqual(
  3718. expect.arrayContaining([
  3719. expect.objectContaining({ id: 'model', currentValue: 'm:minimax:m3:v:' }),
  3720. expect.objectContaining({ id: 'thinkingEffort', currentValue: 'low' }),
  3721. ]),
  3722. );
  3723. await connection.request(acp.methods.agent.session.setConfigOption, {
  3724. sessionId: session.sessionId,
  3725. configId: 'model',
  3726. value: 'm:minimax:m3:v:',
  3727. });
  3728. });
  3729. expect(selectSessionModel).toHaveBeenCalledWith(
  3730. { providerId: 'minimax', modelId: 'm3', variant: '' },
  3731. 'session-1',
  3732. );
  3733. });
  3734. it('forks an attached Runtime session through the standard ACP method', async () => {
  3735. const { runtime, configureSessionMcpServers, getSessionForkOptions, forkSession } =
  3736. createRuntime();
  3737. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  3738. const client = acp.client({ name: 'test-client' });
  3739. await client.connectWith(agent, async (connection) => {
  3740. await connection.request(acp.methods.agent.initialize, {
  3741. protocolVersion: acp.PROTOCOL_VERSION,
  3742. clientCapabilities: {},
  3743. });
  3744. const session = await connection.request(acp.methods.agent.session.new, {
  3745. cwd: '/workspace',
  3746. mcpServers: [
  3747. {
  3748. name: 'client-tools',
  3749. command: '/usr/local/bin/client-tools',
  3750. args: ['serve'],
  3751. env: [],
  3752. },
  3753. ],
  3754. });
  3755. await expect(
  3756. connection.request(acp.methods.agent.session.fork, {
  3757. sessionId: session.sessionId,
  3758. cwd: '/workspace',
  3759. }),
  3760. ).resolves.toMatchObject({
  3761. sessionId: 'session-fork',
  3762. modes: { currentModeId: 'default' },
  3763. });
  3764. });
  3765. expect(getSessionForkOptions).toHaveBeenCalledWith('session-1');
  3766. expect(configureSessionMcpServers).toHaveBeenCalledWith('session-fork', [
  3767. {
  3768. name: 'client-tools',
  3769. type: 'stdio',
  3770. command: '/usr/local/bin/client-tools',
  3771. args: ['serve'],
  3772. },
  3773. ]);
  3774. expect(forkSession).toHaveBeenCalledWith(
  3775. expect.objectContaining({
  3776. sessionId: 'session-1',
  3777. useSuggestedTitle: true,
  3778. createIsolatedWorktree: false,
  3779. }),
  3780. );
  3781. });
  3782. it('bounds concurrent durable fork operations', async () => {
  3783. const { runtime, forkSession } = createRuntime();
  3784. forkSession.mockImplementation(() => new Promise(() => undefined));
  3785. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  3786. const client = acp.client({ name: 'test-client' });
  3787. await client.connectWith(agent, async (connection) => {
  3788. await connection.request(acp.methods.agent.initialize, {
  3789. protocolVersion: acp.PROTOCOL_VERSION,
  3790. clientCapabilities: {},
  3791. });
  3792. const session = await connection.request(acp.methods.agent.session.new, {
  3793. cwd: '/workspace',
  3794. mcpServers: [],
  3795. });
  3796. const cancellations = Array.from({ length: 8 }, () => new AbortController());
  3797. const admitted = cancellations.map((cancellation) =>
  3798. connection.request(
  3799. acp.methods.agent.session.fork,
  3800. {
  3801. sessionId: session.sessionId,
  3802. cwd: '/workspace',
  3803. mcpServers: [],
  3804. },
  3805. { cancellationSignal: cancellation.signal },
  3806. ),
  3807. );
  3808. for (const request of admitted) void request.catch(() => undefined);
  3809. await vi.waitFor(() => expect(forkSession).toHaveBeenCalledTimes(8));
  3810. for (const cancellation of cancellations) cancellation.abort();
  3811. await Promise.all(admitted.map((request) => expect(request).rejects.toThrow('cancel')));
  3812. await expect(
  3813. connection.request(acp.methods.agent.session.fork, {
  3814. sessionId: session.sessionId,
  3815. cwd: '/workspace',
  3816. mcpServers: [],
  3817. }),
  3818. ).rejects.toThrow('Too many ACP Session fork operations');
  3819. });
  3820. });
  3821. it('deletes a durable fork when its ACP request is cancelled', async () => {
  3822. const { runtime, deleteSession, forkSession } = createRuntime();
  3823. let releaseFork!: () => void;
  3824. forkSession.mockImplementation(
  3825. () =>
  3826. new Promise((resolve) => {
  3827. releaseFork = () =>
  3828. resolve({ session: { sessionId: 'session-fork', workspaceDir: '/workspace' } });
  3829. }),
  3830. );
  3831. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  3832. const client = acp.client({ name: 'test-client' });
  3833. await client.connectWith(agent, async (connection) => {
  3834. await connection.request(acp.methods.agent.initialize, {
  3835. protocolVersion: acp.PROTOCOL_VERSION,
  3836. clientCapabilities: {},
  3837. });
  3838. const session = await connection.request(acp.methods.agent.session.new, {
  3839. cwd: '/workspace',
  3840. mcpServers: [],
  3841. });
  3842. const cancellation = new AbortController();
  3843. const fork = connection.request(
  3844. acp.methods.agent.session.fork,
  3845. { sessionId: session.sessionId, cwd: '/workspace', mcpServers: [] },
  3846. { cancellationSignal: cancellation.signal },
  3847. );
  3848. await vi.waitFor(() => expect(forkSession).toHaveBeenCalledOnce());
  3849. cancellation.abort();
  3850. releaseFork();
  3851. await expect(fork).rejects.toThrow('cancelled');
  3852. });
  3853. expect(deleteSession).toHaveBeenCalledWith('session-fork');
  3854. });
  3855. it('treats an explicit empty MCP list as a complete fork overlay replacement', async () => {
  3856. const { runtime, configureSessionMcpServers } = createRuntime();
  3857. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  3858. const client = acp.client({ name: 'test-client' });
  3859. await client.connectWith(agent, async (connection) => {
  3860. await connection.request(acp.methods.agent.initialize, {
  3861. protocolVersion: acp.PROTOCOL_VERSION,
  3862. clientCapabilities: {},
  3863. });
  3864. const session = await connection.request(acp.methods.agent.session.new, {
  3865. cwd: '/workspace',
  3866. mcpServers: [
  3867. {
  3868. name: 'client-tools',
  3869. command: '/usr/local/bin/client-tools',
  3870. args: ['serve'],
  3871. env: [],
  3872. },
  3873. ],
  3874. });
  3875. await expect(
  3876. connection.request(acp.methods.agent.session.fork, {
  3877. sessionId: session.sessionId,
  3878. cwd: '/workspace',
  3879. mcpServers: [],
  3880. }),
  3881. ).resolves.toMatchObject({ sessionId: 'session-fork' });
  3882. });
  3883. expect(configureSessionMcpServers).not.toHaveBeenCalled();
  3884. });
  3885. it('deletes a durable fork without waiting for MCP clear after configuration fails', async () => {
  3886. const { runtime, configureSessionMcpServers, clearSessionMcpServers, deleteSession } =
  3887. createRuntime();
  3888. configureSessionMcpServers.mockRejectedValue(new Error('MCP startup failed'));
  3889. clearSessionMcpServers.mockImplementation(() => new Promise(() => undefined));
  3890. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  3891. const client = acp.client({ name: 'test-client' });
  3892. await client.connectWith(agent, async (connection) => {
  3893. await connection.request(acp.methods.agent.initialize, {
  3894. protocolVersion: acp.PROTOCOL_VERSION,
  3895. clientCapabilities: {},
  3896. });
  3897. const session = await connection.request(acp.methods.agent.session.new, {
  3898. cwd: '/workspace',
  3899. mcpServers: [
  3900. {
  3901. name: 'client-tools',
  3902. command: '/usr/local/bin/client-tools',
  3903. args: ['serve'],
  3904. env: [],
  3905. },
  3906. ],
  3907. });
  3908. await expect(
  3909. connection.request(acp.methods.agent.session.fork, {
  3910. sessionId: session.sessionId,
  3911. cwd: '/workspace',
  3912. }),
  3913. ).rejects.toThrow('Internal error');
  3914. await expect(
  3915. connection.request(acp.methods.agent.session.close, { sessionId: 'session-fork' }),
  3916. ).rejects.toThrow();
  3917. });
  3918. expect(clearSessionMcpServers).not.toHaveBeenCalled();
  3919. expect(deleteSession).toHaveBeenCalledWith('session-fork');
  3920. });
  3921. it('exposes steer, queue, Goal, and delegation control through ACP extensions', async () => {
  3922. const {
  3923. runtime,
  3924. sendMessage,
  3925. abortSession,
  3926. steer,
  3927. listQueuedMessages,
  3928. enqueueMessage,
  3929. updateQueuedMessageContent,
  3930. deleteQueuedMessage,
  3931. steerQueuedMessage,
  3932. getGoal,
  3933. createGoal,
  3934. patchGoal,
  3935. clearGoal,
  3936. getDelegationSnapshot,
  3937. stopDelegation,
  3938. } = createRuntime(
  3939. [
  3940. {
  3941. type: 'delta',
  3942. messageId: 'message-active',
  3943. role: 'assistant',
  3944. content: 'Working',
  3945. turnId: 'turn-active',
  3946. },
  3947. ],
  3948. { holdRunAfterEvents: true },
  3949. );
  3950. updateQueuedMessageContent.mockResolvedValueOnce({
  3951. itemId: 'queue-1',
  3952. sessionId: 'session-1',
  3953. content: 'Run focused checks',
  3954. status: 'queued',
  3955. });
  3956. deleteQueuedMessage.mockResolvedValueOnce({
  3957. itemId: 'queue-1',
  3958. sessionId: 'session-1',
  3959. content: 'Run focused checks',
  3960. status: 'deleted',
  3961. });
  3962. const agent = createTuiAcpAgent({
  3963. runtime,
  3964. version: '1.2.3',
  3965. createTurnId: () => 'turn-active',
  3966. });
  3967. const activeUpdates: acp.SessionNotification[] = [];
  3968. const currentSessionUpdates: unknown[] = [];
  3969. const client = acp
  3970. .client({ name: 'test-client' })
  3971. .onNotification(acp.methods.client.session.update, ({ params }) => activeUpdates.push(params))
  3972. .onNotification(
  3973. 'mcode/session/current_session_update',
  3974. (value) => value as { sessionId: string | null },
  3975. ({ params }) => currentSessionUpdates.push(params),
  3976. );
  3977. await client.connectWith(agent, async (connection) => {
  3978. await connection.request(acp.methods.agent.initialize, {
  3979. protocolVersion: acp.PROTOCOL_VERSION,
  3980. clientCapabilities: {
  3981. _meta: { 'minimax-code/extensions': { version: 1, notifications: true } },
  3982. },
  3983. });
  3984. const session = await connection.request(acp.methods.agent.session.new, {
  3985. cwd: '/workspace',
  3986. mcpServers: [],
  3987. });
  3988. await expect(
  3989. connection.request<{ sessionId: string }, { sessionId: string }>('session/activate', {
  3990. sessionId: session.sessionId,
  3991. }),
  3992. ).resolves.toEqual({ sessionId: 'session-1' });
  3993. await expect(
  3994. connection.request<{ sessionId: string }, { sessionId: string }>('mcode/session/activate', {
  3995. sessionId: session.sessionId,
  3996. }),
  3997. ).resolves.toEqual({ sessionId: 'session-1' });
  3998. await expect(
  3999. connection.request<
  4000. { itemId: string; position: number },
  4001. { sessionId: string; text: string }
  4002. >('mcode/session/queue/enqueue', {
  4003. sessionId: session.sessionId,
  4004. text: '\n Run checks next \n',
  4005. }),
  4006. ).resolves.toEqual({ itemId: 'queue-1', position: 1 });
  4007. await expect(
  4008. connection.request<{ items: unknown[] }, { sessionId: string }>(
  4009. 'mcode/session/queue/list',
  4010. { sessionId: session.sessionId },
  4011. ),
  4012. ).resolves.toEqual({ items: [] });
  4013. await expect(
  4014. connection.request<
  4015. { item: { content: string } },
  4016. { sessionId: string; itemId: string; text: string }
  4017. >('mcode/session/queue/update', {
  4018. sessionId: session.sessionId,
  4019. itemId: 'queue-1',
  4020. text: '\n Run focused checks \n',
  4021. }),
  4022. ).resolves.toMatchObject({ item: { content: 'Run focused checks' } });
  4023. await expect(
  4024. connection.request<{ item: { status: string } }, { sessionId: string; itemId: string }>(
  4025. 'mcode/session/queue/delete',
  4026. {
  4027. sessionId: session.sessionId,
  4028. itemId: 'queue-1',
  4029. },
  4030. ),
  4031. ).resolves.toMatchObject({ item: { status: 'deleted' } });
  4032. await expect(
  4033. connection.request<
  4034. { queueItemId: string; turnId: string },
  4035. { sessionId: string; itemId: string }
  4036. >('mcode/session/queue/steer', {
  4037. sessionId: session.sessionId,
  4038. itemId: 'queue-1',
  4039. }),
  4040. ).resolves.toEqual({ queueItemId: 'queue-1', turnId: 'turn-2' });
  4041. await expect(
  4042. connection.request<{ goal: unknown | null }, { sessionId: string }>(
  4043. 'mcode/session/goal/get',
  4044. {
  4045. sessionId: session.sessionId,
  4046. },
  4047. ),
  4048. ).resolves.toEqual({ goal: null });
  4049. await expect(
  4050. connection.request<
  4051. { goal: { goalId: string; objective: string } },
  4052. { sessionId: string; objective: string; tokenBudget: number }
  4053. >('mcode/session/goal/create', {
  4054. sessionId: session.sessionId,
  4055. objective: 'Ship ACP',
  4056. tokenBudget: 8_000,
  4057. }),
  4058. ).resolves.toMatchObject({ goal: { goalId: 'goal-1', objective: 'Ship ACP' } });
  4059. await expect(
  4060. connection.request<{ goal: { status: string } }, { sessionId: string; status: string }>(
  4061. 'mcode/session/goal/patch',
  4062. {
  4063. sessionId: session.sessionId,
  4064. status: 'paused',
  4065. },
  4066. ),
  4067. ).resolves.toMatchObject({ goal: { status: 'paused' } });
  4068. await expect(
  4069. connection.request<{ cleared: boolean }, { sessionId: string }>(
  4070. 'mcode/session/goal/clear',
  4071. { sessionId: session.sessionId },
  4072. ),
  4073. ).resolves.toEqual({ cleared: true });
  4074. await expect(
  4075. connection.request<{ snapshot: { rootSessionId: string } }, { sessionId: string }>(
  4076. 'mcode/session/delegation/get',
  4077. { sessionId: session.sessionId },
  4078. ),
  4079. ).resolves.toMatchObject({ snapshot: { rootSessionId: 'session-1' } });
  4080. await expect(
  4081. connection.request<{ receipt: { rootStopped: boolean } }, { sessionId: string }>(
  4082. 'mcode/session/delegation/stop',
  4083. { sessionId: session.sessionId },
  4084. ),
  4085. ).resolves.toMatchObject({ receipt: { rootStopped: true } });
  4086. const prompt = connection.request(acp.methods.agent.session.prompt, {
  4087. sessionId: session.sessionId,
  4088. prompt: [{ type: 'text', text: 'Start working' }],
  4089. });
  4090. await vi.waitFor(() => expect(sendMessage).toHaveBeenCalledOnce());
  4091. await vi.waitFor(() =>
  4092. expect(activeUpdates).toEqual(
  4093. expect.arrayContaining([
  4094. expect.objectContaining({
  4095. update: expect.objectContaining({ sessionUpdate: 'agent_message_chunk' }),
  4096. }),
  4097. ]),
  4098. ),
  4099. );
  4100. await expect(
  4101. connection.request<
  4102. { turnId: string; mode: string },
  4103. { sessionId: string; text: string; clientRequestId: string }
  4104. >('mcode/session/steer', {
  4105. sessionId: session.sessionId,
  4106. text: '\n Prioritize protocol tests \n',
  4107. clientRequestId: 'client-steer-1',
  4108. }),
  4109. ).resolves.toEqual({ turnId: 'turn-active', mode: 'steered' });
  4110. await connection.notify(acp.methods.agent.session.cancel, { sessionId: session.sessionId });
  4111. await expect(prompt).resolves.toEqual({ stopReason: 'cancelled' });
  4112. await expect(
  4113. connection.request(acp.methods.agent.session.close, { sessionId: session.sessionId }),
  4114. ).resolves.toEqual({});
  4115. });
  4116. expect(enqueueMessage).toHaveBeenCalledWith('session-1', '\n Run checks next \n');
  4117. expect(listQueuedMessages).toHaveBeenCalledWith('session-1');
  4118. expect(updateQueuedMessageContent).toHaveBeenCalledWith(
  4119. 'session-1',
  4120. 'queue-1',
  4121. '\n Run focused checks \n',
  4122. );
  4123. expect(deleteQueuedMessage).toHaveBeenCalledWith('session-1', 'queue-1');
  4124. expect(steerQueuedMessage).toHaveBeenCalledWith('session-1', 'queue-1');
  4125. expect(getGoal).toHaveBeenCalledWith('session-1');
  4126. expect(createGoal).toHaveBeenCalledWith({
  4127. sessionId: 'session-1',
  4128. objective: 'Ship ACP',
  4129. tokenBudget: 8_000,
  4130. });
  4131. expect(patchGoal).toHaveBeenCalledWith('session-1', { status: 'paused' });
  4132. expect(clearGoal).toHaveBeenCalledWith('session-1');
  4133. expect(getDelegationSnapshot).toHaveBeenCalledWith('session-1');
  4134. expect(stopDelegation).toHaveBeenCalledWith('session-1');
  4135. expect(currentSessionUpdates).toEqual([
  4136. { sessionId: 'session-1' },
  4137. { sessionId: 'session-1' },
  4138. { sessionId: null },
  4139. ]);
  4140. expect(steer).toHaveBeenCalledWith(
  4141. expect.objectContaining({
  4142. sessionId: 'session-1',
  4143. source: 'api',
  4144. message: { content: '\n Prioritize protocol tests \n' },
  4145. producerId: 'mcode-acp',
  4146. idempotencyKey: 'client-steer-1',
  4147. preDelivery: { accept: expect.any(Function) },
  4148. }),
  4149. );
  4150. expect(abortSession).toHaveBeenCalled();
  4151. });
  4152. it('rejects ACP steering before the Runtime admits the prompt Turn', async () => {
  4153. const { runtime, sendMessage, steer } = createRuntime([], { holdRunUntilAbort: true });
  4154. const agent = createTuiAcpAgent({
  4155. runtime,
  4156. version: '1.2.3',
  4157. createTurnId: () => 'turn-pending',
  4158. });
  4159. const client = acp.client({ name: 'test-client' });
  4160. await client.connectWith(agent, async (connection) => {
  4161. await connection.request(acp.methods.agent.initialize, {
  4162. protocolVersion: acp.PROTOCOL_VERSION,
  4163. clientCapabilities: {},
  4164. });
  4165. const session = await connection.request(acp.methods.agent.session.new, {
  4166. cwd: '/workspace',
  4167. mcpServers: [],
  4168. });
  4169. const prompt = connection.request(acp.methods.agent.session.prompt, {
  4170. sessionId: session.sessionId,
  4171. prompt: [{ type: 'text', text: 'Wait for admission' }],
  4172. });
  4173. await vi.waitFor(() => expect(sendMessage).toHaveBeenCalledOnce());
  4174. await expect(
  4175. connection.request('mcode/session/steer', {
  4176. sessionId: session.sessionId,
  4177. text: 'Must not become a new Turn',
  4178. }),
  4179. ).rejects.toThrow('admitted, active ACP prompt Turn');
  4180. expect(steer).not.toHaveBeenCalled();
  4181. await connection.notify(acp.methods.agent.session.cancel, { sessionId: session.sessionId });
  4182. await expect(prompt).resolves.toEqual({ stopReason: 'cancelled' });
  4183. });
  4184. });
  4185. it('rejects ACP steering when Runtime admission activates or targets another Turn', async () => {
  4186. const { runtime, sendMessage, steer } = createRuntime(
  4187. [
  4188. {
  4189. type: 'delta',
  4190. messageId: 'message-admitted',
  4191. role: 'assistant',
  4192. content: 'Working',
  4193. turnId: 'turn-admitted',
  4194. },
  4195. ],
  4196. { holdRunAfterEvents: true },
  4197. );
  4198. const agent = createTuiAcpAgent({
  4199. runtime,
  4200. version: '1.2.3',
  4201. createTurnId: () => 'turn-admitted',
  4202. });
  4203. const updates: acp.SessionNotification[] = [];
  4204. const client = acp
  4205. .client({ name: 'test-client' })
  4206. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
  4207. await client.connectWith(agent, async (connection) => {
  4208. await connection.request(acp.methods.agent.initialize, {
  4209. protocolVersion: acp.PROTOCOL_VERSION,
  4210. clientCapabilities: {},
  4211. });
  4212. const session = await connection.request(acp.methods.agent.session.new, {
  4213. cwd: '/workspace',
  4214. mcpServers: [],
  4215. });
  4216. const prompt = connection.request(acp.methods.agent.session.prompt, {
  4217. sessionId: session.sessionId,
  4218. prompt: [{ type: 'text', text: 'Start admitted work' }],
  4219. });
  4220. await vi.waitFor(() => expect(sendMessage).toHaveBeenCalledOnce());
  4221. await vi.waitFor(() =>
  4222. expect(updates).toEqual(
  4223. expect.arrayContaining([
  4224. expect.objectContaining({
  4225. update: expect.objectContaining({ sessionUpdate: 'agent_message_chunk' }),
  4226. }),
  4227. ]),
  4228. ),
  4229. );
  4230. steer.mockImplementationOnce(async (input) => {
  4231. await input.preDelivery?.accept({ mode: 'activated', turnId: 'turn-new' });
  4232. return { turnId: 'turn-new', mode: 'steered' };
  4233. });
  4234. await expect(
  4235. connection.request('mcode/session/steer', {
  4236. sessionId: session.sessionId,
  4237. text: 'Do not activate',
  4238. }),
  4239. ).rejects.toThrow('active ACP prompt Turn changed');
  4240. steer.mockImplementationOnce(async (input) => {
  4241. await input.preDelivery?.accept({ mode: 'steered', turnId: 'turn-other' });
  4242. return { turnId: 'turn-other', mode: 'steered' };
  4243. });
  4244. await expect(
  4245. connection.request('mcode/session/steer', {
  4246. sessionId: session.sessionId,
  4247. text: 'Do not steer another Turn',
  4248. }),
  4249. ).rejects.toThrow('active ACP prompt Turn changed');
  4250. await connection.notify(acp.methods.agent.session.cancel, { sessionId: session.sessionId });
  4251. await expect(prompt).resolves.toEqual({ stopReason: 'cancelled' });
  4252. });
  4253. });
  4254. it('omits and rejects Goal extensions when the Runtime feature gate is disabled', async () => {
  4255. const { runtime, emitRuntimeEvent, createGoal, getGoal, patchGoal, clearGoal } = createRuntime(
  4256. [],
  4257. { goalEnabled: false },
  4258. );
  4259. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  4260. const goalUpdates: unknown[] = [];
  4261. const client = acp.client({ name: 'test-client' }).onNotification(
  4262. 'mcode/session/goal_update',
  4263. (value) => value as { sessionId: string; goal: unknown },
  4264. ({ params }) => goalUpdates.push(params),
  4265. );
  4266. await client.connectWith(agent, async (connection) => {
  4267. const initialized = await connection.request(acp.methods.agent.initialize, {
  4268. protocolVersion: acp.PROTOCOL_VERSION,
  4269. clientCapabilities: {
  4270. _meta: { 'minimax-code/extensions': { version: 1, notifications: true } },
  4271. },
  4272. });
  4273. const extensions = initialized._meta?.['minimax-code/extensions'] as {
  4274. methods: string[];
  4275. notifications: string[];
  4276. };
  4277. expect(extensions.methods).not.toEqual(
  4278. expect.arrayContaining([
  4279. 'mcode/session/goal/get',
  4280. 'mcode/session/goal/create',
  4281. 'mcode/session/goal/patch',
  4282. 'mcode/session/goal/clear',
  4283. ]),
  4284. );
  4285. expect(extensions.notifications).not.toContain('mcode/session/goal_update');
  4286. const session = await connection.request(acp.methods.agent.session.new, {
  4287. cwd: '/workspace',
  4288. mcpServers: [],
  4289. });
  4290. await expect(
  4291. connection.request('mcode/session/goal/create', {
  4292. sessionId: session.sessionId,
  4293. objective: 'Should not persist',
  4294. }),
  4295. ).rejects.toThrow('Goal extensions are disabled');
  4296. const goalGateChecks = vi.mocked(runtime.isGoalEnabled).mock.calls.length;
  4297. emitRuntimeEvent({
  4298. type: 'thread_goal.updated',
  4299. timestampMs: 1,
  4300. source: 'runtime',
  4301. sessionId: 'session-1',
  4302. goal: {
  4303. goalId: 'goal-1',
  4304. sessionId: 'session-1',
  4305. objective: 'Must stay hidden',
  4306. status: 'active',
  4307. createdAt: 1,
  4308. updatedAt: 1,
  4309. tokensUsed: 0,
  4310. timeUsedSeconds: 0,
  4311. tokenBudget: null,
  4312. hasKickoffAttachments: false,
  4313. },
  4314. });
  4315. emitRuntimeEvent({
  4316. type: 'thread_goal.cleared',
  4317. timestampMs: 2,
  4318. source: 'runtime',
  4319. sessionId: 'session-1',
  4320. goalId: 'goal-1',
  4321. });
  4322. await vi.waitFor(() =>
  4323. expect(runtime.isGoalEnabled).toHaveBeenCalledTimes(goalGateChecks + 2),
  4324. );
  4325. expect(goalUpdates).toEqual([]);
  4326. });
  4327. expect(getGoal).not.toHaveBeenCalled();
  4328. expect(createGoal).not.toHaveBeenCalled();
  4329. expect(patchGoal).not.toHaveBeenCalled();
  4330. expect(clearGoal).not.toHaveBeenCalled();
  4331. });
  4332. it('projects session info, usage, plans, and opted-in extension notifications', async () => {
  4333. const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined);
  4334. const { runtime, emitRuntimeEvent, listQueuedMessages } = createRuntime([], {
  4335. contextSnapshot: {
  4336. status: 'live',
  4337. model: { provider: 'minimax', id: 'm3', contextWindow: 10_000 },
  4338. contextUsage: {
  4339. contextWindowTokens: 10_000,
  4340. usedTokens: 4_000,
  4341. totalCountSource: 'LOCAL_ESTIMATE',
  4342. components: [],
  4343. },
  4344. compaction: { state: 'never' },
  4345. },
  4346. sessionUsage: { summary: { costUsd: 0.25 } },
  4347. });
  4348. listQueuedMessages.mockResolvedValueOnce([
  4349. {
  4350. itemId: 'queue-1',
  4351. sessionId: 'session-1',
  4352. content: 'Run checks',
  4353. status: 'queued',
  4354. createdAt: 1,
  4355. },
  4356. ]);
  4357. const updates: acp.SessionNotification[] = [];
  4358. const queueUpdates: unknown[] = [];
  4359. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  4360. const client = acp
  4361. .client({ name: 'test-client' })
  4362. .onNotification(acp.methods.client.session.update, ({ params }) => {
  4363. if (params.update.sessionUpdate === 'plan_removed') {
  4364. throw new Error('client disconnected while removing plan');
  4365. }
  4366. updates.push(params);
  4367. })
  4368. .onNotification(
  4369. 'mcode/session/queue_update',
  4370. (value) => value as { sessionId: string; items: unknown[] },
  4371. ({ params }) => queueUpdates.push(params),
  4372. )
  4373. .onRequest(acp.methods.client.elicitation.create, () => ({ action: 'cancel' }));
  4374. await client.connectWith(agent, async (connection) => {
  4375. await connection.request(acp.methods.agent.initialize, {
  4376. protocolVersion: acp.PROTOCOL_VERSION,
  4377. clientCapabilities: {
  4378. plan: {},
  4379. elicitation: { form: {} },
  4380. _meta: {
  4381. 'minimax-code/extensions': { version: 1, notifications: true },
  4382. },
  4383. },
  4384. });
  4385. await connection.request(acp.methods.agent.session.new, {
  4386. cwd: '/workspace',
  4387. mcpServers: [],
  4388. });
  4389. emitRuntimeEvent({
  4390. type: 'session.title_updated',
  4391. timestampMs: 1_725_000_000_000,
  4392. source: 'runtime',
  4393. sessionId: 'session-1',
  4394. title: 'ACP control plane',
  4395. });
  4396. emitRuntimeEvent({
  4397. type: 'session.finish',
  4398. timestampMs: 1_725_000_000_001,
  4399. source: 'runtime',
  4400. sessionId: 'session-1',
  4401. queueItemIds: [],
  4402. });
  4403. emitRuntimeEvent({
  4404. type: 'session.queue.updated',
  4405. timestampMs: 1_725_000_000_002,
  4406. source: 'runtime',
  4407. sessionId: 'session-1',
  4408. queuedCount: 1,
  4409. });
  4410. emitRuntimeEvent({
  4411. type: 'questionnaire.ask',
  4412. timestampMs: 1_725_000_000_003,
  4413. source: 'runtime',
  4414. sessionId: 'session-1',
  4415. request: {
  4416. schemaVersion: 1,
  4417. id: 'plan-review-1',
  4418. title: 'Review the plan',
  4419. requester: { sessionId: 'session-1', agentName: 'mcode' },
  4420. presentation: {
  4421. replaceComposer: false,
  4422. showProgress: false,
  4423. allowBackNavigation: false,
  4424. },
  4425. steps: [],
  4426. mode: 'plan',
  4427. modePayload: {
  4428. planReview: { markdown: '# Plan\n\n1. Add ACP controls', path: '/plan.md' },
  4429. },
  4430. },
  4431. });
  4432. await vi.waitFor(() => {
  4433. expect(queueUpdates).toHaveLength(1);
  4434. expect(updates).toContainEqual({
  4435. sessionId: 'session-1',
  4436. update: expect.objectContaining({
  4437. sessionUpdate: 'usage_update',
  4438. used: 4_000,
  4439. size: 10_000,
  4440. }),
  4441. });
  4442. expect(updates).toContainEqual({
  4443. sessionId: 'session-1',
  4444. update: expect.objectContaining({ sessionUpdate: 'plan_update' }),
  4445. });
  4446. });
  4447. });
  4448. expect(updates).toContainEqual({
  4449. sessionId: 'session-1',
  4450. update: {
  4451. sessionUpdate: 'session_info_update',
  4452. title: 'ACP control plane',
  4453. updatedAt: '2024-08-30T06:40:00.000Z',
  4454. },
  4455. });
  4456. expect(updates).toContainEqual({
  4457. sessionId: 'session-1',
  4458. update: {
  4459. sessionUpdate: 'plan_update',
  4460. plan: {
  4461. type: 'markdown',
  4462. planId: 'plan-review-1',
  4463. content: '# Plan\n\n1. Add ACP controls',
  4464. },
  4465. },
  4466. });
  4467. expect(queueUpdates).toEqual([
  4468. {
  4469. sessionId: 'session-1',
  4470. items: [
  4471. {
  4472. itemId: 'queue-1',
  4473. sessionId: 'session-1',
  4474. content: 'Run checks',
  4475. status: 'queued',
  4476. createdAt: 1,
  4477. },
  4478. ],
  4479. },
  4480. ]);
  4481. expect(consoleError).toHaveBeenCalled();
  4482. consoleError.mockRestore();
  4483. });
  4484. it('closes the connection instead of dropping required Plan removals', async () => {
  4485. const { runtime, createSession, dismissQuestionnaire, emitRuntimeEvent, getSession } =
  4486. createRuntime();
  4487. let nextSession = 0;
  4488. createSession.mockImplementation(async ({ workspaceDir }: { workspaceDir: string }) => ({
  4489. sessionId: `session-${nextSession++}`,
  4490. workspaceDir,
  4491. }));
  4492. const answerQuestionnaires: Array<(response: acp.CreateElicitationResponse) => void> = [];
  4493. let planUpdates = 0;
  4494. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  4495. const client = acp
  4496. .client({ name: 'test-client' })
  4497. .onNotification(acp.methods.client.session.update, ({ params }) => {
  4498. if (params.update.sessionUpdate === 'plan_update') planUpdates += 1;
  4499. })
  4500. .onRequest(
  4501. acp.methods.client.elicitation.create,
  4502. () =>
  4503. new Promise<acp.CreateElicitationResponse>((resolve) => {
  4504. answerQuestionnaires.push(resolve);
  4505. }),
  4506. );
  4507. await client
  4508. .connectWith(agent, async (connection) => {
  4509. await connection.request(acp.methods.agent.initialize, {
  4510. protocolVersion: acp.PROTOCOL_VERSION,
  4511. clientCapabilities: { plan: {}, elicitation: { form: {} } },
  4512. });
  4513. for (let index = 0; index < 65; index += 1) {
  4514. await connection.request(acp.methods.agent.session.new, {
  4515. cwd: `/workspace/${index}`,
  4516. mcpServers: [],
  4517. });
  4518. emitRuntimeEvent(planReviewEvent(index));
  4519. }
  4520. await vi.waitFor(() => expect(planUpdates).toBe(65));
  4521. await vi.waitFor(() => expect(getSession).toHaveBeenCalledTimes(65));
  4522. await vi.waitFor(() => expect(answerQuestionnaires).toHaveLength(8));
  4523. const priorSessionReads = getSession.mock.calls.length;
  4524. getSession.mockImplementation(() => new Promise(() => undefined));
  4525. for (let index = 0; index < 8; index += 1) {
  4526. emitRuntimeEvent({
  4527. type: 'session.start',
  4528. timestampMs: 100 + index,
  4529. source: 'runtime',
  4530. sessionId: `session-${index}`,
  4531. turnId: `turn-${index}`,
  4532. queueItemIds: [],
  4533. });
  4534. }
  4535. await vi.waitFor(() => expect(getSession).toHaveBeenCalledTimes(priorSessionReads + 8));
  4536. for (let settled = 0; settled < 64; ) {
  4537. const nextSettled = Math.min(settled + 8, 64);
  4538. await vi.waitFor(() =>
  4539. expect(answerQuestionnaires.length).toBeGreaterThanOrEqual(nextSettled),
  4540. );
  4541. for (let index = settled; index < nextSettled; index += 1) {
  4542. answerQuestionnaires[index]?.({ action: 'cancel' });
  4543. }
  4544. settled = nextSettled;
  4545. await vi.waitFor(() => expect(dismissQuestionnaire).toHaveBeenCalledTimes(settled));
  4546. }
  4547. await vi.waitFor(() => expect(answerQuestionnaires).toHaveLength(65));
  4548. answerQuestionnaires[64]?.({ action: 'cancel' });
  4549. await vi.waitFor(() => expect(connection.signal.aborted).toBe(true));
  4550. })
  4551. .catch(() => undefined);
  4552. });
  4553. it('closes the connection when a required Plan removal notification never settles', async () => {
  4554. const { runtime, emitRuntimeEvent } = createRuntime();
  4555. let releaseQuestionnaire!: (response: acp.CreateElicitationResponse) => void;
  4556. const questionnaire = new Promise<acp.CreateElicitationResponse>((resolve) => {
  4557. releaseQuestionnaire = resolve;
  4558. });
  4559. let planDelivered!: () => void;
  4560. const delivered = new Promise<void>((resolve) => {
  4561. planDelivered = resolve;
  4562. });
  4563. const agent = createTuiAcpAgent({
  4564. runtime,
  4565. version: '1.2.3',
  4566. runtimeEventProjectionTimeoutMs: 10,
  4567. });
  4568. const client = acp
  4569. .client({ name: 'test-client' })
  4570. .onNotification(acp.methods.client.session.update, ({ params }) => {
  4571. if (params.update.sessionUpdate === 'plan_update') planDelivered();
  4572. if (params.update.sessionUpdate === 'plan_removed') {
  4573. return new Promise<void>(() => undefined);
  4574. }
  4575. })
  4576. .onRequest(acp.methods.client.elicitation.create, () => questionnaire);
  4577. await client
  4578. .connectWith(agent, async (connection) => {
  4579. await connection.request(acp.methods.agent.initialize, {
  4580. protocolVersion: acp.PROTOCOL_VERSION,
  4581. clientCapabilities: { plan: {}, elicitation: { form: {} } },
  4582. });
  4583. await connection.request(acp.methods.agent.session.new, {
  4584. cwd: '/workspace',
  4585. mcpServers: [],
  4586. });
  4587. emitRuntimeEvent(planReviewEvent(1));
  4588. await delivered;
  4589. releaseQuestionnaire({ action: 'cancel' });
  4590. await vi.waitFor(() => expect(connection.signal.aborted).toBe(true));
  4591. })
  4592. .catch(() => undefined);
  4593. });
  4594. it('closes the connection when a required Plan removal expires in the pending queue', async () => {
  4595. const { runtime, createSession, emitRuntimeEvent, getSession } = createRuntime();
  4596. let nextSession = 0;
  4597. createSession.mockImplementation(async ({ workspaceDir }: { workspaceDir: string }) => ({
  4598. sessionId: `session-${nextSession++}`,
  4599. workspaceDir,
  4600. }));
  4601. let settlePlan!: (response: acp.CreateElicitationResponse) => void;
  4602. let planDelivered!: () => void;
  4603. const agent = createTuiAcpAgent({
  4604. runtime,
  4605. version: '1.2.3',
  4606. runtimeEventProjectionTimeoutMs: 10,
  4607. });
  4608. const client = acp
  4609. .client({ name: 'test-client' })
  4610. .onNotification(acp.methods.client.session.update, ({ params }) => {
  4611. if (params.update.sessionUpdate === 'plan_update') planDelivered();
  4612. })
  4613. .onRequest(
  4614. acp.methods.client.elicitation.create,
  4615. () =>
  4616. new Promise<acp.CreateElicitationResponse>((resolve) => {
  4617. settlePlan = resolve;
  4618. }),
  4619. );
  4620. const delivered = new Promise<void>((resolve) => {
  4621. planDelivered = resolve;
  4622. });
  4623. await client
  4624. .connectWith(agent, async (connection) => {
  4625. await connection.request(acp.methods.agent.initialize, {
  4626. protocolVersion: acp.PROTOCOL_VERSION,
  4627. clientCapabilities: { plan: {}, elicitation: { form: {} } },
  4628. });
  4629. for (let index = 0; index < 8; index += 1) {
  4630. await connection.request(acp.methods.agent.session.new, {
  4631. cwd: `/workspace/${index}`,
  4632. mcpServers: [],
  4633. });
  4634. }
  4635. emitRuntimeEvent(planReviewEvent(0));
  4636. await delivered;
  4637. const priorSessionReads = getSession.mock.calls.length;
  4638. getSession.mockImplementation(() => new Promise(() => undefined));
  4639. for (let index = 0; index < 8; index += 1) {
  4640. emitRuntimeEvent({
  4641. type: 'session.start',
  4642. timestampMs: 10 + index,
  4643. source: 'runtime',
  4644. sessionId: `session-${index}`,
  4645. turnId: `turn-${index}`,
  4646. queueItemIds: [],
  4647. });
  4648. }
  4649. await vi.waitFor(() =>
  4650. expect(getSession.mock.calls.length).toBeGreaterThanOrEqual(priorSessionReads + 8),
  4651. );
  4652. settlePlan({ action: 'cancel' });
  4653. await vi.waitFor(() => expect(connection.signal.aborted).toBe(true));
  4654. })
  4655. .catch(() => undefined);
  4656. });
  4657. it('closes the connection when attachment replacement cannot confirm prior Plan delivery', async () => {
  4658. const { runtime, emitRuntimeEvent } = createRuntime();
  4659. let planNotificationStarted!: () => void;
  4660. const planNotification = new Promise<void>((resolve) => {
  4661. planNotificationStarted = resolve;
  4662. });
  4663. const agent = createTuiAcpAgent({
  4664. runtime,
  4665. version: '1.2.3',
  4666. runtimeEventProjectionTimeoutMs: 10,
  4667. });
  4668. const client = acp
  4669. .client({ name: 'test-client' })
  4670. .onNotification(acp.methods.client.session.update, ({ params }) => {
  4671. if (params.update.sessionUpdate === 'plan_update') {
  4672. planNotificationStarted();
  4673. return new Promise<void>(() => undefined);
  4674. }
  4675. })
  4676. .onRequest(
  4677. acp.methods.client.elicitation.create,
  4678. () => new Promise<acp.CreateElicitationResponse>(() => undefined),
  4679. );
  4680. await client
  4681. .connectWith(agent, async (connection) => {
  4682. await connection.request(acp.methods.agent.initialize, {
  4683. protocolVersion: acp.PROTOCOL_VERSION,
  4684. clientCapabilities: { plan: {}, elicitation: { form: {} } },
  4685. });
  4686. const session = await connection.request(acp.methods.agent.session.new, {
  4687. cwd: '/workspace',
  4688. mcpServers: [],
  4689. });
  4690. emitRuntimeEvent(planReviewEvent(1));
  4691. await planNotification;
  4692. await connection.request(acp.methods.agent.session.resume, {
  4693. sessionId: session.sessionId,
  4694. cwd: '/workspace',
  4695. mcpServers: [],
  4696. });
  4697. await vi.waitFor(() => expect(connection.signal.aborted).toBe(true));
  4698. })
  4699. .catch(() => undefined);
  4700. });
  4701. it('does not let a stalled control projection block questionnaire handling', async () => {
  4702. const { runtime, emitRuntimeEvent, getSession, replyQuestionnaire } = createRuntime();
  4703. let resolveStalledProjection:
  4704. | ((session: { sessionId: string; workspaceDir: string; interactionMode: 'plan' }) => void)
  4705. | undefined;
  4706. const updates: acp.SessionNotification[] = [];
  4707. const agent = createTuiAcpAgent({
  4708. runtime,
  4709. version: '1.2.3',
  4710. runtimeEventProjectionTimeoutMs: 0,
  4711. });
  4712. const client = acp
  4713. .client({ name: 'test-client' })
  4714. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params))
  4715. .onRequest(acp.methods.client.elicitation.create, () => ({
  4716. action: 'accept',
  4717. content: { approach: 'Safe' },
  4718. }));
  4719. await client.connectWith(agent, async (connection) => {
  4720. await connection.request(acp.methods.agent.initialize, {
  4721. protocolVersion: acp.PROTOCOL_VERSION,
  4722. clientCapabilities: { elicitation: { form: {} } },
  4723. });
  4724. await connection.request(acp.methods.agent.session.new, {
  4725. cwd: '/workspace',
  4726. mcpServers: [],
  4727. });
  4728. getSession.mockImplementation(
  4729. () =>
  4730. new Promise((resolve) => {
  4731. resolveStalledProjection = resolve;
  4732. }),
  4733. );
  4734. emitRuntimeEvent({
  4735. type: 'questionnaire.ask',
  4736. timestampMs: 1,
  4737. source: 'runtime',
  4738. sessionId: 'session-1',
  4739. agentName: 'mcode',
  4740. request: {
  4741. schemaVersion: 1,
  4742. id: 'questionnaire-with-stalled-projection',
  4743. title: 'Choose settings',
  4744. requester: { sessionId: 'session-1', agentName: 'mcode' },
  4745. presentation: {
  4746. replaceComposer: false,
  4747. showProgress: false,
  4748. allowBackNavigation: false,
  4749. },
  4750. steps: [
  4751. {
  4752. id: 'approach',
  4753. question: 'Which approach?',
  4754. selectionMode: 'single',
  4755. options: [{ id: 'safe', label: 'Safe' }],
  4756. allowOther: false,
  4757. otherPlaceholder: '',
  4758. required: true,
  4759. },
  4760. ],
  4761. },
  4762. });
  4763. await vi.waitFor(() =>
  4764. expect(replyQuestionnaire).toHaveBeenCalledWith(
  4765. 'mcode',
  4766. 'questionnaire-with-stalled-projection',
  4767. [{ stepId: 'approach', selectedOptionIds: ['safe'] }],
  4768. ),
  4769. );
  4770. emitRuntimeEvent({
  4771. type: 'session.title_updated',
  4772. timestampMs: 2,
  4773. source: 'runtime',
  4774. sessionId: 'session-1',
  4775. title: 'Projection recovered',
  4776. });
  4777. await vi.waitFor(() =>
  4778. expect(updates).toContainEqual({
  4779. sessionId: 'session-1',
  4780. update: {
  4781. sessionUpdate: 'session_info_update',
  4782. title: 'Projection recovered',
  4783. updatedAt: new Date(2).toISOString(),
  4784. },
  4785. }),
  4786. );
  4787. await new Promise<void>((resolve) => setImmediate(resolve));
  4788. resolveStalledProjection?.({
  4789. sessionId: 'session-1',
  4790. workspaceDir: '/workspace',
  4791. interactionMode: 'plan',
  4792. });
  4793. await Promise.resolve();
  4794. await Promise.resolve();
  4795. expect(updates).not.toEqual(
  4796. expect.arrayContaining([
  4797. expect.objectContaining({
  4798. update: expect.objectContaining({ sessionUpdate: 'current_mode_update' }),
  4799. }),
  4800. ]),
  4801. );
  4802. });
  4803. });
  4804. it('isolates stalled projection lanes and coalesces repeated events within a lane', async () => {
  4805. const { runtime, emitRuntimeEvent, getSession, listQueuedMessages, replyQuestionnaire } =
  4806. createRuntime();
  4807. getSession.mockImplementation(() => new Promise(() => undefined));
  4808. listQueuedMessages.mockImplementation(() => new Promise(() => undefined));
  4809. const updates: acp.SessionNotification[] = [];
  4810. const agent = createTuiAcpAgent({
  4811. runtime,
  4812. version: '1.2.3',
  4813. runtimeEventProjectionTimeoutMs: 0,
  4814. });
  4815. const client = acp
  4816. .client({ name: 'test-client' })
  4817. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params))
  4818. .onRequest(acp.methods.client.elicitation.create, () => ({
  4819. action: 'accept',
  4820. content: { approach: 'Safe' },
  4821. }));
  4822. const event = (id: string): TuiRuntimeEvent => ({
  4823. type: 'questionnaire.ask',
  4824. timestampMs: 1,
  4825. source: 'runtime',
  4826. sessionId: 'session-1',
  4827. agentName: 'mcode',
  4828. request: {
  4829. schemaVersion: 1,
  4830. id,
  4831. title: 'Choose settings',
  4832. requester: { sessionId: 'session-1', agentName: 'mcode' },
  4833. presentation: {
  4834. replaceComposer: false,
  4835. showProgress: false,
  4836. allowBackNavigation: false,
  4837. },
  4838. steps: [
  4839. {
  4840. id: 'approach',
  4841. question: 'Which approach?',
  4842. selectionMode: 'single',
  4843. options: [{ id: 'safe', label: 'Safe' }],
  4844. allowOther: false,
  4845. otherPlaceholder: '',
  4846. required: true,
  4847. },
  4848. ],
  4849. },
  4850. });
  4851. await client.connectWith(agent, async (connection) => {
  4852. await connection.request(acp.methods.agent.initialize, {
  4853. protocolVersion: acp.PROTOCOL_VERSION,
  4854. clientCapabilities: {
  4855. elicitation: { form: {} },
  4856. _meta: { 'minimax-code/extensions': { version: 1, notifications: true } },
  4857. },
  4858. });
  4859. await connection.request(acp.methods.agent.session.new, {
  4860. cwd: '/workspace',
  4861. mcpServers: [],
  4862. });
  4863. emitRuntimeEvent(event('stalled-1'));
  4864. emitRuntimeEvent(event('stalled-2'));
  4865. emitRuntimeEvent(event('stalled-3'));
  4866. emitRuntimeEvent({
  4867. type: 'session.queue.updated',
  4868. timestampMs: 2,
  4869. source: 'runtime',
  4870. sessionId: 'session-1',
  4871. queuedCount: 1,
  4872. });
  4873. emitRuntimeEvent({
  4874. type: 'session.title_updated',
  4875. timestampMs: 3,
  4876. source: 'runtime',
  4877. sessionId: 'session-1',
  4878. title: 'Independent projection lane',
  4879. });
  4880. await vi.waitFor(() => expect(replyQuestionnaire).toHaveBeenCalledTimes(3));
  4881. await vi.waitFor(() => expect(getSession).toHaveBeenCalledOnce());
  4882. await vi.waitFor(() => expect(listQueuedMessages).toHaveBeenCalledOnce());
  4883. await vi.waitFor(() =>
  4884. expect(updates).toContainEqual({
  4885. sessionId: 'session-1',
  4886. update: {
  4887. sessionUpdate: 'session_info_update',
  4888. title: 'Independent projection lane',
  4889. updatedAt: new Date(3).toISOString(),
  4890. },
  4891. }),
  4892. );
  4893. await new Promise<void>((resolve) => setImmediate(resolve));
  4894. expect(getSession).toHaveBeenCalledOnce();
  4895. expect(listQueuedMessages).toHaveBeenCalledOnce();
  4896. });
  4897. });
  4898. it('drops a delayed projection after its ACP Session attachment closes', async () => {
  4899. const { runtime, emitRuntimeEvent, getSession } = createRuntime();
  4900. let resolveProjection:
  4901. | ((session: { sessionId: string; workspaceDir: string; interactionMode: 'plan' }) => void)
  4902. | undefined;
  4903. const updates: acp.SessionNotification[] = [];
  4904. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  4905. const client = acp
  4906. .client({ name: 'test-client' })
  4907. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
  4908. await client.connectWith(agent, async (connection) => {
  4909. await connection.request(acp.methods.agent.initialize, {
  4910. protocolVersion: acp.PROTOCOL_VERSION,
  4911. clientCapabilities: {},
  4912. });
  4913. const session = await connection.request(acp.methods.agent.session.new, {
  4914. cwd: '/workspace',
  4915. mcpServers: [],
  4916. });
  4917. getSession.mockImplementationOnce(
  4918. () =>
  4919. new Promise((resolve) => {
  4920. resolveProjection = resolve;
  4921. }),
  4922. );
  4923. emitRuntimeEvent({
  4924. type: 'session.start',
  4925. timestampMs: 1,
  4926. source: 'runtime',
  4927. sessionId: 'session-1',
  4928. turnId: 'turn-closing',
  4929. queueItemIds: [],
  4930. });
  4931. await vi.waitFor(() => expect(getSession).toHaveBeenCalledOnce());
  4932. await connection.request(acp.methods.agent.session.close, { sessionId: session.sessionId });
  4933. resolveProjection?.({
  4934. sessionId: 'session-1',
  4935. workspaceDir: '/workspace',
  4936. interactionMode: 'plan',
  4937. });
  4938. await new Promise<void>((resolve) => setImmediate(resolve));
  4939. expect(updates).not.toEqual(
  4940. expect.arrayContaining([
  4941. expect.objectContaining({
  4942. update: expect.objectContaining({ sessionUpdate: 'current_mode_update' }),
  4943. }),
  4944. ]),
  4945. );
  4946. });
  4947. });
  4948. it('does not rebind a pending projection to a replacement attachment', async () => {
  4949. const { runtime, emitRuntimeEvent, getSession } = createRuntime();
  4950. let resolveFirstProjection:
  4951. | ((session: { sessionId: string; workspaceDir: string; interactionMode: 'plan' }) => void)
  4952. | undefined;
  4953. const updates: acp.SessionNotification[] = [];
  4954. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  4955. const client = acp
  4956. .client({ name: 'test-client' })
  4957. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
  4958. await client.connectWith(agent, async (connection) => {
  4959. await connection.request(acp.methods.agent.initialize, {
  4960. protocolVersion: acp.PROTOCOL_VERSION,
  4961. clientCapabilities: {},
  4962. });
  4963. const session = await connection.request(acp.methods.agent.session.new, {
  4964. cwd: '/workspace',
  4965. mcpServers: [],
  4966. });
  4967. getSession
  4968. .mockImplementationOnce(
  4969. () =>
  4970. new Promise((resolve) => {
  4971. resolveFirstProjection = resolve;
  4972. }),
  4973. )
  4974. .mockResolvedValueOnce({
  4975. sessionId: 'session-1',
  4976. workspaceDir: '/workspace',
  4977. interactionMode: 'default',
  4978. });
  4979. emitRuntimeEvent({
  4980. type: 'session.start',
  4981. timestampMs: 1,
  4982. source: 'runtime',
  4983. sessionId: 'session-1',
  4984. turnId: 'turn-old',
  4985. queueItemIds: [],
  4986. });
  4987. await vi.waitFor(() => expect(getSession).toHaveBeenCalledOnce());
  4988. emitRuntimeEvent({
  4989. type: 'questionnaire.dismiss',
  4990. timestampMs: 2,
  4991. source: 'runtime',
  4992. sessionId: 'session-1',
  4993. requestId: 'question-old',
  4994. });
  4995. await new Promise<void>((resolve) => setImmediate(resolve));
  4996. await connection.request(acp.methods.agent.session.resume, {
  4997. sessionId: session.sessionId,
  4998. cwd: '/workspace',
  4999. mcpServers: [],
  5000. });
  5001. expect(getSession).toHaveBeenCalledTimes(2);
  5002. resolveFirstProjection?.({
  5003. sessionId: 'session-1',
  5004. workspaceDir: '/workspace',
  5005. interactionMode: 'plan',
  5006. });
  5007. await new Promise<void>((resolve) => setImmediate(resolve));
  5008. expect(updates).not.toEqual(
  5009. expect.arrayContaining([
  5010. expect.objectContaining({
  5011. update: expect.objectContaining({ sessionUpdate: 'current_mode_update' }),
  5012. }),
  5013. ]),
  5014. );
  5015. expect(getSession).toHaveBeenCalledTimes(2);
  5016. });
  5017. });
  5018. it('projects finish usage independently when its mode refresh is stalled and superseded', async () => {
  5019. const { runtime, emitRuntimeEvent, getSession } = createRuntime([], {
  5020. contextSnapshot: {
  5021. status: 'live',
  5022. model: { provider: 'minimax', id: 'm3', contextWindow: 10_000 },
  5023. contextUsage: {
  5024. contextWindowTokens: 10_000,
  5025. usedTokens: 2_000,
  5026. totalCountSource: 'LOCAL_ESTIMATE',
  5027. components: [],
  5028. },
  5029. compaction: { state: 'never' },
  5030. },
  5031. });
  5032. const updates: acp.SessionNotification[] = [];
  5033. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  5034. const client = acp
  5035. .client({ name: 'test-client' })
  5036. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
  5037. await client.connectWith(agent, async (connection) => {
  5038. await connection.request(acp.methods.agent.initialize, {
  5039. protocolVersion: acp.PROTOCOL_VERSION,
  5040. clientCapabilities: {},
  5041. });
  5042. await connection.request(acp.methods.agent.session.new, {
  5043. cwd: '/workspace',
  5044. mcpServers: [],
  5045. });
  5046. getSession.mockImplementation(() => new Promise(() => undefined));
  5047. emitRuntimeEvent({
  5048. type: 'session.finish',
  5049. timestampMs: 1,
  5050. source: 'runtime',
  5051. sessionId: 'session-1',
  5052. turnId: 'turn-finished',
  5053. queueItemIds: [],
  5054. });
  5055. emitRuntimeEvent({
  5056. type: 'session.start',
  5057. timestampMs: 2,
  5058. source: 'runtime',
  5059. sessionId: 'session-1',
  5060. turnId: 'turn-newer',
  5061. queueItemIds: [],
  5062. });
  5063. await vi.waitFor(() => expect(getSession).toHaveBeenCalledOnce());
  5064. await vi.waitFor(() =>
  5065. expect(updates).toContainEqual({
  5066. sessionId: 'session-1',
  5067. update: expect.objectContaining({
  5068. sessionUpdate: 'usage_update',
  5069. used: 2_000,
  5070. size: 10_000,
  5071. }),
  5072. }),
  5073. );
  5074. });
  5075. });
  5076. it('does not coalesce a title update away behind Session activity', async () => {
  5077. const { runtime, emitRuntimeEvent } = createRuntime();
  5078. let releaseActivity!: () => void;
  5079. const activityGate = new Promise<void>((resolve) => {
  5080. releaseActivity = resolve;
  5081. });
  5082. let blockFirstActivity = true;
  5083. const updates: acp.SessionNotification[] = [];
  5084. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  5085. const client = acp
  5086. .client({ name: 'test-client' })
  5087. .onNotification(acp.methods.client.session.update, async ({ params }) => {
  5088. updates.push(params);
  5089. if (
  5090. blockFirstActivity &&
  5091. params.update.sessionUpdate === 'session_info_update' &&
  5092. !('title' in params.update)
  5093. ) {
  5094. blockFirstActivity = false;
  5095. await activityGate;
  5096. }
  5097. });
  5098. await client.connectWith(agent, async (connection) => {
  5099. await connection.request(acp.methods.agent.initialize, {
  5100. protocolVersion: acp.PROTOCOL_VERSION,
  5101. clientCapabilities: {},
  5102. });
  5103. await connection.request(acp.methods.agent.session.new, {
  5104. cwd: '/workspace',
  5105. mcpServers: [],
  5106. });
  5107. emitRuntimeEvent({
  5108. type: 'session.start',
  5109. timestampMs: 1,
  5110. source: 'runtime',
  5111. sessionId: 'session-1',
  5112. turnId: 'turn-1',
  5113. queueItemIds: [],
  5114. });
  5115. await vi.waitFor(() =>
  5116. expect(updates).toContainEqual({
  5117. sessionId: 'session-1',
  5118. update: {
  5119. sessionUpdate: 'session_info_update',
  5120. updatedAt: new Date(1).toISOString(),
  5121. },
  5122. }),
  5123. );
  5124. emitRuntimeEvent({
  5125. type: 'session.title_updated',
  5126. timestampMs: 2,
  5127. source: 'runtime',
  5128. sessionId: 'session-1',
  5129. title: 'Durable title',
  5130. });
  5131. emitRuntimeEvent({
  5132. type: 'session.finish',
  5133. timestampMs: 3,
  5134. source: 'runtime',
  5135. sessionId: 'session-1',
  5136. turnId: 'turn-1',
  5137. queueItemIds: [],
  5138. });
  5139. await vi.waitFor(() =>
  5140. expect(updates).toContainEqual({
  5141. sessionId: 'session-1',
  5142. update: {
  5143. sessionUpdate: 'session_info_update',
  5144. title: 'Durable title',
  5145. updatedAt: new Date(2).toISOString(),
  5146. },
  5147. }),
  5148. );
  5149. releaseActivity();
  5150. });
  5151. });
  5152. it('serializes mode projections across Runtime event types for one Session', async () => {
  5153. const { runtime, emitRuntimeEvent, getSession } = createRuntime();
  5154. let resolveOlder:
  5155. | ((session: { sessionId: string; workspaceDir: string; interactionMode: 'plan' }) => void)
  5156. | undefined;
  5157. const updates: acp.SessionNotification[] = [];
  5158. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  5159. const client = acp
  5160. .client({ name: 'test-client' })
  5161. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params));
  5162. await client.connectWith(agent, async (connection) => {
  5163. await connection.request(acp.methods.agent.initialize, {
  5164. protocolVersion: acp.PROTOCOL_VERSION,
  5165. clientCapabilities: {},
  5166. });
  5167. await connection.request(acp.methods.agent.session.new, {
  5168. cwd: '/workspace',
  5169. mcpServers: [],
  5170. });
  5171. getSession
  5172. .mockImplementationOnce(
  5173. () =>
  5174. new Promise((resolve) => {
  5175. resolveOlder = resolve;
  5176. }),
  5177. )
  5178. .mockResolvedValueOnce({
  5179. sessionId: 'session-1',
  5180. workspaceDir: '/workspace',
  5181. interactionMode: 'default',
  5182. });
  5183. emitRuntimeEvent({
  5184. type: 'session.start',
  5185. timestampMs: 1,
  5186. source: 'runtime',
  5187. sessionId: 'session-1',
  5188. turnId: 'turn-older',
  5189. queueItemIds: [],
  5190. });
  5191. emitRuntimeEvent({
  5192. type: 'questionnaire.dismiss',
  5193. timestampMs: 2,
  5194. source: 'runtime',
  5195. sessionId: 'session-1',
  5196. requestId: 'question-newer',
  5197. });
  5198. await vi.waitFor(() => expect(getSession).toHaveBeenCalledOnce());
  5199. resolveOlder?.({
  5200. sessionId: 'session-1',
  5201. workspaceDir: '/workspace',
  5202. interactionMode: 'plan',
  5203. });
  5204. await vi.waitFor(() => expect(getSession).toHaveBeenCalledTimes(2));
  5205. await vi.waitFor(() =>
  5206. expect(
  5207. updates
  5208. .filter(({ update }) => update.sessionUpdate === 'current_mode_update')
  5209. .map(({ update }) =>
  5210. update.sessionUpdate === 'current_mode_update' ? update.currentModeId : undefined,
  5211. ),
  5212. ).toEqual(['plan', 'default']),
  5213. );
  5214. });
  5215. });
  5216. it('caps globally active projection lanes when unique Runtime reads never settle', async () => {
  5217. const { runtime, createSession, emitRuntimeEvent, getSession } = createRuntime();
  5218. let nextSession = 0;
  5219. createSession.mockImplementation(async ({ workspaceDir }: { workspaceDir: string }) => ({
  5220. sessionId: `session-${nextSession++}`,
  5221. workspaceDir,
  5222. }));
  5223. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  5224. const client = acp
  5225. .client({ name: 'test-client' })
  5226. .onNotification(acp.methods.client.session.update, () => undefined);
  5227. await client.connectWith(agent, async (connection) => {
  5228. await connection.request(acp.methods.agent.initialize, {
  5229. protocolVersion: acp.PROTOCOL_VERSION,
  5230. clientCapabilities: {},
  5231. });
  5232. for (let index = 0; index < 12; index += 1) {
  5233. await connection.request(acp.methods.agent.session.new, {
  5234. cwd: `/workspace/${index}`,
  5235. mcpServers: [],
  5236. });
  5237. }
  5238. getSession.mockImplementation(() => new Promise(() => undefined));
  5239. for (let index = 0; index < 12; index += 1) {
  5240. emitRuntimeEvent({
  5241. type: 'session.start',
  5242. timestampMs: index,
  5243. source: 'runtime',
  5244. sessionId: `session-${index}`,
  5245. turnId: `turn-${index}`,
  5246. queueItemIds: [],
  5247. });
  5248. }
  5249. await vi.waitFor(() => expect(getSession).toHaveBeenCalledTimes(8));
  5250. await new Promise<void>((resolve) => setImmediate(resolve));
  5251. expect(getSession).toHaveBeenCalledTimes(8);
  5252. });
  5253. });
  5254. it('serializes delegation fan-out and reuses one snapshot for a shared root', async () => {
  5255. const { runtime, createSession, emitRuntimeEvent, getSession, getDelegationSnapshot } =
  5256. createRuntime();
  5257. let nextSession = 1;
  5258. createSession.mockImplementation(async ({ workspaceDir }: { workspaceDir: string }) => ({
  5259. sessionId: `session-${nextSession++}`,
  5260. workspaceDir,
  5261. parentSessionId: 'session-root',
  5262. }));
  5263. getSession.mockResolvedValue({ sessionId: 'session-root', workspaceDir: '/workspace' });
  5264. let releaseSnapshot!: () => void;
  5265. const snapshotGate = new Promise<void>((resolve) => {
  5266. releaseSnapshot = resolve;
  5267. });
  5268. let activeSnapshots = 0;
  5269. let peakSnapshots = 0;
  5270. getDelegationSnapshot.mockImplementation(async (rootSessionId: string) => {
  5271. activeSnapshots += 1;
  5272. peakSnapshots = Math.max(peakSnapshots, activeSnapshots);
  5273. await snapshotGate;
  5274. activeSnapshots -= 1;
  5275. return { schemaVersion: 1, rootSessionId, members: [] };
  5276. });
  5277. const delegationUpdates: unknown[] = [];
  5278. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  5279. const client = acp.client({ name: 'test-client' }).onNotification(
  5280. 'mcode/session/delegation_update',
  5281. (params) => params,
  5282. ({ params }) => delegationUpdates.push(params),
  5283. );
  5284. await client.connectWith(agent, async (connection) => {
  5285. await connection.request(acp.methods.agent.initialize, {
  5286. protocolVersion: acp.PROTOCOL_VERSION,
  5287. clientCapabilities: {
  5288. _meta: { 'minimax-code/extensions': { version: 1, notifications: true } },
  5289. },
  5290. });
  5291. for (let index = 0; index < 3; index += 1) {
  5292. await connection.request(acp.methods.agent.session.new, {
  5293. cwd: `/workspace/${index}`,
  5294. mcpServers: [],
  5295. });
  5296. }
  5297. emitRuntimeEvent({
  5298. type: 'session.created',
  5299. timestampMs: 1,
  5300. source: 'runtime',
  5301. sessionId: 'session-child',
  5302. agentName: 'worker',
  5303. sessionType: 'branch',
  5304. parentSessionId: 'session-root',
  5305. });
  5306. await vi.waitFor(() => expect(getDelegationSnapshot).toHaveBeenCalledOnce());
  5307. expect(activeSnapshots).toBe(1);
  5308. releaseSnapshot();
  5309. await vi.waitFor(() => expect(delegationUpdates).toHaveLength(3));
  5310. });
  5311. expect(getDelegationSnapshot).toHaveBeenCalledOnce();
  5312. expect(peakSnapshots).toBe(1);
  5313. });
  5314. it('rejects a second Client connection to preserve connection-owned ACP state', async () => {
  5315. const { runtime, createSession } = createRuntime();
  5316. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  5317. const firstClient = acp.client({ name: 'first-client' });
  5318. const secondClient = acp.client({ name: 'second-client' });
  5319. await firstClient.connectWith(agent, async (firstConnection) => {
  5320. await firstConnection.request(acp.methods.agent.initialize, {
  5321. protocolVersion: acp.PROTOCOL_VERSION,
  5322. clientCapabilities: {},
  5323. });
  5324. await expect(
  5325. secondClient.connectWith(agent, (secondConnection) =>
  5326. secondConnection.request(acp.methods.agent.initialize, {
  5327. protocolVersion: acp.PROTOCOL_VERSION,
  5328. clientCapabilities: {},
  5329. }),
  5330. ),
  5331. ).rejects.toThrow('ACP connection closed');
  5332. await firstConnection.request(acp.methods.agent.session.new, {
  5333. cwd: '/workspace',
  5334. mcpServers: [],
  5335. });
  5336. expect(createSession).toHaveBeenCalledOnce();
  5337. });
  5338. });
  5339. it('cancels a stale ACP permission prompt when Runtime resolves the request', async () => {
  5340. const { runtime, emitRuntimeEvent, replyPermission } = createRuntime();
  5341. let firstRequested!: () => void;
  5342. const firstRequest = new Promise<void>((resolve) => {
  5343. firstRequested = resolve;
  5344. });
  5345. const client = acp
  5346. .client({ name: 'test-client' })
  5347. .onRequest(acp.methods.client.session.requestPermission, ({ params }) => {
  5348. if (params.toolCall.toolCallId === 'permission-stale') {
  5349. firstRequested();
  5350. return new Promise<acp.RequestPermissionResponse>(() => undefined);
  5351. }
  5352. return { outcome: { outcome: 'selected', optionId: 'allow-once' } };
  5353. });
  5354. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  5355. await client.connectWith(agent, async (connection) => {
  5356. await connection.request(acp.methods.agent.initialize, {
  5357. protocolVersion: acp.PROTOCOL_VERSION,
  5358. clientCapabilities: {},
  5359. });
  5360. await connection.request(acp.methods.agent.session.new, {
  5361. cwd: '/workspace',
  5362. mcpServers: [],
  5363. });
  5364. emitRuntimeEvent(permissionEvent('permission-stale'));
  5365. await firstRequest;
  5366. emitRuntimeEvent({
  5367. type: 'permission.resolved',
  5368. timestampMs: 2,
  5369. source: 'runtime',
  5370. sessionId: 'session-1',
  5371. requestId: 'permission-stale',
  5372. decision: 'deny',
  5373. });
  5374. emitRuntimeEvent(permissionEvent('permission-next'));
  5375. await vi.waitFor(() =>
  5376. expect(replyPermission).toHaveBeenCalledWith('mcode', 'permission-next', 'allowOnce'),
  5377. );
  5378. });
  5379. expect(replyPermission).not.toHaveBeenCalledWith(
  5380. 'mcode',
  5381. 'permission-stale',
  5382. expect.anything(),
  5383. );
  5384. });
  5385. it('closes the connection when terminated Client interactions ignore cancellation', async () => {
  5386. const { runtime, emitRuntimeEvent } = createRuntime();
  5387. const requested: string[] = [];
  5388. const client = acp
  5389. .client({ name: 'test-client' })
  5390. .onRequest(acp.methods.client.session.requestPermission, ({ params }) => {
  5391. requested.push(params.toolCall.toolCallId);
  5392. return new Promise<acp.RequestPermissionResponse>(() => undefined);
  5393. });
  5394. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  5395. await client
  5396. .connectWith(agent, async (connection) => {
  5397. await connection.request(acp.methods.agent.initialize, {
  5398. protocolVersion: acp.PROTOCOL_VERSION,
  5399. clientCapabilities: {},
  5400. });
  5401. await connection.request(acp.methods.agent.session.new, {
  5402. cwd: '/workspace',
  5403. mcpServers: [],
  5404. });
  5405. for (let index = 0; index < 3; index += 1) {
  5406. const requestId = `permission-detached-${index}`;
  5407. emitRuntimeEvent(permissionEvent(requestId));
  5408. await vi.waitFor(() => expect(requested).toContain(requestId));
  5409. emitRuntimeEvent({
  5410. type: 'permission.resolved',
  5411. timestampMs: 2 + index,
  5412. source: 'runtime',
  5413. sessionId: 'session-1',
  5414. requestId,
  5415. decision: 'deny',
  5416. });
  5417. }
  5418. await vi.waitFor(() => expect(connection.signal.aborted).toBe(true));
  5419. })
  5420. .catch(() => undefined);
  5421. });
  5422. it('does not let an old attachment terminal event terminate a reused request id', async () => {
  5423. const { runtime, emitRuntimeEvent, replyPermission } = createRuntime();
  5424. const answers: Array<(response: acp.RequestPermissionResponse) => void> = [];
  5425. const client = acp.client({ name: 'test-client' }).onRequest(
  5426. acp.methods.client.session.requestPermission,
  5427. () =>
  5428. new Promise<acp.RequestPermissionResponse>((resolve) => {
  5429. answers.push(resolve);
  5430. }),
  5431. );
  5432. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  5433. await client.connectWith(agent, async (connection) => {
  5434. await connection.request(acp.methods.agent.initialize, {
  5435. protocolVersion: acp.PROTOCOL_VERSION,
  5436. clientCapabilities: {},
  5437. });
  5438. const session = await connection.request(acp.methods.agent.session.new, {
  5439. cwd: '/workspace',
  5440. mcpServers: [],
  5441. });
  5442. emitRuntimeEvent(permissionEvent('permission-reused'));
  5443. await vi.waitFor(() => expect(answers).toHaveLength(1));
  5444. await connection.request(acp.methods.agent.session.resume, {
  5445. sessionId: session.sessionId,
  5446. cwd: '/workspace',
  5447. mcpServers: [],
  5448. });
  5449. emitRuntimeEvent(permissionEvent('permission-reused'));
  5450. await vi.waitFor(() => expect(answers).toHaveLength(2));
  5451. emitRuntimeEvent({
  5452. type: 'permission.resolved',
  5453. timestampMs: 2,
  5454. source: 'runtime',
  5455. sessionId: 'session-1',
  5456. requestId: 'permission-reused',
  5457. decision: 'deny',
  5458. });
  5459. answers[1]?.({ outcome: { outcome: 'selected', optionId: 'allow-once' } });
  5460. await vi.waitFor(() =>
  5461. expect(replyPermission).toHaveBeenCalledWith('mcode', 'permission-reused', 'allowOnce'),
  5462. );
  5463. });
  5464. });
  5465. it('consumes duplicate request terminals one interaction at a time', async () => {
  5466. const { runtime, emitRuntimeEvent, replyPermission } = createRuntime();
  5467. const answers: Array<(response: acp.RequestPermissionResponse) => void> = [];
  5468. const client = acp.client({ name: 'test-client' }).onRequest(
  5469. acp.methods.client.session.requestPermission,
  5470. () =>
  5471. new Promise<acp.RequestPermissionResponse>((resolve) => {
  5472. answers.push(resolve);
  5473. }),
  5474. );
  5475. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  5476. await client.connectWith(agent, async (connection) => {
  5477. await connection.request(acp.methods.agent.initialize, {
  5478. protocolVersion: acp.PROTOCOL_VERSION,
  5479. clientCapabilities: {},
  5480. });
  5481. await connection.request(acp.methods.agent.session.new, {
  5482. cwd: '/workspace',
  5483. mcpServers: [],
  5484. });
  5485. emitRuntimeEvent(permissionEvent('permission-duplicate'));
  5486. emitRuntimeEvent(permissionEvent('permission-duplicate'));
  5487. await vi.waitFor(() => expect(answers).toHaveLength(1));
  5488. emitRuntimeEvent({
  5489. type: 'permission.resolved',
  5490. timestampMs: 2,
  5491. source: 'runtime',
  5492. sessionId: 'session-1',
  5493. requestId: 'permission-duplicate',
  5494. decision: 'deny',
  5495. });
  5496. await vi.waitFor(() => expect(answers).toHaveLength(2));
  5497. answers[1]?.({ outcome: { outcome: 'selected', optionId: 'allow-once' } });
  5498. await vi.waitFor(() =>
  5499. expect(replyPermission).toHaveBeenCalledWith('mcode', 'permission-duplicate', 'allowOnce'),
  5500. );
  5501. });
  5502. });
  5503. it('settles a blocked Prompt when Runtime dismisses its Questionnaire', async () => {
  5504. const { runtime, emitRuntimeEvent, dismissQuestionnaire } = createRuntime();
  5505. let releaseBlockedRun!: () => void;
  5506. const blockedRun = new Promise<void>((resolve) => {
  5507. releaseBlockedRun = resolve;
  5508. });
  5509. let markRunStarted!: () => void;
  5510. const runStarted = new Promise<void>((resolve) => {
  5511. markRunStarted = resolve;
  5512. });
  5513. vi.mocked(runtime.sendMessage).mockImplementation(() =>
  5514. (async function* blockedRunEvents() {
  5515. markRunStarted();
  5516. await blockedRun;
  5517. yield {
  5518. type: 'generic',
  5519. eventType: 'runtime.action-required',
  5520. data: { kind: 'questionnaire' },
  5521. turnId: 'turn-dismissed',
  5522. } as const;
  5523. })(),
  5524. );
  5525. let questionnaireRequested!: () => void;
  5526. const requested = new Promise<void>((resolve) => {
  5527. questionnaireRequested = resolve;
  5528. });
  5529. const client = acp
  5530. .client({ name: 'test-client' })
  5531. .onRequest(acp.methods.client.elicitation.create, () => {
  5532. questionnaireRequested();
  5533. return new Promise<acp.CreateElicitationResponse>(() => undefined);
  5534. });
  5535. const agent = createTuiAcpAgent({
  5536. runtime,
  5537. version: '1.2.3',
  5538. createTurnId: () => 'turn-dismissed',
  5539. });
  5540. await client.connectWith(agent, async (connection) => {
  5541. await connection.request(acp.methods.agent.initialize, {
  5542. protocolVersion: acp.PROTOCOL_VERSION,
  5543. clientCapabilities: { elicitation: { form: {} } },
  5544. });
  5545. const session = await connection.request(acp.methods.agent.session.new, {
  5546. cwd: '/workspace',
  5547. mcpServers: [],
  5548. });
  5549. const prompt = connection.request(acp.methods.agent.session.prompt, {
  5550. sessionId: session.sessionId,
  5551. prompt: [{ type: 'text', text: 'Ask and then expire' }],
  5552. });
  5553. await runStarted;
  5554. emitRuntimeEvent(questionnaireEvent('questionnaire-expired'));
  5555. await requested;
  5556. emitRuntimeEvent({
  5557. type: 'questionnaire.dismiss',
  5558. timestampMs: 2,
  5559. source: 'runtime',
  5560. sessionId: 'session-1',
  5561. requestId: 'questionnaire-expired',
  5562. });
  5563. releaseBlockedRun();
  5564. await expect(prompt).resolves.toEqual({ stopReason: 'end_turn' });
  5565. });
  5566. expect(dismissQuestionnaire).not.toHaveBeenCalledWith('mcode', 'questionnaire-expired');
  5567. });
  5568. it('stops a Questionnaire continuation when Runtime aborts its Turn', async () => {
  5569. const continuation = new TuiAcpPromptContinuation('session-1', 'turn-aborted');
  5570. continuation.observe(questionnaireEvent('questionnaire-aborted'));
  5571. continuation.observe({
  5572. type: 'session.abort',
  5573. timestampMs: 2,
  5574. source: 'runtime',
  5575. sessionId: 'session-1',
  5576. turnId: 'turn-aborted',
  5577. queueItemIds: [],
  5578. });
  5579. await expect(
  5580. continuation.waitForTransition('turn-aborted', new AbortController().signal, {
  5581. requireQuestion: true,
  5582. }),
  5583. ).resolves.toEqual({ kind: 'cancelled' });
  5584. });
  5585. it('preserves the last mode selection made while a Prompt is running', async () => {
  5586. const { runtime, getSession } = createRuntime();
  5587. getSession.mockResolvedValue({
  5588. sessionId: 'session-1',
  5589. workspaceDir: '/workspace',
  5590. interactionMode: 'default',
  5591. });
  5592. let releaseFirst!: () => void;
  5593. const firstGate = new Promise<void>((resolve) => {
  5594. releaseFirst = resolve;
  5595. });
  5596. const requests: Array<{ clientIntent?: string }> = [];
  5597. vi.mocked(runtime.sendMessage).mockImplementation((request) =>
  5598. (async function* modeRuns() {
  5599. requests.push(request);
  5600. if (requests.length === 1) await firstGate;
  5601. yield { type: 'session-status', status: 'finished', turnId: request.turnId } as const;
  5602. })(),
  5603. );
  5604. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  5605. const client = acp.client({ name: 'test-client' });
  5606. await client.connectWith(agent, async (connection) => {
  5607. await connection.request(acp.methods.agent.initialize, {
  5608. protocolVersion: acp.PROTOCOL_VERSION,
  5609. clientCapabilities: {},
  5610. });
  5611. const session = await connection.request(acp.methods.agent.session.new, {
  5612. cwd: '/workspace',
  5613. mcpServers: [],
  5614. });
  5615. await connection.request(acp.methods.agent.session.setMode, {
  5616. sessionId: session.sessionId,
  5617. modeId: 'plan',
  5618. });
  5619. const firstPrompt = connection.request(acp.methods.agent.session.prompt, {
  5620. sessionId: session.sessionId,
  5621. prompt: [{ type: 'text', text: 'Plan first' }],
  5622. });
  5623. await vi.waitFor(() => expect(requests).toHaveLength(1));
  5624. await expect(
  5625. connection.request(acp.methods.agent.session.setMode, {
  5626. sessionId: session.sessionId,
  5627. modeId: 'default',
  5628. }),
  5629. ).resolves.toEqual({ _meta: { 'minimax-code/transition': 'next_prompt' } });
  5630. releaseFirst();
  5631. await expect(firstPrompt).resolves.toEqual({ stopReason: 'end_turn' });
  5632. await expect(
  5633. connection.request(acp.methods.agent.session.prompt, {
  5634. sessionId: session.sessionId,
  5635. prompt: [{ type: 'text', text: 'Stay in default mode' }],
  5636. }),
  5637. ).resolves.toEqual({ stopReason: 'end_turn' });
  5638. });
  5639. expect(requests.map(({ clientIntent }) => clientIntent)).toEqual(['plan-entry', 'plan-exit']);
  5640. });
  5641. it('removes a delivered Plan when the Session attachment is replaced', async () => {
  5642. const { runtime, emitRuntimeEvent } = createRuntime();
  5643. const updates: acp.SessionNotification[] = [];
  5644. const client = acp
  5645. .client({ name: 'test-client' })
  5646. .onNotification(acp.methods.client.session.update, ({ params }) => updates.push(params))
  5647. .onRequest(
  5648. acp.methods.client.elicitation.create,
  5649. () => new Promise<acp.CreateElicitationResponse>(() => undefined),
  5650. );
  5651. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  5652. await client.connectWith(agent, async (connection) => {
  5653. await connection.request(acp.methods.agent.initialize, {
  5654. protocolVersion: acp.PROTOCOL_VERSION,
  5655. clientCapabilities: { plan: {}, elicitation: { form: {} } },
  5656. });
  5657. const session = await connection.request(acp.methods.agent.session.new, {
  5658. cwd: '/workspace',
  5659. mcpServers: [],
  5660. });
  5661. emitRuntimeEvent(planReviewEvent(1));
  5662. await vi.waitFor(() =>
  5663. expect(updates).toContainEqual({
  5664. sessionId: 'session-1',
  5665. update: expect.objectContaining({
  5666. sessionUpdate: 'plan_update',
  5667. plan: expect.objectContaining({ planId: 'plan-1' }),
  5668. }),
  5669. }),
  5670. );
  5671. await connection.request(acp.methods.agent.session.resume, {
  5672. sessionId: session.sessionId,
  5673. cwd: '/workspace',
  5674. mcpServers: [],
  5675. });
  5676. await vi.waitFor(() =>
  5677. expect(updates).toContainEqual({
  5678. sessionId: 'session-1',
  5679. update: { sessionUpdate: 'plan_removed', planId: 'plan-1' },
  5680. }),
  5681. );
  5682. });
  5683. });
  5684. it('serializes fork MCP initialization with a concurrent resume', async () => {
  5685. const { runtime, clearSessionMcpServers, configureSessionMcpServers } = createRuntime();
  5686. let releaseForkMcp!: () => void;
  5687. const forkMcpGate = new Promise<void>((resolve) => {
  5688. releaseForkMcp = resolve;
  5689. });
  5690. configureSessionMcpServers.mockImplementation(async (_sessionId, servers) => {
  5691. if (servers[0]?.name === 'fork-tools') await forkMcpGate;
  5692. });
  5693. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  5694. const client = acp.client({ name: 'test-client' });
  5695. await client.connectWith(agent, async (connection) => {
  5696. await connection.request(acp.methods.agent.initialize, {
  5697. protocolVersion: acp.PROTOCOL_VERSION,
  5698. clientCapabilities: {},
  5699. });
  5700. const session = await connection.request(acp.methods.agent.session.new, {
  5701. cwd: '/workspace',
  5702. mcpServers: [],
  5703. });
  5704. clearSessionMcpServers.mockClear();
  5705. const fork = connection.request(acp.methods.agent.session.fork, {
  5706. sessionId: session.sessionId,
  5707. cwd: '/workspace',
  5708. mcpServers: [{ name: 'fork-tools', command: '/bin/fork', args: [], env: [] }],
  5709. });
  5710. await vi.waitFor(() =>
  5711. expect(configureSessionMcpServers).toHaveBeenCalledWith(
  5712. 'session-fork',
  5713. expect.arrayContaining([expect.objectContaining({ name: 'fork-tools' })]),
  5714. ),
  5715. );
  5716. const resume = connection.request(acp.methods.agent.session.resume, {
  5717. sessionId: 'session-fork',
  5718. cwd: '/workspace',
  5719. mcpServers: [{ name: 'resume-tools', command: '/bin/resume', args: [], env: [] }],
  5720. });
  5721. await new Promise<void>((resolve) => setImmediate(resolve));
  5722. expect(clearSessionMcpServers).not.toHaveBeenCalled();
  5723. releaseForkMcp();
  5724. await expect(fork).resolves.toMatchObject({ sessionId: 'session-fork' });
  5725. await expect(resume).resolves.toMatchObject({ modes: { currentModeId: 'default' } });
  5726. });
  5727. expect(configureSessionMcpServers.mock.calls.map(([, servers]) => servers[0]?.name)).toEqual([
  5728. 'fork-tools',
  5729. 'resume-tools',
  5730. ]);
  5731. });
  5732. it('finishes failed fork cleanup before admitting a resume for the fork target', async () => {
  5733. const { runtime, clearSessionMcpServers, configureSessionMcpServers, deleteSession } =
  5734. createRuntime();
  5735. let failForkMcp!: () => void;
  5736. const forkMcpGate = new Promise<void>((resolve) => {
  5737. failForkMcp = resolve;
  5738. });
  5739. configureSessionMcpServers.mockImplementation(async (_sessionId, servers) => {
  5740. if (servers[0]?.name === 'fork-tools') {
  5741. await forkMcpGate;
  5742. throw new Error('fork MCP failed');
  5743. }
  5744. });
  5745. let finishDelete!: () => void;
  5746. deleteSession.mockImplementation(
  5747. () =>
  5748. new Promise<void>((resolve) => {
  5749. finishDelete = resolve;
  5750. }),
  5751. );
  5752. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  5753. const client = acp.client({ name: 'test-client' });
  5754. await client.connectWith(agent, async (connection) => {
  5755. await connection.request(acp.methods.agent.initialize, {
  5756. protocolVersion: acp.PROTOCOL_VERSION,
  5757. clientCapabilities: {},
  5758. });
  5759. const source = await connection.request(acp.methods.agent.session.new, {
  5760. cwd: '/workspace',
  5761. mcpServers: [],
  5762. });
  5763. clearSessionMcpServers.mockClear();
  5764. const fork = connection.request(acp.methods.agent.session.fork, {
  5765. sessionId: source.sessionId,
  5766. cwd: '/workspace',
  5767. mcpServers: [{ name: 'fork-tools', command: '/bin/fork', args: [], env: [] }],
  5768. });
  5769. void fork.catch(() => undefined);
  5770. await vi.waitFor(() => expect(configureSessionMcpServers).toHaveBeenCalledOnce());
  5771. const resume = connection.request(acp.methods.agent.session.resume, {
  5772. sessionId: 'session-fork',
  5773. cwd: '/workspace',
  5774. mcpServers: [{ name: 'resume-tools', command: '/bin/resume', args: [], env: [] }],
  5775. });
  5776. failForkMcp();
  5777. await vi.waitFor(() => expect(deleteSession).toHaveBeenCalledWith('session-fork'));
  5778. expect(clearSessionMcpServers).not.toHaveBeenCalled();
  5779. finishDelete();
  5780. await expect(fork).rejects.toThrow();
  5781. await expect(resume).resolves.toMatchObject({ modes: { currentModeId: 'default' } });
  5782. });
  5783. expect(clearSessionMcpServers).toHaveBeenCalledWith('session-fork');
  5784. });
  5785. it('fails a cancelled load immediately when its history read never returns', async () => {
  5786. const { runtime, clearSessionMcpServers, listMessagePage } = createRuntime();
  5787. listMessagePage.mockImplementation(() => new Promise(() => undefined));
  5788. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  5789. const client = acp.client({ name: 'test-client' });
  5790. await client.connectWith(agent, async (connection) => {
  5791. await connection.request(acp.methods.agent.initialize, {
  5792. protocolVersion: acp.PROTOCOL_VERSION,
  5793. clientCapabilities: {},
  5794. });
  5795. const session = await connection.request(acp.methods.agent.session.new, {
  5796. cwd: '/workspace',
  5797. mcpServers: [],
  5798. });
  5799. clearSessionMcpServers.mockClear();
  5800. const cancellation = new AbortController();
  5801. const load = connection.request(
  5802. acp.methods.agent.session.load,
  5803. { sessionId: session.sessionId, cwd: '/workspace', mcpServers: [] },
  5804. { cancellationSignal: cancellation.signal },
  5805. );
  5806. await vi.waitFor(() => expect(listMessagePage).toHaveBeenCalledOnce());
  5807. cancellation.abort();
  5808. await expect(load).rejects.toThrow('cancel');
  5809. await vi.waitFor(() => expect(clearSessionMcpServers).toHaveBeenCalledTimes(2));
  5810. await expect(
  5811. connection.request(acp.methods.agent.session.close, { sessionId: session.sessionId }),
  5812. ).rejects.toThrow();
  5813. });
  5814. });
  5815. it('does not commit a first attachment when cancellation wins the final MCP boundary', async () => {
  5816. const { runtime, clearSessionMcpServers, configureSessionMcpServers } = createRuntime();
  5817. const cancellation = new AbortController();
  5818. configureSessionMcpServers.mockImplementationOnce(async () => {
  5819. cancellation.abort();
  5820. });
  5821. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  5822. const client = acp.client({ name: 'test-client' });
  5823. await client.connectWith(agent, async (connection) => {
  5824. await connection.request(acp.methods.agent.initialize, {
  5825. protocolVersion: acp.PROTOCOL_VERSION,
  5826. clientCapabilities: {},
  5827. });
  5828. const resume = connection.request(
  5829. acp.methods.agent.session.resume,
  5830. {
  5831. sessionId: 'session-existing',
  5832. cwd: '/workspace',
  5833. mcpServers: [{ name: 'client-tools', command: '/bin/client-tools', args: [], env: [] }],
  5834. },
  5835. { cancellationSignal: cancellation.signal },
  5836. );
  5837. await expect(resume).rejects.toThrow('cancel');
  5838. await vi.waitFor(() => expect(clearSessionMcpServers.mock.calls.length).toBeGreaterThan(1));
  5839. await expect(
  5840. connection.request(acp.methods.agent.session.close, {
  5841. sessionId: 'session-existing',
  5842. }),
  5843. ).rejects.toThrow();
  5844. });
  5845. });
  5846. it('fails closed for unsupported additional directories', async () => {
  5847. const { runtime, createSession } = createRuntime();
  5848. const agent = createTuiAcpAgent({ runtime, version: '1.2.3' });
  5849. const client = acp.client({ name: 'test-client' });
  5850. await client.connectWith(agent, async (connection) => {
  5851. await connection.request(acp.methods.agent.initialize, {
  5852. protocolVersion: acp.PROTOCOL_VERSION,
  5853. clientCapabilities: {},
  5854. });
  5855. await expect(
  5856. connection.request(acp.methods.agent.session.new, {
  5857. cwd: '/workspace',
  5858. additionalDirectories: ['/other'],
  5859. mcpServers: [],
  5860. }),
  5861. ).rejects.toThrow('Additional directories are not supported by MiniMax Code ACP');
  5862. });
  5863. expect(createSession).not.toHaveBeenCalled();
  5864. });
  5865. });
  5866. function permissionEvent(requestId: string, sessionId = 'session-1'): TuiRuntimeEvent {
  5867. return {
  5868. type: 'permission.ask',
  5869. timestampMs: 1,
  5870. source: 'runtime',
  5871. sessionId,
  5872. request: {
  5873. requestId,
  5874. sessionId,
  5875. agentName: 'mcode',
  5876. toolName: 'edit_file',
  5877. allowAlwaysSupported: false,
  5878. },
  5879. };
  5880. }
  5881. function questionnaireEvent(requestId: string): TuiRuntimeEvent {
  5882. return {
  5883. type: 'questionnaire.ask',
  5884. timestampMs: 1,
  5885. source: 'runtime',
  5886. sessionId: 'session-1',
  5887. agentName: 'mcode',
  5888. request: {
  5889. schemaVersion: 1,
  5890. id: requestId,
  5891. requester: { sessionId: 'session-1', agentName: 'mcode' },
  5892. presentation: {
  5893. replaceComposer: false,
  5894. showProgress: false,
  5895. allowBackNavigation: false,
  5896. },
  5897. steps: [
  5898. {
  5899. id: 'approach',
  5900. question: 'Which approach?',
  5901. selectionMode: 'single',
  5902. options: [{ id: 'safe', label: 'Safe' }],
  5903. allowOther: false,
  5904. otherPlaceholder: '',
  5905. required: true,
  5906. },
  5907. ],
  5908. },
  5909. };
  5910. }
  5911. function planReviewEvent(index: number): TuiRuntimeEvent {
  5912. const sessionId = `session-${index}`;
  5913. return {
  5914. type: 'questionnaire.ask',
  5915. timestampMs: index,
  5916. source: 'runtime',
  5917. sessionId,
  5918. agentName: 'mcode',
  5919. request: {
  5920. schemaVersion: 1,
  5921. id: `plan-${index}`,
  5922. requester: { sessionId, agentName: 'mcode' },
  5923. presentation: {
  5924. replaceComposer: false,
  5925. showProgress: false,
  5926. allowBackNavigation: false,
  5927. },
  5928. steps: [],
  5929. mode: 'plan',
  5930. modePayload: {
  5931. planReview: { markdown: `# Plan ${index}`, path: `/plan-${index}.md` },
  5932. },
  5933. },
  5934. };
  5935. }