acp-agent.test.ts 211 KB

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