product-projection.test.ts 373 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932
  1. // ProductProjection 黄金测试首批(M2,docs/v4-refactor/13-golden-test-mapping)。
  2. // 形态:事件序列进、投影断言出(L1)。测试名携带 catalog 组别,供 coverage matrix 对账。
  3. import { describe, expect, it, vi } from "vitest";
  4. import type {
  5. EventId,
  6. SessionEvent,
  7. SessionEventType as SessionEventTypeUnion,
  8. SessionId,
  9. TraceId,
  10. TurnId,
  11. } from "@zcode/contracts";
  12. import { HookEventName, SessionEventType, ModelErrorCode } from "@zcode/contracts";
  13. import type {
  14. ConversationDelta,
  15. ConversationSnapshot,
  16. DeliveryProfile,
  17. } from "@zcode/shared/zcode-protocol-v4";
  18. import {
  19. DELIVERY_PROFILES,
  20. WORKFLOW_RUNS_LIMITS,
  21. applyConversationDeltas,
  22. coalesceConversationDeltas,
  23. conversationSnapshotSchema,
  24. filterConversationDeltasForProfile,
  25. hookInvocationRowSchema,
  26. workflowRunStepCounts,
  27. } from "@zcode/shared/zcode-protocol-v4";
  28. import { ProductProjection } from "../src/zcode-protocol-v4/index.js";
  29. // ── 事件序列构造器 ──
  30. class EventLog {
  31. private seq = 0;
  32. readonly events: SessionEvent[] = [];
  33. constructor(private readonly sessionId = "session-1") {}
  34. push(
  35. type: SessionEventTypeUnion,
  36. payload: unknown,
  37. opts: { timestampMs?: number; turnId?: string } = {},
  38. ): SessionEvent {
  39. this.seq += 1;
  40. const event: SessionEvent = {
  41. id: `event-${this.seq}` as EventId,
  42. sessionId: this.sessionId as SessionId,
  43. turnId: opts.turnId as TurnId | undefined,
  44. type,
  45. timestamp: new Date(opts.timestampMs ?? 1_700_000_000_000 + this.seq * 1000),
  46. traceId: "trace-1" as TraceId,
  47. sequenceNumber: this.seq,
  48. payload,
  49. };
  50. this.events.push(event);
  51. return event;
  52. }
  53. }
  54. function basicTurnEvents(log: EventLog, turnId = "turn-1"): void {
  55. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  56. log.push(
  57. SessionEventType.TurnStarted,
  58. { turnNumber: 1, input: "写一个 hello world" },
  59. { turnId },
  60. );
  61. log.push(
  62. SessionEventType.ModelStreaming,
  63. { kind: "text_start", delta: "", done: false },
  64. { turnId },
  65. );
  66. log.push(
  67. SessionEventType.ModelStreaming,
  68. { kind: "text_delta", delta: "Hello ", done: false },
  69. { turnId },
  70. );
  71. log.push(
  72. SessionEventType.ModelStreaming,
  73. { kind: "text_delta", delta: "world", done: false },
  74. { turnId },
  75. );
  76. log.push(
  77. SessionEventType.ModelStreaming,
  78. { kind: "text_end", delta: "", done: false },
  79. { turnId },
  80. );
  81. log.push(
  82. SessionEventType.ModelComplete,
  83. {
  84. content: "Hello world",
  85. stopReason: "end_turn",
  86. querySource: "main_turn",
  87. contextWindow: 200_000,
  88. usage: { inputTokens: 120, outputTokens: 30, cacheReadTokens: 40, cacheWriteTokens: 10 },
  89. },
  90. { turnId },
  91. );
  92. log.push(
  93. SessionEventType.TurnComplete,
  94. {
  95. response: "Hello world",
  96. tokenCount: 30,
  97. toolCallCount: 0,
  98. duration: 5000,
  99. resultType: "success",
  100. },
  101. { turnId },
  102. );
  103. }
  104. function runAll(events: readonly SessionEvent[]): {
  105. projection: ProductProjection;
  106. deltasPerEvent: ConversationDelta[][];
  107. snapshots: ConversationSnapshot[];
  108. } {
  109. const projection = new ProductProjection("session-1", "epoch-1");
  110. const deltasPerEvent: ConversationDelta[][] = [];
  111. const snapshots: ConversationSnapshot[] = [projection.getSnapshot()];
  112. for (const event of events) {
  113. deltasPerEvent.push(projection.applyEvent(event));
  114. snapshots.push(projection.getSnapshot());
  115. }
  116. return { projection, deltasPerEvent, snapshots };
  117. }
  118. function inputTextAppends(deltas: readonly ConversationDelta[]): string[] {
  119. return deltas.flatMap((delta) =>
  120. delta.op === "row.delta" && delta.path === "inputText" ? [delta.append] : [],
  121. );
  122. }
  123. // ── A 组:基础 turn 生命周期 ──
  124. describe("ProductProjection 黄金测试(L1)", () => {
  125. it("Highspeed 单 Turn output tokens 由权威投影累计且不受快照观察时机影响", () => {
  126. const log = new EventLog();
  127. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  128. log.push(
  129. SessionEventType.TurnStarted,
  130. { turnNumber: 1, input: "first", inputId: "command-1", messageId: "user-1" },
  131. { turnId: "turn-1" },
  132. );
  133. for (const outputTokens of [5, 7]) {
  134. log.push(
  135. SessionEventType.ModelComplete,
  136. {
  137. content: "step",
  138. stopReason: "end_turn",
  139. querySource: "main_turn",
  140. usage: { inputTokens: 10, outputTokens },
  141. },
  142. { turnId: "turn-1" },
  143. );
  144. }
  145. log.push(
  146. SessionEventType.TurnComplete,
  147. { response: "done", tokenCount: 12, toolCallCount: 1, duration: 100, resultType: "success" },
  148. { turnId: "turn-1" },
  149. );
  150. log.push(
  151. SessionEventType.TurnStarted,
  152. { turnNumber: 2, input: "second", inputId: "command-2", messageId: "user-2" },
  153. { turnId: "turn-2" },
  154. );
  155. log.push(
  156. SessionEventType.ModelComplete,
  157. {
  158. content: "done",
  159. stopReason: "end_turn",
  160. querySource: "main_turn",
  161. usage: { inputTokens: 8, outputTokens: 4 },
  162. },
  163. { turnId: "turn-2" },
  164. );
  165. log.push(
  166. SessionEventType.TurnComplete,
  167. { response: "done", tokenCount: 4, toolCallCount: 0, duration: 50, resultType: "success" },
  168. { turnId: "turn-2" },
  169. );
  170. const snapshot = runAll(log.events).projection.getSnapshot();
  171. const headers = snapshot.rows.window.filter((row) => row.kind === "turnHeader");
  172. expect(headers).toEqual([
  173. expect.objectContaining({ sourceCommandId: "command-1", outputTokens: 12 }),
  174. expect.objectContaining({ sourceCommandId: "command-2", outputTokens: 4 }),
  175. ]);
  176. expect(conversationSnapshotSchema.parse(snapshot).rows.window).toEqual(snapshot.rows.window);
  177. });
  178. it("Highspeed turn 终态持久化 CLI 聚合的模型/工具真实耗时", () => {
  179. const log = new EventLog();
  180. const turnId = "turn-highspeed-timing";
  181. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  182. log.push(
  183. SessionEventType.TurnStarted,
  184. { turnNumber: 1, input: "measure", inputId: "command-highspeed-timing", messageId: "user-1" },
  185. { turnId, timestampMs: 1_700_000_000_000 },
  186. );
  187. log.push(
  188. SessionEventType.ModelNetworkStatus,
  189. {
  190. type: "model_request_completed",
  191. requestId: "request-1",
  192. providerId: "account:bigmodel-highspeed-card",
  193. modelId: "glm-5.3",
  194. transport: "sse",
  195. attempt: 1,
  196. maxAttempts: 1,
  197. durationMs: 400,
  198. },
  199. { turnId, timestampMs: 1_700_000_000_500 },
  200. );
  201. log.push(
  202. SessionEventType.ModelNetworkStatus,
  203. {
  204. type: "model_request_completed",
  205. requestId: "request-fallback",
  206. providerId: "account:bigmodel-individual-coding-plan",
  207. modelId: "glm-5.3",
  208. transport: "sse",
  209. attempt: 1,
  210. maxAttempts: 1,
  211. durationMs: 10_000,
  212. },
  213. { turnId, timestampMs: 1_700_000_000_700 },
  214. );
  215. log.push(
  216. SessionEventType.ToolCallScheduled,
  217. {
  218. toolCallId: "tool-1",
  219. toolName: "Bash",
  220. input: { command: "echo ok" },
  221. schedule: { parallelGroups: [["tool-1"]], executionOrder: ["tool-1"] },
  222. },
  223. { turnId, timestampMs: 1_700_000_001_000 },
  224. );
  225. log.push(
  226. SessionEventType.ToolCallStarted,
  227. { toolCallId: "tool-1", toolName: "Bash", startedAt: new Date(1_700_000_001_000) },
  228. { turnId, timestampMs: 1_700_000_001_100 },
  229. );
  230. log.push(
  231. SessionEventType.ToolCallResult,
  232. { toolCallId: "tool-1", result: { success: true, content: "ok" }, duration: 900 },
  233. { turnId, timestampMs: 1_700_000_002_000 },
  234. );
  235. log.push(
  236. SessionEventType.TurnComplete,
  237. {
  238. response: "done",
  239. tokenCount: 20,
  240. toolCallCount: 1,
  241. duration: 3_000,
  242. resultType: "success",
  243. },
  244. { turnId, timestampMs: 1_700_000_003_000 },
  245. );
  246. const header = runAll(log.events)
  247. .projection.getSnapshot()
  248. .rows.window.find((row) => row.kind === "turnHeader");
  249. expect(header).toMatchObject({
  250. activeMs: 3_000,
  251. modelDurationMs: 400,
  252. toolDurationMs: 900,
  253. otherDurationMs: 1_700,
  254. });
  255. });
  256. it("Highspeed 卡失效降级后只记录 fallback 时间,不改变分享资格", () => {
  257. const log = new EventLog();
  258. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  259. log.push(
  260. SessionEventType.TurnStarted,
  261. {
  262. turnNumber: 1,
  263. input: "accelerated prompt",
  264. messageId: "user-highspeed-expired",
  265. inputId: "command-highspeed-expired",
  266. intent: {
  267. sourceCommandId: "command-highspeed-expired",
  268. queueItemId: "queue-highspeed-expired",
  269. clientId: "desktop",
  270. kind: "sendText",
  271. text: "accelerated prompt",
  272. admissionSeq: 1,
  273. admittedAt: 1_700_000_000_000,
  274. requestedDelivery: "startNow",
  275. admittedDelivery: "startNow",
  276. highspeed: {
  277. schemaVersion: 1,
  278. cardId: "hsc-expired",
  279. taskId: "session-1",
  280. provider: "builtin:bigmodel-coding-plan",
  281. model: "GLM-5.3",
  282. issuedAt: 1_700_000_000_000,
  283. expiresAt: 1_700_000_300_000,
  284. regularTps: 80,
  285. },
  286. },
  287. },
  288. { turnId: "turn-highspeed-expired" },
  289. );
  290. log.push(
  291. SessionEventType.TurnExecutionModelFallback,
  292. {
  293. inputId: "command-highspeed-expired",
  294. reason: "highspeed_card_expired",
  295. fromModelSelection: { providerId: "account:bigmodel-highspeed-card", modelId: "GLM-5.3" },
  296. toModelSelection: { providerId: "builtin:bigmodel-coding-plan", modelId: "GLM-5.3" },
  297. },
  298. { timestampMs: 1_700_000_301_000, turnId: "turn-highspeed-expired" },
  299. );
  300. const { projection } = runAll(log.events);
  301. const row = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput");
  302. expect(row).toMatchObject({
  303. highspeed: { fallbackAt: 1_700_000_301_000, fallbackReason: "highspeed_card_expired" },
  304. });
  305. expect(row?.highspeed).not.toHaveProperty("shareExcludedReason");
  306. });
  307. it("加速请求其他失败的降级同样写入 fallbackAt,并以 fallbackReason 区分提示文案", () => {
  308. // spec §2.2:任何失败都退回;Renderer 按 fallbackReason 选择“卡已到期”或“加速服务不可用”文案。
  309. const log = new EventLog();
  310. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  311. log.push(
  312. SessionEventType.TurnStarted,
  313. {
  314. turnNumber: 1,
  315. input: "accelerated prompt",
  316. messageId: "user-highspeed-failed",
  317. inputId: "command-highspeed-failed",
  318. intent: {
  319. sourceCommandId: "command-highspeed-failed",
  320. queueItemId: "queue-highspeed-failed",
  321. clientId: "desktop",
  322. kind: "sendText",
  323. text: "accelerated prompt",
  324. admissionSeq: 1,
  325. admittedAt: 1_700_000_000_000,
  326. requestedDelivery: "startNow",
  327. admittedDelivery: "startNow",
  328. highspeed: {
  329. schemaVersion: 1,
  330. cardId: "hsc-failed",
  331. taskId: "session-1",
  332. provider: "builtin:bigmodel-coding-plan",
  333. model: "GLM-5.3",
  334. issuedAt: 1_700_000_000_000,
  335. expiresAt: 1_700_000_300_000,
  336. },
  337. },
  338. },
  339. { turnId: "turn-highspeed-failed" },
  340. );
  341. log.push(
  342. SessionEventType.TurnExecutionModelFallback,
  343. {
  344. inputId: "command-highspeed-failed",
  345. reason: "highspeed_request_failed",
  346. fromModelSelection: { providerId: "account:bigmodel-highspeed-card", modelId: "GLM-5.3" },
  347. toModelSelection: { providerId: "builtin:bigmodel-coding-plan", modelId: "GLM-5.3" },
  348. },
  349. { timestampMs: 1_700_000_002_000, turnId: "turn-highspeed-failed" },
  350. );
  351. const { projection } = runAll(log.events);
  352. const row = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput");
  353. expect(row).toMatchObject({
  354. highspeed: { fallbackAt: 1_700_000_002_000, fallbackReason: "highspeed_request_failed" },
  355. });
  356. });
  357. it("Highspeed 流式输出降级时中断废弃内容,并让原模型从新行继续", () => {
  358. const log = new EventLog();
  359. const turnId = "turn-highspeed-stream-fallback";
  360. const projection = new ProductProjection("session-1", "epoch-1");
  361. const apply = (type: SessionEventTypeUnion, payload: unknown): void => {
  362. projection.applyEvent(log.push(type, payload, { turnId }));
  363. };
  364. apply(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  365. apply(SessionEventType.TurnStarted, {
  366. turnNumber: 1,
  367. input: "accelerated prompt",
  368. messageId: "user-highspeed-stream-fallback",
  369. inputId: "command-highspeed-stream-fallback",
  370. intent: {
  371. sourceCommandId: "command-highspeed-stream-fallback",
  372. kind: "sendText",
  373. text: "accelerated prompt",
  374. requestedDelivery: "startNow",
  375. highspeed: {
  376. schemaVersion: 1,
  377. cardId: "hsc-stream-fallback",
  378. taskId: "session-1",
  379. provider: "builtin:bigmodel-coding-plan",
  380. model: "GLM-5.3",
  381. issuedAt: 1_700_000_000_000,
  382. expiresAt: 1_700_000_300_000,
  383. },
  384. },
  385. });
  386. apply(SessionEventType.ModelStreaming, {
  387. kind: "reasoning_delta",
  388. delta: "discarded reasoning",
  389. done: false,
  390. });
  391. apply(SessionEventType.ModelStreaming, {
  392. kind: "text_delta",
  393. delta: "discarded accelerated output",
  394. done: false,
  395. });
  396. apply(SessionEventType.ModelStreaming, {
  397. kind: "tool_input_start",
  398. delta: "",
  399. done: false,
  400. toolCallId: "tool-highspeed-orphan",
  401. toolName: "CreateWorkflow",
  402. });
  403. apply(SessionEventType.ModelStreaming, {
  404. kind: "tool_input_delta",
  405. delta: '{"script":"unfinished',
  406. done: false,
  407. toolCallId: "tool-highspeed-orphan",
  408. });
  409. apply(SessionEventType.TurnExecutionModelFallback, {
  410. inputId: "command-highspeed-stream-fallback",
  411. reason: "highspeed_request_failed",
  412. fromModelSelection: { providerId: "account:zai-highspeed-card", modelId: "GLM-5.3" },
  413. toModelSelection: { providerId: "user-provider", modelId: "user-model" },
  414. });
  415. const discardedRows = projection.getSnapshot().rows.window;
  416. expect(discardedRows.find((row) => row.kind === "reasoning")).toMatchObject({
  417. state: "interrupted",
  418. text: "discarded reasoning",
  419. });
  420. expect(discardedRows.find((row) => row.kind === "assistantText")).toMatchObject({
  421. state: "interrupted",
  422. text: "discarded accelerated output",
  423. });
  424. expect(
  425. discardedRows.find(
  426. (row) => row.kind === "toolCall" && row.toolCallId === "tool-highspeed-orphan",
  427. ),
  428. ).toMatchObject({ status: "cancelled", inputText: '{"script":"unfinished' });
  429. // 部分 provider 不发送 text_start;降级事件也必须清空旧 row identity,避免 delta 拼进废弃输出。
  430. apply(SessionEventType.ModelStreaming, {
  431. kind: "text_delta",
  432. delta: "fresh session-model output",
  433. done: false,
  434. });
  435. expect(
  436. projection
  437. .getSnapshot()
  438. .rows.window.filter((row) => row.kind === "assistantText")
  439. .map((row) => ({ state: row.state, text: row.text })),
  440. ).toEqual([
  441. { state: "interrupted", text: "discarded accelerated output" },
  442. { state: "streaming", text: "fresh session-model output" },
  443. ]);
  444. });
  445. it("终态指标更新是增量合并,不清除同一 Turn 已产生的 fallbackAt", () => {
  446. // CR-02 回归:Highspeed 请求 3402 → TurnExecutionModelFallback 写入 fallbackAt → 普通模型跑完 →
  447. // persistHighspeedTiming 发 HighspeedMetricsUpdated。旧实现整体替换 row.highspeed,payload 又不含
  448. // live 才有的 fallbackAt,降级 Toast 依赖的字段被清掉。
  449. const highspeedMeta = {
  450. schemaVersion: 1,
  451. cardId: "hsc-expired",
  452. taskId: "session-1",
  453. provider: "builtin:bigmodel-coding-plan",
  454. model: "GLM-5.3",
  455. issuedAt: 1_700_000_000_000,
  456. expiresAt: 1_700_000_300_000,
  457. regularTps: 80,
  458. };
  459. const log = new EventLog();
  460. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  461. log.push(
  462. SessionEventType.TurnStarted,
  463. {
  464. turnNumber: 1,
  465. input: "accelerated prompt",
  466. messageId: "user-highspeed-expired",
  467. inputId: "command-highspeed-expired",
  468. intent: {
  469. sourceCommandId: "command-highspeed-expired",
  470. queueItemId: "queue-highspeed-expired",
  471. clientId: "desktop",
  472. kind: "sendText",
  473. text: "accelerated prompt",
  474. admissionSeq: 1,
  475. admittedAt: 1_700_000_000_000,
  476. requestedDelivery: "startNow",
  477. admittedDelivery: "startNow",
  478. highspeed: highspeedMeta,
  479. },
  480. },
  481. { turnId: "turn-highspeed-expired" },
  482. );
  483. log.push(
  484. SessionEventType.TurnExecutionModelFallback,
  485. {
  486. inputId: "command-highspeed-expired",
  487. reason: "highspeed_card_expired",
  488. fromModelSelection: { providerId: "account:bigmodel-highspeed-card", modelId: "GLM-5.3" },
  489. toModelSelection: { providerId: "builtin:bigmodel-coding-plan", modelId: "GLM-5.3" },
  490. },
  491. { timestampMs: 1_700_000_301_000, turnId: "turn-highspeed-expired" },
  492. );
  493. log.push(
  494. SessionEventType.HighspeedMetricsUpdated,
  495. {
  496. entityId: "user-highspeed-expired",
  497. highspeed: {
  498. ...highspeedMeta,
  499. outputTokens: 120,
  500. durationMs: 3_000,
  501. modelDurationMs: 400,
  502. toolDurationMs: 900,
  503. otherDurationMs: 1_700,
  504. },
  505. },
  506. { timestampMs: 1_700_000_305_000, turnId: "turn-highspeed-expired" },
  507. );
  508. const { projection } = runAll(log.events);
  509. const row = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput");
  510. expect(row).toMatchObject({
  511. highspeed: {
  512. fallbackAt: 1_700_000_301_000,
  513. outputTokens: 120,
  514. durationMs: 3_000,
  515. modelDurationMs: 400,
  516. toolDurationMs: 900,
  517. otherDurationMs: 1_700,
  518. },
  519. });
  520. });
  521. it("CUA response 的 reasoning、text 与 tool row 共享 assistantResponseId", () => {
  522. const log = new EventLog();
  523. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  524. log.push(
  525. SessionEventType.TurnStarted,
  526. { turnNumber: 1, input: "检查权限", messageId: "user-cua" },
  527. { turnId: "turn-cua" },
  528. );
  529. log.push(
  530. SessionEventType.ModelStreaming,
  531. {
  532. kind: "reasoning_start",
  533. delta: "",
  534. done: false,
  535. assistantMessageId: "assistant-cua",
  536. partId: "reasoning-cua",
  537. },
  538. { turnId: "turn-cua" },
  539. );
  540. log.push(
  541. SessionEventType.ModelStreaming,
  542. {
  543. kind: "text_start",
  544. delta: "",
  545. done: false,
  546. assistantMessageId: "assistant-cua",
  547. partId: "text-cua",
  548. },
  549. { turnId: "turn-cua" },
  550. );
  551. log.push(
  552. SessionEventType.ModelStreaming,
  553. {
  554. kind: "tool_input_start",
  555. delta: "",
  556. done: false,
  557. assistantMessageId: "assistant-cua",
  558. toolCallId: "call-cua",
  559. toolName: "mcp__computer-use__request_access",
  560. },
  561. { turnId: "turn-cua" },
  562. );
  563. log.push(
  564. SessionEventType.ToolCallScheduled,
  565. {
  566. toolCallId: "call-cua",
  567. assistantMessageId: "assistant-cua",
  568. toolName: "mcp__computer-use__request_access",
  569. input: {},
  570. schedule: { parallelGroups: [["call-cua"]], executionOrder: ["call-cua"] },
  571. },
  572. { turnId: "turn-cua" },
  573. );
  574. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  575. expect(rows.find((row) => row.kind === "reasoning")?.assistantResponseId).toBe("assistant-cua");
  576. expect(rows.find((row) => row.kind === "assistantText")?.assistantResponseId).toBe(
  577. "assistant-cua",
  578. );
  579. expect(rows.find((row) => row.kind === "toolCall")?.assistantResponseId).toBe("assistant-cua");
  580. });
  581. it("projects the submitted model, mode and Plan onto the user input row", () => {
  582. // docs/ui/composer-edit-mode.md:编辑最后一条消息时工具栏载入它提交时的配置,与排队项编辑一致。
  583. // 配置来自该输入的 canonical intent;旧输入没有这些字段时行上也不带,前端沿用当前配置。
  584. const modelSelection = {
  585. providerId: "provider-a",
  586. modelId: "model-a",
  587. options: { reasoningLevel: "high" },
  588. };
  589. const log = new EventLog();
  590. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  591. log.push(
  592. SessionEventType.TurnStarted,
  593. {
  594. turnNumber: 1,
  595. input: "with config",
  596. inputId: "command-with-config",
  597. intent: {
  598. sourceCommandId: "command-with-config",
  599. kind: "sendText",
  600. text: "with config",
  601. admissionSeq: 1,
  602. admittedAt: 10,
  603. requestedDelivery: "startNow",
  604. admittedDelivery: "startNow",
  605. modelSelection,
  606. mode: "yolo",
  607. planEnabled: true,
  608. },
  609. },
  610. { turnId: "turn-config" },
  611. );
  612. log.push(
  613. SessionEventType.TurnStarted,
  614. { turnNumber: 2, input: "legacy input" },
  615. { turnId: "turn-legacy" },
  616. );
  617. const userRows = runAll(log.events)
  618. .projection.getSnapshot()
  619. .rows.window.filter((row) => row.kind === "userInput");
  620. expect(userRows[0]).toMatchObject({ modelSelection, mode: "yolo", planEnabled: true });
  621. expect(userRows[1]).not.toHaveProperty("modelSelection");
  622. expect(userRows[1]).not.toHaveProperty("mode");
  623. expect(userRows[1]).not.toHaveProperty("planEnabled");
  624. });
  625. it("projects the submitted config onto user rows drained from the queue or guide", () => {
  626. // 队列续跑/guide 注入的 real-user 行同样可编辑;提交配置必须与 TurnStarted 行一致投影,
  627. // 否则编辑时会误当作旧消息而沿用当前工具栏(MR 3454 评审 CR-01)。
  628. const turnId = "turn-drain-config";
  629. const modelSelection = { providerId: "provider-a", modelId: "model-a" };
  630. const log = new EventLog();
  631. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  632. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  633. log.push(
  634. SessionEventType.TurnSteerDrained,
  635. {
  636. pendingInputIds: ["pi-config"],
  637. targetTurnId: turnId,
  638. injectedMessageIds: ["message-config"],
  639. drainedInputs: [
  640. {
  641. pendingInputId: "pi-config",
  642. messageId: "message-config",
  643. text: "drained with config",
  644. delivery: "guide",
  645. intent: {
  646. sourceCommandId: "command-config",
  647. queueItemId: "pi-config",
  648. clientId: "desktop",
  649. kind: "sendText",
  650. admissionSeq: 1,
  651. admittedAt: 10,
  652. requestedDelivery: "guide",
  653. admittedDelivery: "guide",
  654. modelSelection,
  655. mode: "yolo",
  656. planEnabled: true,
  657. },
  658. },
  659. ],
  660. },
  661. { turnId },
  662. );
  663. expect(runAll(log.events).projection.getSnapshot().rows.window.at(-1)).toMatchObject({
  664. kind: "userInput",
  665. text: "drained with config",
  666. modelSelection,
  667. mode: "yolo",
  668. planEnabled: true,
  669. });
  670. });
  671. it("preserves topic originals and attachment ownership when replaying accepted turn events", () => {
  672. const source = {
  673. provider: "feishu",
  674. botId: "bot",
  675. chatId: "group",
  676. threadId: "topic",
  677. senderId: "b",
  678. senderName: "Bob",
  679. messageId: "second",
  680. messages: [
  681. {
  682. messageId: "first",
  683. senderId: "a",
  684. senderName: "Alice",
  685. text: "First",
  686. attachmentIndexes: [0],
  687. conversationQuotes: [{ text: "Root", senderName: "Root author" }],
  688. },
  689. {
  690. messageId: "second",
  691. senderId: "b",
  692. senderName: "Bob",
  693. text: "Second",
  694. attachmentIndexes: [1],
  695. },
  696. ],
  697. };
  698. const log = new EventLog();
  699. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  700. log.push(
  701. SessionEventType.TurnStarted,
  702. {
  703. turnNumber: 1,
  704. input: "combined",
  705. messageId: "accepted",
  706. inputId: "command",
  707. intent: {
  708. sourceCommandId: "command",
  709. kind: "sendText",
  710. text: "combined",
  711. admissionSeq: 1,
  712. admittedAt: 10,
  713. requestedDelivery: "startNow",
  714. admittedDelivery: "startNow",
  715. botGroupSource: source,
  716. attachmentRefs: [
  717. { ref: "artifact://first", fileName: "first.txt", mime: "text/plain", bytes: 1 },
  718. { ref: "artifact://second", fileName: "second.txt", mime: "text/plain", bytes: 1 },
  719. ],
  720. },
  721. },
  722. { turnId: "topic-turn" },
  723. );
  724. const restored = log.events.map((event) => ({
  725. ...event,
  726. payload: JSON.parse(JSON.stringify(event.payload)),
  727. }));
  728. const snapshot = conversationSnapshotSchema.parse(runAll(restored).projection.getSnapshot());
  729. expect(snapshot.rows.window.find((row) => row.kind === "userInput")).toMatchObject({
  730. botGroupSource: source,
  731. attachments: [{ ref: "artifact://first" }, { ref: "artifact://second" }],
  732. });
  733. });
  734. it("TEL06:edit/rerun user row 保留 canonical root sourceCommandId", () => {
  735. const log = new EventLog();
  736. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  737. log.push(
  738. SessionEventType.TurnStarted,
  739. {
  740. turnNumber: 1,
  741. input: "retry prompt",
  742. messageId: "user-retry",
  743. inputId: "command-edit",
  744. foregroundExecutionId: "foreground-edit",
  745. intent: {
  746. sourceCommandId: "command-edit",
  747. queueItemId: "queue-edit",
  748. clientId: "desktop",
  749. kind: "sendText",
  750. text: "retry prompt",
  751. admissionSeq: 2,
  752. admittedAt: 1_700_000_000_000,
  753. requestedDelivery: "startNow",
  754. admittedDelivery: "startNow",
  755. provenance: { sourceCommandId: "command-original" },
  756. },
  757. },
  758. { turnId: "turn-retry" },
  759. );
  760. const { projection } = runAll(log.events);
  761. expect(conversationSnapshotSchema.parse(projection.getSnapshot()).control.activeWorks).toEqual([
  762. expect.objectContaining({
  763. foregroundExecutionId: "foreground-edit",
  764. sourceCommandId: "command-edit",
  765. }),
  766. ]);
  767. expect(
  768. projection.getSnapshot().rows.window.find((row) => row.kind === "userInput"),
  769. ).toMatchObject({
  770. sourceCommandId: "command-edit",
  771. rootSourceCommandId: "command-original",
  772. productTurnId: "user-retry",
  773. });
  774. });
  775. it("PV4-08:只给 completedSuccess 轮尾 assistant 下发 canFork,后续 turn running 时仍稳定", () => {
  776. const log = new EventLog();
  777. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  778. log.push(
  779. SessionEventType.TurnStarted,
  780. { turnNumber: 1, input: "first", messageId: "user-1" },
  781. { turnId: "turn-1" },
  782. );
  783. log.push(
  784. SessionEventType.ModelStreaming,
  785. { kind: "text_start", delta: "", done: false, assistantMessageId: "assistant-1" },
  786. { turnId: "turn-1" },
  787. );
  788. log.push(
  789. SessionEventType.ModelStreaming,
  790. { kind: "text_end", delta: "", done: false },
  791. { turnId: "turn-1" },
  792. );
  793. log.push(
  794. SessionEventType.TurnComplete,
  795. { response: "done", tokenCount: 1, toolCallCount: 0, duration: 1, resultType: "success" },
  796. { turnId: "turn-1" },
  797. );
  798. log.push(
  799. SessionEventType.TurnStarted,
  800. { turnNumber: 2, input: "second", messageId: "user-2" },
  801. { turnId: "turn-2" },
  802. );
  803. const { projection } = runAll(log.events);
  804. const firstAssistant = projection
  805. .getSnapshot()
  806. .rows.window.find((row) => row.kind === "assistantText" && row.turnId === "user-1");
  807. expect(firstAssistant?.actions).toEqual({ canFork: true });
  808. expect(projection.resolveStableForkCandidate(firstAssistant!.rowId)).toEqual({
  809. ok: true,
  810. candidate: {
  811. boundaryMessageId: "assistant-1",
  812. productTurnId: "user-1",
  813. startMessageId: "user-1",
  814. transcriptTurnId: "turn-1",
  815. },
  816. });
  817. expect(projection.getSnapshot().control.phase).toBe("running");
  818. });
  819. it("PV4-08:成功轮固化 fork 能力时不复制并反转完整 rows 窗口", () => {
  820. const log = new EventLog();
  821. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  822. log.push(
  823. SessionEventType.TurnStarted,
  824. { turnNumber: 1, input: "first", messageId: "user-1" },
  825. { turnId: "turn-1" },
  826. );
  827. log.push(
  828. SessionEventType.ModelStreaming,
  829. { kind: "text_start", delta: "", done: false, assistantMessageId: "assistant-1" },
  830. { turnId: "turn-1" },
  831. );
  832. log.push(
  833. SessionEventType.ModelStreaming,
  834. { kind: "text_end", delta: "", done: false },
  835. { turnId: "turn-1" },
  836. );
  837. const { projection } = runAll(log.events);
  838. const reverse = vi.spyOn(Array.prototype, "reverse").mockImplementation(() => {
  839. throw new Error("TurnComplete must not reverse the full rows window");
  840. });
  841. try {
  842. projection.applyEvent(
  843. log.push(
  844. SessionEventType.TurnComplete,
  845. {
  846. response: "done",
  847. tokenCount: 1,
  848. toolCallCount: 0,
  849. duration: 1,
  850. resultType: "success",
  851. },
  852. { turnId: "turn-1" },
  853. ),
  854. );
  855. } finally {
  856. reverse.mockRestore();
  857. }
  858. const assistant = projection
  859. .getSnapshot()
  860. .rows.window.find((row) => row.kind === "assistantText");
  861. expect(assistant?.actions?.canFork).toBe(true);
  862. });
  863. it("PV4-08:中间 assistant 段和 interrupted turn 都不可 fork", () => {
  864. const log = new EventLog();
  865. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  866. log.push(
  867. SessionEventType.TurnStarted,
  868. { turnNumber: 1, input: "first", messageId: "user-1" },
  869. { turnId: "turn-1" },
  870. );
  871. log.push(
  872. SessionEventType.ModelStreaming,
  873. { kind: "text_start", delta: "", done: false, assistantMessageId: "assistant-1a" },
  874. { turnId: "turn-1" },
  875. );
  876. log.push(
  877. SessionEventType.ModelStreaming,
  878. { kind: "text_end", delta: "", done: false },
  879. { turnId: "turn-1" },
  880. );
  881. log.push(
  882. SessionEventType.ModelStreaming,
  883. { kind: "text_start", delta: "", done: false, assistantMessageId: "assistant-1b" },
  884. { turnId: "turn-1" },
  885. );
  886. log.push(
  887. SessionEventType.TurnComplete,
  888. {
  889. response: "partial",
  890. tokenCount: 1,
  891. toolCallCount: 0,
  892. duration: 1,
  893. resultType: "cancelled",
  894. },
  895. { turnId: "turn-1" },
  896. );
  897. const { projection } = runAll(log.events);
  898. const assistants = projection
  899. .getSnapshot()
  900. .rows.window.filter((row) => row.kind === "assistantText");
  901. expect(assistants.every((row) => row.actions?.canFork !== true)).toBe(true);
  902. expect(projection.resolveStableForkCandidate(assistants[0]!.rowId)).toEqual({
  903. ok: false,
  904. reasonCode: "guard.forkTargetNotStable",
  905. });
  906. expect(projection.resolveStableForkCandidate(assistants[1]!.rowId)).toEqual({
  907. ok: false,
  908. reasonCode: "guard.forkTargetNotStable",
  909. });
  910. });
  911. it("OTC08:同一 turn 的 output-limit Continue 只投影一条累计 assistantText", () => {
  912. const log = new EventLog();
  913. const turnId = "turn-output-continue";
  914. const appendAssistantResponse = (
  915. assistantMessageId: string,
  916. partId: string,
  917. text: string,
  918. stopReason: "length" | "end_turn",
  919. ) => {
  920. log.push(
  921. SessionEventType.ModelStreaming,
  922. {
  923. kind: "text_start",
  924. delta: "",
  925. done: false,
  926. assistantMessageId,
  927. partId,
  928. },
  929. { turnId },
  930. );
  931. log.push(
  932. SessionEventType.ModelStreaming,
  933. { kind: "text_delta", delta: text, done: false, assistantMessageId, partId },
  934. { turnId },
  935. );
  936. log.push(
  937. SessionEventType.ModelStreaming,
  938. { kind: "text_end", delta: "", done: false, assistantMessageId, partId },
  939. { turnId },
  940. );
  941. log.push(
  942. SessionEventType.ModelComplete,
  943. {
  944. content: text,
  945. stopReason,
  946. querySource: "main_turn",
  947. toolCallCount: 0,
  948. usage: {
  949. inputTokens: 1,
  950. outputTokens: 1,
  951. cacheReadTokens: 0,
  952. cacheWriteTokens: 0,
  953. },
  954. },
  955. { turnId },
  956. );
  957. };
  958. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  959. log.push(
  960. SessionEventType.TurnStarted,
  961. { turnNumber: 1, input: "写一段长回复", messageId: "user-output-continue" },
  962. { turnId },
  963. );
  964. appendAssistantResponse("assistant-p1", "part-p1", "即使底层已经", "length");
  965. appendAssistantResponse("assistant-p2", "part-p2", "发起新的请求并停在", "length");
  966. appendAssistantResponse("assistant-p3", "part-p3", "一个尚未完成的位置。", "end_turn");
  967. log.push(
  968. SessionEventType.TurnComplete,
  969. {
  970. response: "一个尚未完成的位置。",
  971. tokenCount: 3,
  972. toolCallCount: 0,
  973. duration: 3_000,
  974. resultType: "success",
  975. },
  976. { turnId },
  977. );
  978. const { projection, deltasPerEvent } = runAll(log.events);
  979. const assistantRows = projection
  980. .getSnapshot()
  981. .rows.window.filter((row) => row.kind === "assistantText");
  982. expect(assistantRows).toHaveLength(1);
  983. expect(assistantRows[0]).toMatchObject({
  984. text: "即使底层已经发起新的请求并停在一个尚未完成的位置。",
  985. state: "complete",
  986. assistantResponseId: "assistant-p3",
  987. entityId: "assistant-p3",
  988. actions: { canFork: true },
  989. });
  990. expect(
  991. deltasPerEvent
  992. .flat()
  993. .filter((delta) => delta.op === "row.appended" && delta.row.kind === "assistantText"),
  994. ).toHaveLength(1);
  995. expect(projection.getMessageIdForRow(assistantRows[0]!.rowId)).toBe("assistant-p3");
  996. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  997. expect(projection.getMessageIdsForTurnRow(header!.rowId)).toEqual(
  998. expect.arrayContaining([
  999. "user-output-continue",
  1000. "assistant-p1",
  1001. "assistant-p2",
  1002. "assistant-p3",
  1003. ]),
  1004. );
  1005. });
  1006. it("OTC08:异步 session-title ModelComplete 不清除主 turn 的 Continue 资格", () => {
  1007. const log = new EventLog();
  1008. const turnId = "turn-output-continue-with-title-sidecar";
  1009. const appendAssistantResponse = (
  1010. assistantMessageId: string,
  1011. text: string,
  1012. stopReason: "length" | "end_turn",
  1013. ) => {
  1014. log.push(
  1015. SessionEventType.ModelStreaming,
  1016. { kind: "text_start", delta: "", done: false, assistantMessageId },
  1017. { turnId },
  1018. );
  1019. log.push(
  1020. SessionEventType.ModelStreaming,
  1021. { kind: "text_delta", delta: text, done: false, assistantMessageId },
  1022. { turnId },
  1023. );
  1024. log.push(
  1025. SessionEventType.ModelStreaming,
  1026. { kind: "text_end", delta: "", done: false, assistantMessageId },
  1027. { turnId },
  1028. );
  1029. log.push(
  1030. SessionEventType.ModelComplete,
  1031. {
  1032. content: text,
  1033. querySource: "main_turn",
  1034. stopReason,
  1035. toolCallCount: 0,
  1036. usage: {},
  1037. },
  1038. { turnId },
  1039. );
  1040. };
  1041. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  1042. log.push(
  1043. SessionEventType.TurnStarted,
  1044. { turnNumber: 1, input: "写一段长回复", messageId: "user-output-title-sidecar" },
  1045. { turnId },
  1046. );
  1047. appendAssistantResponse("assistant-title-p1", "主 turn 第一段", "length");
  1048. log.push(
  1049. SessionEventType.ModelComplete,
  1050. {
  1051. content: "标题",
  1052. querySource: "session_title",
  1053. stopReason: "end_turn",
  1054. toolCallCount: 0,
  1055. usage: {},
  1056. },
  1057. { turnId },
  1058. );
  1059. appendAssistantResponse("assistant-title-p2", "继续拼接完成。", "end_turn");
  1060. const { projection } = runAll(log.events);
  1061. const assistantRows = projection
  1062. .getSnapshot()
  1063. .rows.window.filter((row) => row.kind === "assistantText");
  1064. expect(assistantRows).toHaveLength(1);
  1065. expect(assistantRows[0]).toMatchObject({
  1066. text: "主 turn 第一段继续拼接完成。",
  1067. assistantResponseId: "assistant-title-p2",
  1068. state: "complete",
  1069. });
  1070. });
  1071. it.each([
  1072. { label: "含工具边界", stopReason: "length", toolCallCount: 1 },
  1073. { label: "缺少明确 zero-tool 事实", stopReason: "length", toolCallCount: undefined },
  1074. { label: "不是 output-limit", stopReason: "end_turn", toolCallCount: 0 },
  1075. ] as const)("OTC08:$label 时不复用 assistantText row", ({ stopReason, toolCallCount }) => {
  1076. const log = new EventLog();
  1077. const turnId = `turn-output-boundary-${stopReason}-${String(toolCallCount)}`;
  1078. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  1079. log.push(
  1080. SessionEventType.TurnStarted,
  1081. { turnNumber: 1, input: "执行工具", messageId: "user-output-tool-boundary" },
  1082. { turnId },
  1083. );
  1084. log.push(
  1085. SessionEventType.ModelStreaming,
  1086. {
  1087. kind: "text_start",
  1088. delta: "",
  1089. done: false,
  1090. assistantMessageId: "assistant-before-tool",
  1091. },
  1092. { turnId },
  1093. );
  1094. log.push(
  1095. SessionEventType.ModelStreaming,
  1096. { kind: "text_delta", delta: "先执行工具。", done: false },
  1097. { turnId },
  1098. );
  1099. log.push(
  1100. SessionEventType.ModelStreaming,
  1101. { kind: "text_end", delta: "", done: false },
  1102. { turnId },
  1103. );
  1104. log.push(
  1105. SessionEventType.ModelComplete,
  1106. {
  1107. content: "先执行工具。",
  1108. stopReason,
  1109. querySource: "main_turn",
  1110. ...(toolCallCount === undefined ? {} : { toolCallCount }),
  1111. usage: {},
  1112. },
  1113. { turnId },
  1114. );
  1115. log.push(
  1116. SessionEventType.ModelStreaming,
  1117. {
  1118. kind: "text_start",
  1119. delta: "",
  1120. done: false,
  1121. assistantMessageId: "assistant-after-tool",
  1122. },
  1123. { turnId },
  1124. );
  1125. const { projection } = runAll(log.events);
  1126. expect(
  1127. projection.getSnapshot().rows.window.filter((row) => row.kind === "assistantText"),
  1128. ).toHaveLength(2);
  1129. });
  1130. it("A:完整成功 turn —— rows 结构、phase、usage、schema 合法", () => {
  1131. const log = new EventLog();
  1132. basicTurnEvents(log);
  1133. const { projection } = runAll(log.events);
  1134. const snapshot = projection.getSnapshot();
  1135. // schema 合法性(M1 数据模型被 reducer 锤炼的第一道闸)。
  1136. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  1137. const kinds = snapshot.rows.window.map((row) => row.kind);
  1138. expect(kinds).toEqual(["turnHeader", "userInput", "assistantText"]);
  1139. const [header, userInput, assistant] = snapshot.rows.window;
  1140. expect(header).toMatchObject({
  1141. kind: "turnHeader",
  1142. origin: "userInput",
  1143. state: "completedSuccess",
  1144. activeMs: 5000,
  1145. });
  1146. expect(userInput).toMatchObject({
  1147. kind: "userInput",
  1148. text: "写一个 hello world",
  1149. origin: "realUser",
  1150. });
  1151. expect(assistant).toMatchObject({
  1152. kind: "assistantText",
  1153. text: "Hello world",
  1154. state: "complete",
  1155. });
  1156. expect(snapshot.control.phase).toBe("completedSuccess");
  1157. expect(snapshot.control.sessionEnded).toBe(true);
  1158. expect(snapshot.control.canStop).toBe(false);
  1159. expect(snapshot.inputRouting.mode).toBe("startNow");
  1160. expect(snapshot.usage.contextWindow).toEqual({
  1161. usedTokens: 150,
  1162. maxTokens: 200_000,
  1163. autoCompactThresholdTokens: null,
  1164. });
  1165. expect(snapshot.usage.cumulative.inputTokens).toBe(120);
  1166. expect(snapshot.seq).toBe(log.events.length);
  1167. });
  1168. it("A:主轮次 usage 保留 cache 命中率和 context breakdown", () => {
  1169. const log = new EventLog();
  1170. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  1171. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  1172. log.push(
  1173. SessionEventType.ModelComplete,
  1174. {
  1175. content: "done",
  1176. stopReason: "end_turn",
  1177. querySource: "main_turn",
  1178. contextWindow: 200_000,
  1179. usage: {
  1180. inputTokens: 100,
  1181. outputTokens: 20,
  1182. cacheReadTokens: 80,
  1183. cacheWriteTokens: 10,
  1184. },
  1185. cacheHit: {
  1186. inputTokens: 100,
  1187. cacheReadTokens: 80,
  1188. cacheWriteTokens: 10,
  1189. latestHitRate: 0.8,
  1190. hitRate: 0.8,
  1191. hitRateRequestCount: 1,
  1192. totalInputTokens: 100,
  1193. totalCacheReadTokens: 80,
  1194. totalCacheWriteTokens: 10,
  1195. },
  1196. contextUsageBreakdown: [
  1197. { source: "messages", chars: 900 },
  1198. { source: "system_tool_schemas", chars: 100 },
  1199. ],
  1200. },
  1201. { turnId: "turn-1" },
  1202. );
  1203. const { projection } = runAll(log.events);
  1204. const contextWindow = projection.getSnapshot().usage.contextWindow;
  1205. expect(contextWindow?.usedTokens).toBe(120);
  1206. expect(contextWindow?.maxTokens).toBe(200_000);
  1207. expect(contextWindow?.cache).toMatchObject({ hitRate: 0.8, totalCacheReadTokens: 80 });
  1208. expect(contextWindow?.breakdown).toEqual([
  1209. { source: "messages", chars: 900 },
  1210. { source: "system_tool_schemas", chars: 100 },
  1211. ]);
  1212. });
  1213. it("A:sidecar usage 不覆盖输入栏 context cache 和 breakdown", () => {
  1214. const log = new EventLog();
  1215. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  1216. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  1217. log.push(
  1218. SessionEventType.ModelComplete,
  1219. {
  1220. content: "title",
  1221. stopReason: "end_turn",
  1222. querySource: "session_title",
  1223. contextWindow: 200_000,
  1224. usage: {
  1225. inputTokens: 100,
  1226. outputTokens: 20,
  1227. cacheReadTokens: 80,
  1228. cacheWriteTokens: 10,
  1229. },
  1230. cacheHit: {
  1231. inputTokens: 100,
  1232. cacheReadTokens: 80,
  1233. cacheWriteTokens: 10,
  1234. latestHitRate: 0.8,
  1235. hitRate: 0.8,
  1236. hitRateRequestCount: 1,
  1237. totalInputTokens: 100,
  1238. totalCacheReadTokens: 80,
  1239. totalCacheWriteTokens: 10,
  1240. },
  1241. contextUsageBreakdown: [{ source: "messages", chars: 900 }],
  1242. },
  1243. { turnId: "turn-1" },
  1244. );
  1245. const { projection } = runAll(log.events);
  1246. expect(projection.getSnapshot().usage.contextWindow).toBeNull();
  1247. });
  1248. it("A:running 期 inputRouting=enqueue,完成后 startNow", () => {
  1249. const log = new EventLog();
  1250. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1251. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  1252. const { projection } = runAll(log.events);
  1253. expect(projection.getSnapshot().inputRouting.mode).toBe("enqueue");
  1254. // 回归原因:busy 期间 compact 已改为进入 typed FIFO,旧黄金断言仍按直接执行
  1255. // 门禁判为不可用;这里同时补齐标题承诺的完成态路由收口。
  1256. expect(projection.getSnapshot().availability.compact.allowed).toBe(true);
  1257. projection.applyEvent(
  1258. log.push(
  1259. SessionEventType.TurnComplete,
  1260. {
  1261. response: "done",
  1262. tokenCount: 1,
  1263. toolCallCount: 0,
  1264. duration: 100,
  1265. resultType: "success",
  1266. },
  1267. { turnId: "turn-1" },
  1268. ),
  1269. );
  1270. expect(projection.getSnapshot().inputRouting.mode).toBe("startNow");
  1271. });
  1272. it("A:model-only 输入(goal continuation 等)不产生 userInput row", () => {
  1273. const log = new EventLog();
  1274. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1275. log.push(
  1276. SessionEventType.TurnStarted,
  1277. {
  1278. turnNumber: 1,
  1279. input: "continue the goal",
  1280. inputSource: "goal-continuation",
  1281. inputVisibility: "model-only",
  1282. },
  1283. { turnId: "turn-1" },
  1284. );
  1285. const { projection } = runAll(log.events);
  1286. const kinds = projection.getSnapshot().rows.window.map((row) => row.kind);
  1287. expect(kinds).toEqual(["turnHeader"]);
  1288. expect(projection.getSnapshot().rows.window[0]).toMatchObject({
  1289. origin: "goalContinuation",
  1290. });
  1291. });
  1292. it("BG27/BG28:background model-only turn 把结构化标题投影到 turnHeader", () => {
  1293. const log = new EventLog();
  1294. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1295. log.push(
  1296. SessionEventType.TurnStarted,
  1297. {
  1298. turnNumber: 1,
  1299. input: "background result",
  1300. inputSource: "background_task",
  1301. inputVisibility: "model-only",
  1302. originMeta: {
  1303. backgroundSource: "subagent",
  1304. title: "Review the projection chain",
  1305. workId: "agent-review",
  1306. },
  1307. } as never,
  1308. { turnId: "turn-background" },
  1309. );
  1310. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  1311. expect(rows).toHaveLength(1);
  1312. expect(rows[0]).toMatchObject({
  1313. kind: "turnHeader",
  1314. origin: "backgroundResult",
  1315. originMeta: {
  1316. backgroundSource: "subagent",
  1317. title: "Review the projection chain",
  1318. workId: "agent-review",
  1319. },
  1320. });
  1321. });
  1322. it("workflow 终态通知:manifest 载荷随 originMeta 投影到 turnHeader(BG27 姊妹)", () => {
  1323. const log = new EventLog();
  1324. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1325. const workflowNotification = {
  1326. kind: "terminal" as const,
  1327. status: "completed" as const,
  1328. summary: "nightly audit",
  1329. result: "final artifact",
  1330. resultForm: "prose" as const,
  1331. reports: { count: 2, shown: 1, preview: ["第一步"] },
  1332. durationMs: 5_000,
  1333. };
  1334. log.push(
  1335. SessionEventType.TurnStarted,
  1336. {
  1337. turnNumber: 1,
  1338. input: "workflow result",
  1339. inputSource: "background_task",
  1340. inputVisibility: "model-only",
  1341. originMeta: {
  1342. backgroundSource: "workflow",
  1343. title: "nightly audit",
  1344. workId: "dwfrun-proj",
  1345. workflowNotification,
  1346. },
  1347. } as never,
  1348. { turnId: "turn-workflow" },
  1349. );
  1350. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  1351. expect(rows).toHaveLength(1);
  1352. // originMeta 被投影层整体拷贝——manifest 载荷免费搭车,不被逐字段重构剥掉。
  1353. expect(rows[0]).toMatchObject({
  1354. kind: "turnHeader",
  1355. origin: "backgroundResult",
  1356. originMeta: {
  1357. backgroundSource: "workflow",
  1358. title: "nightly audit",
  1359. workId: "dwfrun-proj",
  1360. workflowNotification,
  1361. },
  1362. });
  1363. });
  1364. it("BG26:background Agent 失败通知按 tool-use-id 覆盖 launch ACK 终态", () => {
  1365. const turnId = "turn-agent-launch";
  1366. const toolCallId = "tool-agent-rate-limit";
  1367. const error = "Requests are too frequent. Request id: bg26";
  1368. const result = `Agent general-purpose task \"分析世界杯\" failed. ${error}`;
  1369. const notification = [
  1370. "<task-notification>",
  1371. `<tool-use-id>${toolCallId}</tool-use-id>`,
  1372. "<status>failed</status>",
  1373. `<result>${result}</result>`,
  1374. `<error>${error}</error>`,
  1375. "</task-notification>",
  1376. ].join("\n");
  1377. const log = new EventLog();
  1378. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1379. log.push(
  1380. SessionEventType.TurnStarted,
  1381. { turnNumber: 1, input: "launch agent", messageId: "user-agent-launch" },
  1382. { turnId },
  1383. );
  1384. log.push(
  1385. SessionEventType.ToolCallScheduled,
  1386. {
  1387. toolCallId,
  1388. toolName: "Agent",
  1389. input: {
  1390. description: "分析世界杯",
  1391. run_in_background: true,
  1392. subagent_type: "general-purpose",
  1393. },
  1394. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1395. },
  1396. { turnId },
  1397. );
  1398. log.push(
  1399. SessionEventType.ToolCallStarted,
  1400. { toolCallId, toolName: "Agent", startedAt: new Date(1_700_000_003_000) },
  1401. { turnId },
  1402. );
  1403. log.push(
  1404. SessionEventType.ToolCallResult,
  1405. {
  1406. toolCallId,
  1407. result: { success: true, content: "Async agent launched successfully." },
  1408. duration: 1,
  1409. },
  1410. { turnId },
  1411. );
  1412. log.push(
  1413. SessionEventType.TurnComplete,
  1414. { response: "", tokenCount: 0, toolCallCount: 1, duration: 1, resultType: "success" },
  1415. { turnId },
  1416. );
  1417. log.push(
  1418. SessionEventType.TurnStarted,
  1419. {
  1420. turnNumber: 2,
  1421. input: notification,
  1422. inputSource: "background_task",
  1423. inputVisibility: "model-only",
  1424. messageId: "user-agent-notification",
  1425. },
  1426. { turnId: "turn-agent-notification" },
  1427. );
  1428. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  1429. expect(rows.filter((row) => row.kind === "userInput")).toHaveLength(1);
  1430. expect(
  1431. rows.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  1432. ).toMatchObject({
  1433. error: {
  1434. code: "fault.runtime.backgroundTaskFailed",
  1435. message: error,
  1436. },
  1437. output: { text: result },
  1438. status: "error",
  1439. });
  1440. });
  1441. it("BG26:不带 <error> 的失败通知按 originMeta.subagentResult 取失败原因,不解析 summary", () => {
  1442. const turnId = "turn-agent-launch";
  1443. const toolCallId = "tool-agent-rate-limit";
  1444. const error = "Requests are too frequent. Request id: bg26";
  1445. // 失败通知不带 <error>;失败原文由 originMeta.subagentResult 结构化下发,
  1446. // hover 只显示 provider 原文。
  1447. const summary = `Agent "分析世界杯" failed: ${error}`;
  1448. const notification = [
  1449. "<task-notification>",
  1450. `<tool-use-id>${toolCallId}</tool-use-id>`,
  1451. "<status>failed</status>",
  1452. `<summary>${summary}</summary>`,
  1453. "</task-notification>",
  1454. ].join("\n");
  1455. const toolRowFor = (originMeta?: Record<string, unknown>) => {
  1456. const log = new EventLog();
  1457. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1458. log.push(
  1459. SessionEventType.TurnStarted,
  1460. { turnNumber: 1, input: "launch agent", messageId: "user-agent-launch" },
  1461. { turnId },
  1462. );
  1463. log.push(
  1464. SessionEventType.ToolCallScheduled,
  1465. {
  1466. toolCallId,
  1467. toolName: "Agent",
  1468. input: {
  1469. description: "分析世界杯",
  1470. run_in_background: true,
  1471. subagent_type: "general-purpose",
  1472. },
  1473. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1474. },
  1475. { turnId },
  1476. );
  1477. log.push(
  1478. SessionEventType.ToolCallStarted,
  1479. { toolCallId, toolName: "Agent", startedAt: new Date(1_700_000_003_000) },
  1480. { turnId },
  1481. );
  1482. log.push(
  1483. SessionEventType.ToolCallResult,
  1484. {
  1485. toolCallId,
  1486. result: { success: true, content: "Async agent launched successfully." },
  1487. duration: 1,
  1488. },
  1489. { turnId },
  1490. );
  1491. log.push(
  1492. SessionEventType.TurnComplete,
  1493. { response: "", tokenCount: 0, toolCallCount: 1, duration: 1, resultType: "success" },
  1494. { turnId },
  1495. );
  1496. log.push(
  1497. SessionEventType.TurnStarted,
  1498. {
  1499. turnNumber: 2,
  1500. input: notification,
  1501. inputSource: "background_task",
  1502. inputVisibility: "model-only",
  1503. messageId: "user-agent-notification",
  1504. ...(originMeta ? { originMeta } : {}),
  1505. },
  1506. { turnId: "turn-agent-notification" },
  1507. );
  1508. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  1509. expect(rows.filter((row) => row.kind === "userInput")).toHaveLength(1);
  1510. return rows.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId);
  1511. };
  1512. expect(
  1513. toolRowFor({
  1514. backgroundSource: "subagent",
  1515. workId: "agent-bg26",
  1516. title: "分析世界杯",
  1517. subagentResult: { status: "failed", error },
  1518. }),
  1519. ).toMatchObject({
  1520. error: { code: "fault.runtime.backgroundTaskFailed", message: error },
  1521. output: { text: summary },
  1522. status: "error",
  1523. });
  1524. // 产品数据不依赖模型可见文案:没有结构化结果(合并轮)时不从 summary 猜原因,
  1525. // 失败详情退回整句 summary。
  1526. expect(toolRowFor()).toMatchObject({
  1527. error: { code: "fault.runtime.backgroundTaskFailed", message: summary },
  1528. status: "error",
  1529. });
  1530. });
  1531. it("BG26:合并通知按块投影,失败任务不读下一条通知的结果", () => {
  1532. const turnId = "turn-agent-launch";
  1533. const failedSummary = 'Agent "A" failed: Permission denied';
  1534. const partialFailedSummary = 'Agent "C" failed: Requests are too frequent.';
  1535. const notification = (toolCallId: string, lines: string[]) =>
  1536. [
  1537. "<task-notification>",
  1538. `<tool-use-id>${toolCallId}</tool-use-id>`,
  1539. ...lines,
  1540. "</task-notification>",
  1541. ].join("\n");
  1542. const log = new EventLog();
  1543. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1544. log.push(
  1545. SessionEventType.TurnStarted,
  1546. { turnNumber: 1, input: "launch agents", messageId: "user-agent-launch" },
  1547. { turnId },
  1548. );
  1549. for (const toolCallId of ["tool-agent-a", "tool-agent-b", "tool-agent-c"]) {
  1550. log.push(
  1551. SessionEventType.ToolCallScheduled,
  1552. {
  1553. toolCallId,
  1554. toolName: "Agent",
  1555. input: {
  1556. description: toolCallId,
  1557. run_in_background: true,
  1558. subagent_type: "general-purpose",
  1559. },
  1560. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1561. },
  1562. { turnId },
  1563. );
  1564. log.push(
  1565. SessionEventType.ToolCallResult,
  1566. {
  1567. toolCallId,
  1568. result: { success: true, content: "Async agent launched successfully." },
  1569. duration: 1,
  1570. },
  1571. { turnId },
  1572. );
  1573. }
  1574. log.push(
  1575. SessionEventType.TurnComplete,
  1576. { response: "", tokenCount: 0, toolCallCount: 3, duration: 1, resultType: "success" },
  1577. { turnId },
  1578. );
  1579. // 合并轮的 originMeta 只有基字段,没有逐任务的结构化结果。
  1580. log.push(
  1581. SessionEventType.TurnStarted,
  1582. {
  1583. turnNumber: 2,
  1584. input: [
  1585. notification("tool-agent-a", [
  1586. "<status>failed</status>",
  1587. `<summary>${failedSummary}</summary>`,
  1588. ]),
  1589. notification("tool-agent-b", [
  1590. "<status>completed</status>",
  1591. '<summary>Agent "B" finished</summary>',
  1592. "<result>Tests passed</result>",
  1593. ]),
  1594. // local agent 失败通知带 <note>,<result> 是只给模型的部分报告。
  1595. notification("tool-agent-c", [
  1596. "<status>failed</status>",
  1597. `<summary>${partialFailedSummary}</summary>`,
  1598. "<note>A task-notification fires each time this agent stops.</note>",
  1599. "<result>Interim findings: module A.</result>",
  1600. ]),
  1601. ].join("\n\n"),
  1602. inputSource: "background_task",
  1603. inputVisibility: "model-only",
  1604. messageId: "user-agent-notification",
  1605. originMeta: { backgroundSource: "subagent", workId: "agent-a", title: "A · B" },
  1606. },
  1607. { turnId: "turn-agent-notification" },
  1608. );
  1609. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  1610. const toolRow = (toolCallId: string) =>
  1611. rows.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId);
  1612. expect(toolRow("tool-agent-a")).toMatchObject({
  1613. error: { code: "fault.runtime.backgroundTaskFailed", message: failedSummary },
  1614. output: { text: failedSummary },
  1615. status: "error",
  1616. });
  1617. expect(toolRow("tool-agent-b")).toMatchObject({
  1618. output: { text: "Tests passed" },
  1619. status: "success",
  1620. });
  1621. // 回归:失败原因不能退到部分报告,卡片 output 与 hover 仍是这条通知自己的 summary。
  1622. expect(toolRow("tool-agent-c")).toMatchObject({
  1623. error: { code: "fault.runtime.backgroundTaskFailed", message: partialFailedSummary },
  1624. output: { text: partialFailedSummary },
  1625. status: "error",
  1626. });
  1627. });
  1628. // ── B 组:stop / 迟到终态 ──
  1629. it("B:cancelled turn —— streaming 行收口为 interrupted,phase=completedInterrupted", () => {
  1630. const log = new EventLog();
  1631. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1632. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  1633. log.push(
  1634. SessionEventType.ModelStreaming,
  1635. { kind: "text_start", delta: "", done: false },
  1636. { turnId: "turn-1" },
  1637. );
  1638. log.push(
  1639. SessionEventType.ModelStreaming,
  1640. { kind: "text_delta", delta: "partial", done: false },
  1641. { turnId: "turn-1" },
  1642. );
  1643. log.push(
  1644. SessionEventType.TurnComplete,
  1645. { response: "", tokenCount: 0, toolCallCount: 0, duration: 1000, resultType: "cancelled" },
  1646. { turnId: "turn-1" },
  1647. );
  1648. const { projection } = runAll(log.events);
  1649. const snapshot = projection.getSnapshot();
  1650. expect(snapshot.control.phase).toBe("completedInterrupted");
  1651. const assistant = snapshot.rows.window.find((row) => row.kind === "assistantText");
  1652. expect(assistant).toMatchObject({ text: "partial", state: "interrupted" });
  1653. const header = snapshot.rows.window.find((row) => row.kind === "turnHeader");
  1654. expect(header).toMatchObject({ state: "completedInterrupted" });
  1655. });
  1656. it("B/结构性2:stop 后迟到的流式/工具终态被拒收,投影逐字节不变", () => {
  1657. const log = new EventLog();
  1658. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1659. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  1660. log.push(
  1661. SessionEventType.TurnComplete,
  1662. { response: "", tokenCount: 0, toolCallCount: 0, duration: 100, resultType: "cancelled" },
  1663. { turnId: "turn-1" },
  1664. );
  1665. const { projection } = runAll(log.events);
  1666. const before = structuredClone(projection.getSnapshot());
  1667. const late = new EventLog();
  1668. late.push(
  1669. SessionEventType.ModelStreaming,
  1670. { kind: "text_delta", delta: "ghost", done: false },
  1671. { turnId: "turn-1" },
  1672. );
  1673. late.push(
  1674. SessionEventType.ToolCallResult,
  1675. { toolCallId: "tc-1", result: { success: true, content: "ghost" }, duration: 1 },
  1676. { turnId: "turn-1" },
  1677. );
  1678. for (const event of late.events) {
  1679. expect(projection.applyEvent(event)).toEqual([]);
  1680. }
  1681. expect({ ...projection.getSnapshot(), seq: before.seq }).toEqual(before);
  1682. });
  1683. // ── O/Q 组:tool call 状态机与权限交互 ──
  1684. it("CUA:PID 工具按事件顺序固化最近一次成功 list_apps 快照", () => {
  1685. const turnId = "turn-cua-app-snapshot";
  1686. const log = new EventLog();
  1687. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1688. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "操作应用" }, { turnId });
  1689. const listApps = (id: string, name: string, success = true) => {
  1690. log.push(
  1691. SessionEventType.ToolCallScheduled,
  1692. {
  1693. toolCallId: id,
  1694. toolName: "mcp__computer-use__list_apps",
  1695. input: {},
  1696. schedule: { parallelGroups: [[id]], executionOrder: [id] },
  1697. },
  1698. { turnId },
  1699. );
  1700. log.push(
  1701. SessionEventType.ToolCallResult,
  1702. {
  1703. toolCallId: id,
  1704. result: {
  1705. success,
  1706. content: success
  1707. ? JSON.stringify([{ pid: 42, name, bundle_id: `com.example.${name}` }])
  1708. : "failed",
  1709. ...(!success ? { error: { type: "toolFailed", message: "failed" } } : {}),
  1710. },
  1711. duration: 1,
  1712. },
  1713. { turnId },
  1714. );
  1715. };
  1716. const scheduleKey = (
  1717. id: string,
  1718. toolName = "mcp__computer-use__key",
  1719. appRef: unknown = { pid: 42 },
  1720. ) =>
  1721. log.push(
  1722. SessionEventType.ToolCallScheduled,
  1723. {
  1724. toolCallId: id,
  1725. toolName,
  1726. input: { app_ref: appRef, key: "TAB" },
  1727. schedule: { parallelGroups: [[id]], executionOrder: [id] },
  1728. },
  1729. { turnId },
  1730. );
  1731. listApps("list-1", "One");
  1732. scheduleKey("key-1");
  1733. listApps("list-failed", "Ignored", false);
  1734. scheduleKey("key-after-failure");
  1735. listApps("list-2", "Two");
  1736. scheduleKey("key-2");
  1737. scheduleKey("bundle-only", "mcp__computer-use__get_app_state", {
  1738. bundle_id: "com.example.Two",
  1739. });
  1740. scheduleKey("serialized-pid", "mcp__computer-use__get_app_state", '{"pid":42}');
  1741. scheduleKey("lookalike", "mcp__other__computer-use__key");
  1742. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  1743. const appOf = (id: string) => {
  1744. const row = rows.find(
  1745. (candidate) => candidate.kind === "toolCall" && candidate.toolCallId === id,
  1746. );
  1747. return row?.kind === "toolCall" ? row.cuaApp : undefined;
  1748. };
  1749. expect(appOf("key-1")).toEqual({ pid: 42, name: "One", bundleId: "com.example.One" });
  1750. expect(appOf("key-after-failure")).toEqual({
  1751. pid: 42,
  1752. name: "One",
  1753. bundleId: "com.example.One",
  1754. });
  1755. expect(appOf("key-2")).toEqual({ pid: 42, name: "Two", bundleId: "com.example.Two" });
  1756. expect(appOf("bundle-only")).toEqual({
  1757. pid: 42,
  1758. name: "Two",
  1759. bundleId: "com.example.Two",
  1760. });
  1761. expect(appOf("serialized-pid")).toEqual({
  1762. pid: 42,
  1763. name: "Two",
  1764. bundleId: "com.example.Two",
  1765. });
  1766. expect(appOf("lookalike")).toBeUndefined();
  1767. });
  1768. it("CUA:原子实时投影提交后保留 list_apps 快照", () => {
  1769. const turnId = "turn-cua-atomic-snapshot";
  1770. const log = new EventLog();
  1771. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1772. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "操作飞书" }, { turnId });
  1773. log.push(
  1774. SessionEventType.ToolCallScheduled,
  1775. {
  1776. toolCallId: "list-apps",
  1777. toolName: "mcp__computer-use__list_apps",
  1778. input: {},
  1779. schedule: { parallelGroups: [["list-apps"]], executionOrder: ["list-apps"] },
  1780. },
  1781. { turnId },
  1782. );
  1783. log.push(
  1784. SessionEventType.ToolCallResult,
  1785. {
  1786. toolCallId: "list-apps",
  1787. result: {
  1788. success: true,
  1789. content: JSON.stringify([{ pid: 691, name: "Feishu", bundle_id: "com.electron.lark" }]),
  1790. },
  1791. duration: 1,
  1792. },
  1793. { turnId },
  1794. );
  1795. log.push(
  1796. SessionEventType.ToolCallScheduled,
  1797. {
  1798. toolCallId: "get-app-state",
  1799. toolName: "mcp__computer-use__get_app_state",
  1800. input: { app_ref: '{"pid":691}', title: "查看飞书当前界面" },
  1801. schedule: {
  1802. parallelGroups: [["get-app-state"]],
  1803. executionOrder: ["get-app-state"],
  1804. },
  1805. },
  1806. { turnId },
  1807. );
  1808. const projection = new ProductProjection("session-1", "epoch-1");
  1809. for (const event of log.events) {
  1810. expect(projection.applyEventAtomically(event, () => true)).not.toBeNull();
  1811. }
  1812. const row = projection
  1813. .getSnapshot()
  1814. .rows.window.find(
  1815. (candidate) => candidate.kind === "toolCall" && candidate.toolCallId === "get-app-state",
  1816. );
  1817. expect(row?.kind === "toolCall" ? row.cuaApp : undefined).toEqual({
  1818. pid: 691,
  1819. name: "Feishu",
  1820. bundleId: "com.electron.lark",
  1821. });
  1822. });
  1823. it("BTA01:保留 turn-end Node REPL 图片 display 到 live tool row", () => {
  1824. const turnId = "turn-browser-shot";
  1825. const toolCallId = "tool-browser-shot";
  1826. const log = new EventLog();
  1827. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1828. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "打开页面" }, { turnId });
  1829. log.push(
  1830. SessionEventType.ToolCallScheduled,
  1831. {
  1832. toolCallId,
  1833. toolName: "mcp__node_repl__js",
  1834. input: { source: "browser_turn_end" },
  1835. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1836. },
  1837. { turnId },
  1838. );
  1839. log.push(
  1840. SessionEventType.ToolCallResult,
  1841. {
  1842. toolCallId,
  1843. result: {
  1844. success: true,
  1845. content: "",
  1846. display: {
  1847. kind: "node_repl_images",
  1848. source: "browser_turn_end",
  1849. images: [{ base64: "AAAA", mimeType: "image/png" }],
  1850. },
  1851. },
  1852. duration: 0,
  1853. },
  1854. { turnId },
  1855. );
  1856. const snapshot = runAll(log.events).projection.getSnapshot();
  1857. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  1858. expect(
  1859. snapshot.rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  1860. ).toMatchObject({
  1861. status: "success",
  1862. display: { kind: "node_repl_images", source: "browser_turn_end" },
  1863. });
  1864. });
  1865. it("CUA:保留实时工具结果的截图 display 到 output", () => {
  1866. const turnId = "turn-cua-screenshot";
  1867. const toolCallId = "tool-cua-screenshot";
  1868. const log = new EventLog();
  1869. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1870. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "截图" }, { turnId });
  1871. log.push(
  1872. SessionEventType.ToolCallScheduled,
  1873. {
  1874. toolCallId,
  1875. toolName: "mcp__computer-use__computer-use",
  1876. input: { action: "screenshot" },
  1877. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1878. },
  1879. { turnId },
  1880. );
  1881. log.push(
  1882. SessionEventType.ToolCallResult,
  1883. {
  1884. toolCallId,
  1885. result: {
  1886. success: true,
  1887. content: "[Attached image/jpeg: MCP image]",
  1888. display: {
  1889. kind: "cua",
  1890. schemaVersion: 1,
  1891. toolName: "computer-use",
  1892. status: "success",
  1893. input: '{"action":"screenshot"}',
  1894. media: [{ mimeType: "image/jpeg", data: "AAAA" }],
  1895. },
  1896. },
  1897. duration: 10,
  1898. },
  1899. { turnId },
  1900. );
  1901. expect(
  1902. runAll(log.events)
  1903. .projection.getSnapshot()
  1904. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  1905. ).toMatchObject({
  1906. status: "success",
  1907. output: {
  1908. text: "[Attached image/jpeg: MCP image]",
  1909. display: {
  1910. kind: "cua",
  1911. media: [{ mimeType: "image/jpeg", data: "AAAA" }],
  1912. },
  1913. },
  1914. });
  1915. });
  1916. it.each([
  1917. {
  1918. toolName: "TaskOutput",
  1919. display: {
  1920. kind: "task_output",
  1921. retrievalStatus: "not_ready",
  1922. taskStatus: "running",
  1923. output: "partial output",
  1924. } as const,
  1925. },
  1926. {
  1927. toolName: "RespondToCoordinator",
  1928. display: {
  1929. kind: "respond_to_coordinator",
  1930. status: "success",
  1931. } as const,
  1932. },
  1933. {
  1934. toolName: "CreateWorkflow",
  1935. display: {
  1936. kind: "create_workflow",
  1937. ok: true,
  1938. errorCount: 0,
  1939. diagnostics: [],
  1940. causalityGraph: {
  1941. steps: [
  1942. {
  1943. id: "ask#1",
  1944. kind: "ask",
  1945. label: "scout",
  1946. line: 3,
  1947. column: 20,
  1948. lane: "actor#1",
  1949. },
  1950. ],
  1951. lanes: [{ id: "actor#1", name: "scout", line: 3, column: 11 }],
  1952. // 第二层是子代理导向:每阶段一张参与者卡 + 交接边(docs/dynamic-workflow/presentation.md)。
  1953. participants: [
  1954. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] },
  1955. ],
  1956. handoffs: [],
  1957. sink: ["ask#1"],
  1958. },
  1959. } as const,
  1960. },
  1961. // 观察类工作流工具的五个 display kind(spec:docs/dynamic-workflow/launch.md「Run introspection tools」
  1962. // 「工具卡 display」、同文件「The model catalog」)——whitelist 不放行就整块被剥,UI 只能退回文本投影。
  1963. {
  1964. toolName: "GetWorkflowRun",
  1965. display: {
  1966. kind: "get_workflow_run",
  1967. runId: "wf_demo",
  1968. label: "demo",
  1969. status: "running",
  1970. usage: {
  1971. spentTokens: 1_000,
  1972. nodesObserved: 3,
  1973. nodesRunning: 1,
  1974. nodesCompleted: 2,
  1975. nodesFailed: 0,
  1976. },
  1977. actors: [{ siteId: "agent#1", ordinal: 1, name: "scout" }],
  1978. logTail: [{ sequence: 1, message: "started" }],
  1979. } as const,
  1980. },
  1981. {
  1982. toolName: "ListWorkflowRuns",
  1983. display: {
  1984. kind: "list_workflow_runs",
  1985. runs: [
  1986. {
  1987. runId: "wf_demo",
  1988. label: "demo",
  1989. labelSource: "name",
  1990. status: "completed",
  1991. ownedByThisSession: true,
  1992. createdAt: 1,
  1993. updatedAt: 2,
  1994. spentTokens: 42,
  1995. },
  1996. ],
  1997. } as const,
  1998. },
  1999. {
  2000. toolName: "EvalWorkflowSnippet",
  2001. display: {
  2002. kind: "eval_workflow_snippet",
  2003. ok: true,
  2004. diagnostics: [],
  2005. logs: ["glob matched 3 files"],
  2006. response: "3",
  2007. durationMs: 120,
  2008. } as const,
  2009. },
  2010. {
  2011. toolName: "ResumeWorkflowRun",
  2012. display: {
  2013. kind: "resume_workflow_run",
  2014. runId: "wf_demo",
  2015. } as const,
  2016. },
  2017. // 模型目录卡(spec:docs/dynamic-workflow/launch.md「The model catalog」):白名单漏了它,
  2018. // UI 只能退回那段以 providerId 开头的 `<models>` 文本。
  2019. {
  2020. toolName: "ListModels",
  2021. display: {
  2022. kind: "list_models",
  2023. current: "account:bigmodel-team-coding-plan/GLM-5.3-Flash",
  2024. models: [
  2025. {
  2026. id: "account:bigmodel-team-coding-plan/GLM-5.3-Flash",
  2027. providerId: "account:bigmodel-team-coding-plan",
  2028. modelId: "GLM-5.3-Flash",
  2029. providerLabel: "BigModel",
  2030. reasoningLevels: ["low", "medium", "high"],
  2031. defaultReasoningLevel: "high",
  2032. contextWindow: 128_000,
  2033. },
  2034. ],
  2035. } as const,
  2036. },
  2037. {
  2038. toolName: "ListSavedWorkflows",
  2039. display: {
  2040. kind: "saved_workflow_list",
  2041. workflows: [
  2042. {
  2043. name: "nightly-sync",
  2044. scope: "project",
  2045. path: ".zcode/workflows/nightly-sync.dwf.ts",
  2046. argNames: ["question"],
  2047. },
  2048. ],
  2049. } as const,
  2050. },
  2051. ])("保留 $toolName display 到 live tool row", ({ toolName, display }) => {
  2052. const turnId = `turn-${toolName}`;
  2053. const toolCallId = `tool-${toolName}`;
  2054. const log = new EventLog();
  2055. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2056. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run tool" }, { turnId });
  2057. log.push(
  2058. SessionEventType.ToolCallScheduled,
  2059. {
  2060. toolCallId,
  2061. toolName,
  2062. input: {},
  2063. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  2064. },
  2065. { turnId },
  2066. );
  2067. log.push(
  2068. SessionEventType.ToolCallResult,
  2069. {
  2070. toolCallId,
  2071. result: {
  2072. success: true,
  2073. content: "provider content remains independent",
  2074. display,
  2075. },
  2076. duration: 0,
  2077. },
  2078. { turnId },
  2079. );
  2080. expect(
  2081. runAll(log.events)
  2082. .projection.getSnapshot()
  2083. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  2084. ).toMatchObject({
  2085. status: "success",
  2086. display,
  2087. output: { text: "provider content remains independent" },
  2088. });
  2089. });
  2090. it("不把未声明支持的 display kind 顺带开放到 V4 row", () => {
  2091. const turnId = "turn-file-diff-display";
  2092. const toolCallId = "tool-file-diff-display";
  2093. const log = new EventLog();
  2094. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2095. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "edit file" }, { turnId });
  2096. log.push(
  2097. SessionEventType.ToolCallScheduled,
  2098. {
  2099. toolCallId,
  2100. toolName: "Edit",
  2101. input: {},
  2102. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  2103. },
  2104. { turnId },
  2105. );
  2106. log.push(
  2107. SessionEventType.ToolCallResult,
  2108. {
  2109. toolCallId,
  2110. result: {
  2111. success: true,
  2112. content: "updated",
  2113. display: {
  2114. kind: "file_diff",
  2115. filePath: "/workspace/app.ts",
  2116. additions: 1,
  2117. deletions: 0,
  2118. structuredPatch: [],
  2119. truncated: false,
  2120. },
  2121. },
  2122. duration: 0,
  2123. },
  2124. { turnId },
  2125. );
  2126. const row = runAll(log.events)
  2127. .projection.getSnapshot()
  2128. .rows.window.find((candidate) => candidate.kind === "toolCall");
  2129. expect(row).not.toHaveProperty("display");
  2130. });
  2131. it("不把 mirrored RespondToCoordinator 物化到父会话", () => {
  2132. const turnId = "turn-mirrored-response";
  2133. const toolCallId = "tool_subagent_agent-1_response";
  2134. const mirrored = {
  2135. agentId: "agent-1",
  2136. agentType: "general-purpose",
  2137. childSessionId: "session-child-1",
  2138. childToolCallId: "response",
  2139. parentToolCallId: "parent-agent-call",
  2140. source: "subagent",
  2141. };
  2142. const log = new EventLog();
  2143. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2144. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run child" }, { turnId });
  2145. log.push(
  2146. SessionEventType.ToolCallScheduled,
  2147. {
  2148. ...mirrored,
  2149. toolCallId,
  2150. toolName: "RespondToCoordinator",
  2151. input: { summary: "reply", message: "details" },
  2152. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  2153. },
  2154. { turnId },
  2155. );
  2156. log.push(
  2157. SessionEventType.ToolCallResult,
  2158. {
  2159. ...mirrored,
  2160. toolCallId,
  2161. result: {
  2162. success: true,
  2163. content: "Response response-1 was queued for the coordinator.",
  2164. display: { kind: "respond_to_coordinator", status: "success" },
  2165. },
  2166. duration: 0,
  2167. },
  2168. { turnId },
  2169. );
  2170. expect(
  2171. runAll(log.events)
  2172. .projection.getSnapshot()
  2173. .rows.window.filter((row) => row.kind === "toolCall"),
  2174. ).toEqual([]);
  2175. });
  2176. it("MCP discovery 展示元数据进入 live tool row,不依赖合成工具名解析", () => {
  2177. const turnId = "turn-mcp-presentation";
  2178. const toolCallId = "tool-mcp-presentation";
  2179. const log = new EventLog();
  2180. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2181. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "查询 issue" }, { turnId });
  2182. log.push(
  2183. SessionEventType.ToolCallScheduled,
  2184. {
  2185. toolCallId,
  2186. toolName: "custom-provider-visible-name",
  2187. input: { query: "is:open" },
  2188. display: {
  2189. kind: "mcp_tool",
  2190. serverName: "company-github-prod",
  2191. toolName: "issue_query_v2",
  2192. description: "Query issues visible to the current user.",
  2193. },
  2194. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  2195. },
  2196. { turnId },
  2197. );
  2198. const pendingRow = runAll(log.events.slice(0, 3))
  2199. .projection.getSnapshot()
  2200. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId);
  2201. expect(pendingRow).toMatchObject({
  2202. status: "inputStreaming",
  2203. display: { kind: "mcp_tool", toolName: "issue_query_v2" },
  2204. });
  2205. log.push(
  2206. SessionEventType.ToolCallResult,
  2207. {
  2208. toolCallId,
  2209. result: {
  2210. success: true,
  2211. content: "12 issues",
  2212. display: {
  2213. kind: "mcp_tool",
  2214. serverName: "company-github-prod",
  2215. toolName: "issue_query_v2",
  2216. description: "Query issues visible to the current user.",
  2217. },
  2218. },
  2219. duration: 12,
  2220. },
  2221. { turnId },
  2222. );
  2223. expect(
  2224. runAll(log.events)
  2225. .projection.getSnapshot()
  2226. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  2227. ).toMatchObject({
  2228. toolName: "custom-provider-visible-name",
  2229. status: "success",
  2230. display: {
  2231. kind: "mcp_tool",
  2232. serverName: "company-github-prod",
  2233. toolName: "issue_query_v2",
  2234. },
  2235. });
  2236. });
  2237. it("MCP display 在 running、failed 与 stopped 生命周期更新中保持不变", () => {
  2238. const display = {
  2239. kind: "mcp_tool" as const,
  2240. serverName: "firebase",
  2241. toolName: "get_environment",
  2242. };
  2243. const createLog = () => {
  2244. const log = new EventLog();
  2245. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2246. log.push(
  2247. SessionEventType.TurnStarted,
  2248. { turnNumber: 1, input: "inspect" },
  2249. { turnId: "turn-mcp-lifecycle" },
  2250. );
  2251. log.push(
  2252. SessionEventType.ToolCallScheduled,
  2253. {
  2254. toolCallId: "mcp-lifecycle",
  2255. toolName: "opaque-name",
  2256. input: {},
  2257. display,
  2258. schedule: { parallelGroups: [["mcp-lifecycle"]], executionOrder: ["mcp-lifecycle"] },
  2259. },
  2260. { turnId: "turn-mcp-lifecycle" },
  2261. );
  2262. log.push(
  2263. SessionEventType.ToolCallStarted,
  2264. { toolCallId: "mcp-lifecycle", toolName: "opaque-name", startedAt: new Date() },
  2265. { turnId: "turn-mcp-lifecycle" },
  2266. );
  2267. return log;
  2268. };
  2269. const failedLog = createLog();
  2270. failedLog.push(
  2271. SessionEventType.ToolCallError,
  2272. { toolCallId: "mcp-lifecycle", error: { type: "tool_failed", message: "boom" } },
  2273. { turnId: "turn-mcp-lifecycle" },
  2274. );
  2275. const failedRow = runAll(failedLog.events).projection.getSnapshot().rows.window.at(-1);
  2276. expect(failedRow).toMatchObject({ status: "error", display });
  2277. const stoppedLog = createLog();
  2278. stoppedLog.push(
  2279. SessionEventType.TurnComplete,
  2280. { response: "", tokenCount: 0, toolCallCount: 1, duration: 1, resultType: "cancelled" },
  2281. { turnId: "turn-mcp-lifecycle" },
  2282. );
  2283. const stoppedRow = runAll(stoppedLog.events).projection.getSnapshot().rows.window.at(-1);
  2284. expect(stoppedRow).toMatchObject({ status: "cancelled", display });
  2285. });
  2286. it("工具主动取消错误直接投影为 cancelled,不等待 turn complete 纠正", () => {
  2287. const turnId = "turn-tool-cancelled";
  2288. const log = new EventLog();
  2289. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2290. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run long bash" }, { turnId });
  2291. log.push(
  2292. SessionEventType.ToolCallScheduled,
  2293. {
  2294. toolCallId: "bash-cancelled",
  2295. toolName: "Bash",
  2296. input: { command: "sleep 60" },
  2297. schedule: { parallelGroups: [["bash-cancelled"]], executionOrder: ["bash-cancelled"] },
  2298. },
  2299. { turnId },
  2300. );
  2301. log.push(
  2302. SessionEventType.ToolCallStarted,
  2303. { toolCallId: "bash-cancelled", toolName: "Bash", startedAt: new Date() },
  2304. { turnId },
  2305. );
  2306. log.push(
  2307. SessionEventType.ToolCallError,
  2308. {
  2309. toolCallId: "bash-cancelled",
  2310. error: {
  2311. code: "TOOL_CANCELLED",
  2312. type: "tool_cancelled",
  2313. message: "Bash was cancelled and the child process was asked to stop",
  2314. },
  2315. },
  2316. { turnId },
  2317. );
  2318. const row = runAll(log.events).projection.getSnapshot().rows.window.at(-1);
  2319. expect(row).toMatchObject({ kind: "toolCall", status: "cancelled" });
  2320. });
  2321. it("O/Q:tool 输入流式 → 权限等待 → 放行执行 → 成功终态", () => {
  2322. const turnId = "turn-1";
  2323. const log = new EventLog();
  2324. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2325. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run ls" }, { turnId });
  2326. log.push(
  2327. SessionEventType.ModelStreaming,
  2328. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-1", toolName: "bash" },
  2329. { turnId },
  2330. );
  2331. log.push(
  2332. SessionEventType.ModelStreaming,
  2333. { kind: "tool_input_delta", delta: '{"command":"ls"}', done: false, toolCallId: "tc-1" },
  2334. { turnId },
  2335. );
  2336. log.push(
  2337. SessionEventType.ToolCallScheduled,
  2338. {
  2339. toolCallId: "tc-1",
  2340. toolName: "bash",
  2341. input: { command: "ls" },
  2342. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  2343. },
  2344. { turnId },
  2345. );
  2346. log.push(
  2347. SessionEventType.PermissionRequested,
  2348. {
  2349. requestId: "req-1",
  2350. toolCallId: "tc-1",
  2351. toolName: "bash",
  2352. riskLevel: "medium",
  2353. reason: "Run shell command",
  2354. input: { command: "ls" },
  2355. suggestedPermissionUpdates: [
  2356. {
  2357. behavior: "allow",
  2358. rules: [{ ruleContent: "pnpm run lint:*", toolName: "Bash" }],
  2359. type: "addRules",
  2360. },
  2361. ],
  2362. },
  2363. { turnId },
  2364. );
  2365. const { projection } = runAll(log.events);
  2366. const pending = projection.getSnapshot();
  2367. const toolRow = pending.rows.window.find((row) => row.kind === "toolCall");
  2368. expect(toolRow).toMatchObject({
  2369. status: "pendingApproval",
  2370. inputText: '{"command":"ls"}',
  2371. approvalInteractionId: "req-1",
  2372. });
  2373. expect(pending.pendingInteractions).toHaveLength(1);
  2374. expect(pending.pendingInteractions[0]).toMatchObject({
  2375. kind: "permission",
  2376. anchorRowId: toolRow?.rowId,
  2377. });
  2378. expect(pending.pendingInteractions[0]?.payload).toMatchObject({
  2379. freeText: true,
  2380. options: [
  2381. { optionId: "allowOnce", response: { decision: "allow" } },
  2382. {
  2383. optionId: "allowAlways",
  2384. response: {
  2385. decision: "allow",
  2386. permissionUpdates: [
  2387. {
  2388. behavior: "allow",
  2389. rules: [{ ruleContent: "pnpm run lint:*", toolName: "Bash" }],
  2390. type: "addRules",
  2391. },
  2392. ],
  2393. },
  2394. },
  2395. { optionId: "deny", response: { decision: "deny" } },
  2396. ],
  2397. });
  2398. const resume = new EventLog();
  2399. // EventLog seq 从 1 重新计数不影响断言主体(seq 水位单独断言于 A 组)。
  2400. resume.push(
  2401. SessionEventType.PermissionResolved,
  2402. { requestId: "req-1", toolCallId: "tc-1", decision: "allow" },
  2403. { turnId },
  2404. );
  2405. resume.push(
  2406. SessionEventType.ToolCallStarted,
  2407. { toolCallId: "tc-1", toolName: "bash", startedAt: new Date() },
  2408. { turnId },
  2409. );
  2410. resume.push(
  2411. SessionEventType.ToolCallResult,
  2412. { toolCallId: "tc-1", result: { success: true, content: "file-a\nfile-b" }, duration: 42 },
  2413. { turnId },
  2414. );
  2415. for (const event of resume.events) projection.applyEvent(event);
  2416. const done = projection.getSnapshot();
  2417. expect(done.pendingInteractions).toHaveLength(0);
  2418. const doneRow = done.rows.window.find((row) => row.kind === "toolCall");
  2419. expect(doneRow).toMatchObject({
  2420. status: "success",
  2421. output: { text: "file-a\nfile-b" },
  2422. });
  2423. expect(
  2424. doneRow && "approvalInteractionId" in doneRow && doneRow.approvalInteractionId,
  2425. ).toBeFalsy();
  2426. });
  2427. it.each([
  2428. { label: "空字符串", streamName: "" },
  2429. { label: "纯空白", streamName: " \t " },
  2430. ])("O/ETN:$label 工具名只参与恢复,不物化可见工具行", ({ streamName }) => {
  2431. const turnId = "turn-empty-tool-name";
  2432. const toolCallId = "call-empty-tool-name";
  2433. const log = new EventLog();
  2434. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2435. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "continue" }, { turnId });
  2436. log.push(
  2437. SessionEventType.ModelStreaming,
  2438. {
  2439. kind: "tool_input_start",
  2440. delta: "",
  2441. done: false,
  2442. toolCallId,
  2443. toolName: streamName,
  2444. },
  2445. { turnId },
  2446. );
  2447. log.push(
  2448. SessionEventType.ModelStreaming,
  2449. {
  2450. kind: "tool_input_delta",
  2451. delta: '{"value":1}',
  2452. done: false,
  2453. toolCallId,
  2454. },
  2455. { turnId },
  2456. );
  2457. log.push(
  2458. SessionEventType.ModelStreaming,
  2459. {
  2460. kind: "tool_call",
  2461. delta: "",
  2462. done: true,
  2463. input: { value: 1 },
  2464. toolCallId,
  2465. toolName: streamName,
  2466. },
  2467. { turnId },
  2468. );
  2469. log.push(
  2470. SessionEventType.ToolCallError,
  2471. {
  2472. toolCallId,
  2473. error: {
  2474. type: "fault.runtime.toolFailed",
  2475. message: "Model returned an invalid tool call: tool name is empty.",
  2476. },
  2477. },
  2478. { turnId },
  2479. );
  2480. log.push(
  2481. SessionEventType.ModelStreaming,
  2482. { kind: "text_start", delta: "", done: false },
  2483. { turnId },
  2484. );
  2485. log.push(
  2486. SessionEventType.ModelStreaming,
  2487. { kind: "text_delta", delta: "continued", done: false },
  2488. { turnId },
  2489. );
  2490. log.push(
  2491. SessionEventType.ModelStreaming,
  2492. { kind: "text_end", delta: "", done: false },
  2493. { turnId },
  2494. );
  2495. log.push(
  2496. SessionEventType.TurnComplete,
  2497. {
  2498. response: "continued",
  2499. tokenCount: 1,
  2500. toolCallCount: 1,
  2501. duration: 10,
  2502. resultType: "success",
  2503. },
  2504. { turnId },
  2505. );
  2506. const { deltasPerEvent, projection, snapshots } = runAll(log.events);
  2507. expect(projection.getSnapshot().rows.window.filter((row) => row.kind === "toolCall")).toEqual(
  2508. [],
  2509. );
  2510. expect(
  2511. projection.getSnapshot().rows.window.find((row) => row.kind === "assistantText"),
  2512. ).toMatchObject({ text: "continued", state: "complete" });
  2513. expect(
  2514. deltasPerEvent
  2515. .flat()
  2516. .some(
  2517. (delta) =>
  2518. (delta.op === "row.appended" || delta.op === "row.upserted") &&
  2519. delta.row.kind === "toolCall",
  2520. ),
  2521. ).toBe(false);
  2522. const direct = applyConversationDeltas(snapshots[0]!, deltasPerEvent.flat());
  2523. for (const profile of [DELIVERY_PROFILES.continuous, DELIVERY_PROFILES.replayable]) {
  2524. const delivered = coalesceConversationDeltas(
  2525. filterConversationDeltasForProfile(deltasPerEvent.flat(), profile),
  2526. );
  2527. expect(applyConversationDeltas(snapshots[0]!, delivered)).toEqual(direct);
  2528. }
  2529. });
  2530. it("O/ETN:合法 empty_tool_name 工具保留 live 与 replayable 可见生命周期", () => {
  2531. const turnId = "turn-legitimate-empty-tool-name";
  2532. const toolCallId = "call-legitimate-empty-tool-name";
  2533. const log = new EventLog();
  2534. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2535. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run tool" }, { turnId });
  2536. log.push(
  2537. SessionEventType.ModelStreaming,
  2538. {
  2539. kind: "tool_input_start",
  2540. delta: "",
  2541. done: false,
  2542. toolCallId,
  2543. toolName: "empty_tool_name",
  2544. },
  2545. { turnId },
  2546. );
  2547. log.push(
  2548. SessionEventType.ModelStreaming,
  2549. {
  2550. kind: "tool_input_delta",
  2551. delta: '{"value":1}',
  2552. done: false,
  2553. toolCallId,
  2554. },
  2555. { turnId },
  2556. );
  2557. log.push(
  2558. SessionEventType.ModelStreaming,
  2559. {
  2560. kind: "tool_call",
  2561. delta: "",
  2562. done: true,
  2563. input: { value: 1 },
  2564. toolCallId,
  2565. toolName: "empty_tool_name",
  2566. },
  2567. { turnId },
  2568. );
  2569. log.push(
  2570. SessionEventType.ToolCallScheduled,
  2571. {
  2572. toolCallId,
  2573. toolName: "empty_tool_name",
  2574. input: { value: 1 },
  2575. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  2576. },
  2577. { turnId },
  2578. );
  2579. log.push(
  2580. SessionEventType.ToolCallResult,
  2581. {
  2582. toolCallId,
  2583. result: { success: true, content: "ok" },
  2584. duration: 1,
  2585. },
  2586. { turnId },
  2587. );
  2588. const { deltasPerEvent, projection, snapshots } = runAll(log.events);
  2589. expect(
  2590. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  2591. ).toMatchObject({
  2592. input: { value: 1 },
  2593. status: "success",
  2594. toolCallId,
  2595. toolName: "empty_tool_name",
  2596. });
  2597. const direct = applyConversationDeltas(snapshots[0]!, deltasPerEvent.flat());
  2598. for (const profile of [DELIVERY_PROFILES.continuous, DELIVERY_PROFILES.replayable]) {
  2599. const delivered = coalesceConversationDeltas(
  2600. filterConversationDeltasForProfile(deltasPerEvent.flat(), profile),
  2601. );
  2602. expect(applyConversationDeltas(snapshots[0]!, delivered)).toEqual(direct);
  2603. }
  2604. });
  2605. it("O/ETN:普通非空 unknown tool 仍保留 terminal error 工具行", () => {
  2606. const turnId = "turn-unknown-tool";
  2607. const toolCallId = "call-unknown-tool";
  2608. const log = new EventLog();
  2609. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2610. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "continue" }, { turnId });
  2611. log.push(
  2612. SessionEventType.ToolCallScheduled,
  2613. {
  2614. toolCallId,
  2615. toolName: "DefinitelyMissingTool",
  2616. input: {},
  2617. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  2618. },
  2619. { turnId },
  2620. );
  2621. log.push(
  2622. SessionEventType.ToolCallError,
  2623. {
  2624. toolCallId,
  2625. error: { type: "fault.runtime.toolNotFound", message: "Tool not found" },
  2626. },
  2627. { turnId },
  2628. );
  2629. expect(
  2630. runAll(log.events)
  2631. .projection.getSnapshot()
  2632. .rows.window.find((row) => row.kind === "toolCall"),
  2633. ).toMatchObject({
  2634. toolCallId,
  2635. toolName: "DefinitelyMissingTool",
  2636. status: "error",
  2637. });
  2638. });
  2639. it.each(["Write", "Edit"])(
  2640. "STIP06:%s 首包立即,后续 inputText 按事件时间戳每秒合并一次",
  2641. (toolName) => {
  2642. const turnId = "turn-file-tool";
  2643. const base = 1_700_000_010_000;
  2644. const log = new EventLog();
  2645. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2646. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "modify file" }, { turnId });
  2647. log.push(
  2648. SessionEventType.ModelStreaming,
  2649. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-file", toolName },
  2650. { timestampMs: base, turnId },
  2651. );
  2652. log.push(
  2653. SessionEventType.ModelStreaming,
  2654. {
  2655. kind: "tool_input_delta",
  2656. delta: '{"file_path":"src/app.ts",',
  2657. done: false,
  2658. toolCallId: "tc-file",
  2659. },
  2660. { timestampMs: base + 100, turnId },
  2661. );
  2662. log.push(
  2663. SessionEventType.ModelStreaming,
  2664. { kind: "tool_input_delta", delta: '"content":"a', done: false, toolCallId: "tc-file" },
  2665. { timestampMs: base + 400, turnId },
  2666. );
  2667. log.push(
  2668. SessionEventType.ModelStreaming,
  2669. { kind: "tool_input_delta", delta: 'b"}', done: false, toolCallId: "tc-file" },
  2670. { timestampMs: base + 1_100, turnId },
  2671. );
  2672. const { deltasPerEvent, projection } = runAll(log.events);
  2673. expect(inputTextAppends(deltasPerEvent[3] ?? [])).toEqual(['{"file_path":"src/app.ts",']);
  2674. expect(inputTextAppends(deltasPerEvent[4] ?? [])).toEqual([]);
  2675. expect(inputTextAppends(deltasPerEvent[5] ?? [])).toEqual(['"content":"ab"}']);
  2676. expect(
  2677. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  2678. ).toMatchObject({ inputText: '{"file_path":"src/app.ts","content":"ab"}' });
  2679. const estimateProjection = new ProductProjection("session-1", "epoch-1");
  2680. const appendEstimates = log.events.map((event) => {
  2681. const estimate = estimateProjection.establishedStreamingAppend(event);
  2682. estimateProjection.applyEvent(event);
  2683. return estimate;
  2684. });
  2685. expect(appendEstimates.slice(3)).toEqual([
  2686. '{"file_path":"src/app.ts",',
  2687. "",
  2688. '"content":"ab"}',
  2689. ]);
  2690. },
  2691. );
  2692. it("STIP07:Write input end 立即冲刷窗口内尚未发布的 suffix", () => {
  2693. const turnId = "turn-write-end";
  2694. const base = 1_700_000_020_000;
  2695. const log = new EventLog();
  2696. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2697. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "write" }, { turnId });
  2698. log.push(
  2699. SessionEventType.ModelStreaming,
  2700. {
  2701. kind: "tool_input_start",
  2702. delta: "",
  2703. done: false,
  2704. toolCallId: "tc-write",
  2705. toolName: "Write",
  2706. },
  2707. { timestampMs: base, turnId },
  2708. );
  2709. log.push(
  2710. SessionEventType.ModelStreaming,
  2711. { kind: "tool_input_delta", delta: '{"content":"a', done: false, toolCallId: "tc-write" },
  2712. { timestampMs: base + 100, turnId },
  2713. );
  2714. log.push(
  2715. SessionEventType.ModelStreaming,
  2716. { kind: "tool_input_delta", delta: 'b"}', done: false, toolCallId: "tc-write" },
  2717. { timestampMs: base + 200, turnId },
  2718. );
  2719. log.push(
  2720. SessionEventType.ModelStreaming,
  2721. { kind: "tool_input_end", delta: "", done: true, toolCallId: "tc-write" },
  2722. { timestampMs: base + 300, turnId },
  2723. );
  2724. const { deltasPerEvent, projection } = runAll(log.events);
  2725. expect(inputTextAppends(deltasPerEvent[4] ?? [])).toEqual([]);
  2726. expect(inputTextAppends(deltasPerEvent[5] ?? [])).toEqual(['b"}']);
  2727. expect(
  2728. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  2729. ).toMatchObject({ inputText: '{"content":"ab"}' });
  2730. });
  2731. it("STIP07:Write 被取消时把窗口内 suffix 收进 cancelled row", () => {
  2732. const turnId = "turn-write-cancel";
  2733. const base = 1_700_000_030_000;
  2734. const log = new EventLog();
  2735. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2736. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "write" }, { turnId });
  2737. log.push(
  2738. SessionEventType.ModelStreaming,
  2739. {
  2740. kind: "tool_input_start",
  2741. delta: "",
  2742. done: false,
  2743. toolCallId: "tc-write",
  2744. toolName: "Write",
  2745. },
  2746. { timestampMs: base, turnId },
  2747. );
  2748. log.push(
  2749. SessionEventType.ModelStreaming,
  2750. { kind: "tool_input_delta", delta: '{"content":"a', done: false, toolCallId: "tc-write" },
  2751. { timestampMs: base + 100, turnId },
  2752. );
  2753. log.push(
  2754. SessionEventType.ModelStreaming,
  2755. { kind: "tool_input_delta", delta: 'b"}', done: false, toolCallId: "tc-write" },
  2756. { timestampMs: base + 200, turnId },
  2757. );
  2758. log.push(
  2759. SessionEventType.TurnComplete,
  2760. { response: "", tokenCount: 0, toolCallCount: 0, duration: 300, resultType: "cancelled" },
  2761. { timestampMs: base + 300, turnId },
  2762. );
  2763. const { deltasPerEvent, projection } = runAll(log.events);
  2764. expect(inputTextAppends(deltasPerEvent[4] ?? [])).toEqual([]);
  2765. expect(
  2766. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  2767. ).toMatchObject({ status: "cancelled", inputText: '{"content":"ab"}' });
  2768. });
  2769. it("STIP08:非 Write/Edit 工具保留逐投影增量", () => {
  2770. const turnId = "turn-bash";
  2771. const base = 1_700_000_040_000;
  2772. const log = new EventLog();
  2773. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2774. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId });
  2775. log.push(
  2776. SessionEventType.ModelStreaming,
  2777. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-bash", toolName: "Bash" },
  2778. { timestampMs: base, turnId },
  2779. );
  2780. log.push(
  2781. SessionEventType.ModelStreaming,
  2782. { kind: "tool_input_delta", delta: '{"command":"p', done: false, toolCallId: "tc-bash" },
  2783. { timestampMs: base + 100, turnId },
  2784. );
  2785. log.push(
  2786. SessionEventType.ModelStreaming,
  2787. { kind: "tool_input_delta", delta: 'wd"}', done: false, toolCallId: "tc-bash" },
  2788. { timestampMs: base + 200, turnId },
  2789. );
  2790. const { deltasPerEvent } = runAll(log.events);
  2791. expect(inputTextAppends(deltasPerEvent[3] ?? [])).toEqual(['{"command":"p']);
  2792. expect(inputTextAppends(deltasPerEvent[4] ?? [])).toEqual(['wd"}']);
  2793. });
  2794. it("Q:AskUserQuestion 权限等待态 → structured userInput pendingInteraction", () => {
  2795. const turnId = "turn-ask";
  2796. const log = new EventLog();
  2797. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2798. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "帮我做个番茄钟" }, { turnId });
  2799. log.push(
  2800. SessionEventType.ToolCallScheduled,
  2801. {
  2802. toolCallId: "ask-1",
  2803. toolName: "AskUserQuestion",
  2804. input: {
  2805. questions: [
  2806. {
  2807. question: "你想把这个番茄时钟作为什么形式存在?",
  2808. header: "形式",
  2809. options: [
  2810. { label: "独立新页面", description: "新增页面", preview: "新增页面预览" },
  2811. { label: "独立小工具视图", description: "嵌入现有界面" },
  2812. ],
  2813. },
  2814. ],
  2815. },
  2816. schedule: { parallelGroups: [["ask-1"]], executionOrder: ["ask-1"] },
  2817. },
  2818. { turnId },
  2819. );
  2820. log.push(
  2821. SessionEventType.PermissionRequested,
  2822. {
  2823. requestId: "ask-request-1",
  2824. toolCallId: "ask-1",
  2825. toolName: "AskUserQuestion",
  2826. riskLevel: "low",
  2827. reason: "AskUserQuestion pauses execution to collect answers from the user",
  2828. origin: {
  2829. kind: "subagent",
  2830. agentId: "agent-ask",
  2831. agentType: "general-purpose",
  2832. childSessionId: "sess-child-ask",
  2833. description: "Ask from child",
  2834. parentSessionId: "session-1",
  2835. parentToolCallId: "call-parent-agent",
  2836. parentTurnId: turnId,
  2837. },
  2838. input: {
  2839. questions: [
  2840. {
  2841. question: "你想把这个番茄时钟作为什么形式存在?",
  2842. header: "形式",
  2843. options: [
  2844. { label: "独立新页面", description: "新增页面", preview: "新增页面预览" },
  2845. { label: "独立小工具视图", description: "嵌入现有界面" },
  2846. ],
  2847. },
  2848. ],
  2849. },
  2850. },
  2851. { turnId },
  2852. );
  2853. const { projection } = runAll(log.events);
  2854. const snapshot = projection.getSnapshot();
  2855. const toolRow = snapshot.rows.window.find((row) => row.kind === "toolCall");
  2856. expect(toolRow).toMatchObject({
  2857. status: "pendingApproval",
  2858. approvalInteractionId: "ask-request-1",
  2859. });
  2860. expect(snapshot.pendingInteractions).toHaveLength(1);
  2861. expect(snapshot.pendingInteractions[0]).toMatchObject({
  2862. interactionId: "ask-request-1",
  2863. kind: "userInput",
  2864. anchorRowId: toolRow?.rowId,
  2865. payload: {
  2866. kind: "userInput",
  2867. toolName: "AskUserQuestion",
  2868. toolCallId: "ask-1",
  2869. origin: {
  2870. kind: "subagent",
  2871. agentId: "agent-ask",
  2872. childSessionId: "sess-child-ask",
  2873. parentSessionId: "session-1",
  2874. parentToolCallId: "call-parent-agent",
  2875. },
  2876. prompt: "AskUserQuestion pauses execution to collect answers from the user",
  2877. freeText: true,
  2878. schema: { toolName: "AskUserQuestion" },
  2879. questions: [
  2880. {
  2881. question: "你想把这个番茄时钟作为什么形式存在?",
  2882. header: "形式",
  2883. options: [
  2884. {
  2885. value: "独立新页面",
  2886. label: "独立新页面",
  2887. description: "新增页面",
  2888. preview: "新增页面预览",
  2889. },
  2890. { value: "独立小工具视图", label: "独立小工具视图", description: "嵌入现有界面" },
  2891. ],
  2892. },
  2893. ],
  2894. },
  2895. });
  2896. const autoResolutionLog = new EventLog();
  2897. const hiddenGrace = {
  2898. state: "hiddenGrace" as const,
  2899. startedAt: 1_700_000_000_000,
  2900. visibleAt: 1_700_000_060_000,
  2901. deadlineAt: 1_700_000_300_000,
  2902. };
  2903. projection.applyEvent(
  2904. autoResolutionLog.push(
  2905. SessionEventType.UserInputAutoResolutionUpdated,
  2906. {
  2907. interactionId: "ask-request-1",
  2908. toolCallId: "ask-1",
  2909. autoResolution: hiddenGrace,
  2910. },
  2911. { turnId },
  2912. ),
  2913. );
  2914. expect(projection.getSnapshot().pendingInteractions[0]?.autoResolution).toEqual(hiddenGrace);
  2915. const visibleCountdown = { ...hiddenGrace, state: "visibleCountdown" as const };
  2916. projection.applyEvent(
  2917. autoResolutionLog.push(
  2918. SessionEventType.UserInputAutoResolutionUpdated,
  2919. {
  2920. interactionId: "ask-request-1",
  2921. toolCallId: "ask-1",
  2922. autoResolution: visibleCountdown,
  2923. },
  2924. { turnId },
  2925. ),
  2926. );
  2927. expect(projection.getSnapshot().pendingInteractions[0]?.autoResolution).toEqual(
  2928. visibleCountdown,
  2929. );
  2930. const snoozed = {
  2931. state: "snoozed" as const,
  2932. startedAt: hiddenGrace.startedAt,
  2933. snoozedAt: 1_700_000_299_000,
  2934. };
  2935. projection.applyEvent(
  2936. autoResolutionLog.push(
  2937. SessionEventType.UserInputAutoResolutionUpdated,
  2938. {
  2939. interactionId: "ask-request-1",
  2940. toolCallId: "ask-1",
  2941. autoResolution: snoozed,
  2942. },
  2943. { turnId },
  2944. ),
  2945. );
  2946. expect(projection.getSnapshot().pendingInteractions[0]?.autoResolution).toEqual(snoozed);
  2947. const resume = new EventLog();
  2948. projection.applyEvent(
  2949. resume.push(
  2950. SessionEventType.PermissionResolved,
  2951. { requestId: "ask-request-1", toolCallId: "ask-1", decision: "allow" },
  2952. { turnId },
  2953. ),
  2954. );
  2955. expect(projection.getSnapshot().pendingInteractions).toHaveLength(0);
  2956. });
  2957. it("Q:ExitPlanMode 权限等待态 → plan approval elicitation pendingInteraction", () => {
  2958. const turnId = "turn-plan";
  2959. const log = new EventLog();
  2960. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2961. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "进入计划模式" }, { turnId });
  2962. log.push(
  2963. SessionEventType.ToolCallScheduled,
  2964. {
  2965. toolCallId: "exit-plan-1",
  2966. toolName: "ExitPlanMode",
  2967. input: { plan: "1. 增加协议\n2. 补 UI" },
  2968. schedule: { parallelGroups: [["exit-plan-1"]], executionOrder: ["exit-plan-1"] },
  2969. },
  2970. { turnId },
  2971. );
  2972. log.push(
  2973. SessionEventType.PermissionRequested,
  2974. {
  2975. requestId: "plan-request-1",
  2976. toolCallId: "exit-plan-1",
  2977. toolName: "ExitPlanMode",
  2978. riskLevel: "low",
  2979. reason: "ExitPlanMode requires user approval before implementation",
  2980. input: { plan: "1. 增加协议\n2. 补 UI" },
  2981. },
  2982. { turnId },
  2983. );
  2984. const { projection } = runAll(log.events);
  2985. expect(projection.getSnapshot().pendingInteractions[0]).toMatchObject({
  2986. kind: "userInput",
  2987. payload: {
  2988. kind: "userInput",
  2989. toolName: "ExitPlanMode",
  2990. toolCallId: "exit-plan-1",
  2991. schema: { interaction: "plan_approval", toolName: "ExitPlanMode" },
  2992. questions: [
  2993. {
  2994. header: "Plan",
  2995. question: "ExitPlanMode requires user approval before implementation",
  2996. options: [
  2997. {
  2998. value: "approve",
  2999. label: "Approve",
  3000. description: "Exit plan mode and start implementation.",
  3001. },
  3002. ],
  3003. },
  3004. ],
  3005. },
  3006. });
  3007. });
  3008. it("Q:权限拒绝 → toolCall cancelled,交互清除", () => {
  3009. const turnId = "turn-1";
  3010. const log = new EventLog();
  3011. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3012. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "rm -rf" }, { turnId });
  3013. log.push(
  3014. SessionEventType.ToolCallScheduled,
  3015. {
  3016. toolCallId: "tc-1",
  3017. toolName: "bash",
  3018. input: { command: "rm -rf /" },
  3019. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  3020. },
  3021. { turnId },
  3022. );
  3023. log.push(
  3024. SessionEventType.PermissionRequested,
  3025. {
  3026. requestId: "req-1",
  3027. toolCallId: "tc-1",
  3028. toolName: "bash",
  3029. riskLevel: "high",
  3030. reason: "Destructive",
  3031. input: {},
  3032. },
  3033. { turnId },
  3034. );
  3035. log.push(
  3036. SessionEventType.PermissionResolved,
  3037. { requestId: "req-1", toolCallId: "tc-1", decision: "deny" },
  3038. { turnId },
  3039. );
  3040. const { projection } = runAll(log.events);
  3041. const snapshot = projection.getSnapshot();
  3042. expect(snapshot.pendingInteractions).toHaveLength(0);
  3043. expect(snapshot.rows.window.find((row) => row.kind === "toolCall")).toMatchObject({
  3044. status: "cancelled",
  3045. });
  3046. });
  3047. it("O:SubagentSpawned/Stopped → subagent row success 并保留 child session 下钻信息", () => {
  3048. const turnId = "turn-1";
  3049. const log = new EventLog();
  3050. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3051. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "派子代理" }, { turnId });
  3052. log.push(
  3053. SessionEventType.SubagentSpawned,
  3054. {
  3055. agentId: "agent-1",
  3056. agentType: "Explore",
  3057. childSessionId: "sess_child_1",
  3058. description: "探索项目结构",
  3059. parentToolCallId: "call-agent-1",
  3060. prompt: "请探索项目",
  3061. status: "running",
  3062. },
  3063. { turnId },
  3064. );
  3065. log.push(
  3066. SessionEventType.SubagentStopped,
  3067. {
  3068. agentId: "agent-1",
  3069. agentType: "Explore",
  3070. childSessionId: "sess_child_1",
  3071. status: "completed",
  3072. summaryText: "项目结构已经梳理完成",
  3073. },
  3074. { turnId },
  3075. );
  3076. const { projection } = runAll(log.events);
  3077. expect(
  3078. projection.getSnapshot().rows.window.find((row) => row.kind === "subagent"),
  3079. ).toMatchObject({
  3080. childSessionId: "sess_child_1",
  3081. parentToolCallId: "call-agent-1",
  3082. status: "success",
  3083. subagentType: "Explore",
  3084. summaryText: "项目结构已经梳理完成",
  3085. });
  3086. expect(projection.getSnapshot().subagents).toMatchObject({
  3087. childSessionIds: ["sess_child_1"],
  3088. running: [],
  3089. endedTotal: 1,
  3090. });
  3091. });
  3092. it("SAT12:SendMessage resumed spawn 在同一次投影中恢复原 row 和 cancellable work", () => {
  3093. const turnId = "turn-send-message-resume";
  3094. const log = new EventLog();
  3095. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3096. log.push(
  3097. SessionEventType.TurnStarted,
  3098. { turnNumber: 1, input: "先运行前台 Agent" },
  3099. { turnId },
  3100. );
  3101. log.push(
  3102. SessionEventType.SubagentSpawned,
  3103. {
  3104. agentId: "agent-resume",
  3105. agentType: "general-purpose",
  3106. childSessionId: "sess-child-resume",
  3107. description: "前台任务",
  3108. parentToolCallId: "call-agent",
  3109. status: "running",
  3110. },
  3111. { turnId },
  3112. );
  3113. log.push(
  3114. SessionEventType.SubagentStopped,
  3115. {
  3116. agentId: "agent-resume",
  3117. agentType: "general-purpose",
  3118. childSessionId: "sess-child-resume",
  3119. parentToolCallId: "call-agent",
  3120. status: "completed",
  3121. },
  3122. { turnId },
  3123. );
  3124. const projection = new ProductProjection("session-1", "epoch-1");
  3125. for (const item of log.events) projection.applyEvent(item);
  3126. const resumedEvent = log.push(
  3127. SessionEventType.SubagentSpawned,
  3128. {
  3129. agentId: "agent-resume",
  3130. agentType: "general-purpose",
  3131. background: true,
  3132. childSessionId: "sess-child-resume",
  3133. description: "恢复到后台",
  3134. parentToolCallId: "call-send-message",
  3135. resumed: true,
  3136. status: "running",
  3137. },
  3138. { turnId },
  3139. );
  3140. const deltas = projection.applyEvent(resumedEvent);
  3141. const snapshot = projection.getSnapshot();
  3142. expect(
  3143. snapshot.rows.window.filter(
  3144. (row) => row.kind === "subagent" && row.entityId === "agent-resume",
  3145. ),
  3146. ).toHaveLength(1);
  3147. expect(snapshot.rows.window.find((row) => row.kind === "subagent")).toMatchObject({
  3148. childSessionId: "sess-child-resume",
  3149. parentToolCallId: "call-agent",
  3150. status: "running",
  3151. });
  3152. expect(snapshot.backgroundWorks).toEqual([
  3153. expect.objectContaining({
  3154. workId: "agent-resume",
  3155. kind: "subagent",
  3156. childSessionId: "sess-child-resume",
  3157. cancellable: true,
  3158. status: "running",
  3159. title: "恢复到后台",
  3160. }),
  3161. ]);
  3162. expect(snapshot.subagents).toMatchObject({
  3163. childSessionIds: ["sess-child-resume"],
  3164. running: [expect.objectContaining({ childSessionId: "sess-child-resume" })],
  3165. endedTotal: 0,
  3166. });
  3167. expect(
  3168. deltas.some(
  3169. (delta) => delta.op === "state.updated" && delta.patch.backgroundWorks?.length === 1,
  3170. ),
  3171. ).toBe(true);
  3172. expect(
  3173. deltas.some(
  3174. (delta) => delta.op === "state.updated" && delta.patch.subagents?.running.length === 1,
  3175. ),
  3176. ).toBe(true);
  3177. projection.applyEvent(
  3178. log.push(
  3179. SessionEventType.BackgroundTaskCompleted,
  3180. {
  3181. taskId: "agent-resume",
  3182. toolName: "Agent",
  3183. taskKind: "subagent",
  3184. childSessionId: "sess-child-resume",
  3185. status: "cancelled",
  3186. cancellable: false,
  3187. },
  3188. { turnId },
  3189. ),
  3190. );
  3191. projection.applyEvent(
  3192. log.push(
  3193. SessionEventType.SubagentStopped,
  3194. {
  3195. agentId: "agent-resume",
  3196. agentType: "general-purpose",
  3197. background: true,
  3198. childSessionId: "sess-child-resume",
  3199. parentToolCallId: "call-send-message",
  3200. status: "cancelled",
  3201. },
  3202. { turnId },
  3203. ),
  3204. );
  3205. const terminalSnapshot = projection.getSnapshot();
  3206. expect(terminalSnapshot.rows.window.find((row) => row.kind === "subagent")).toMatchObject({
  3207. parentToolCallId: "call-agent",
  3208. status: "cancelled",
  3209. });
  3210. expect(terminalSnapshot.backgroundWorks).toEqual([
  3211. expect.objectContaining({ workId: "agent-resume", status: "cancelled" }),
  3212. ]);
  3213. });
  3214. it("SAT24:7 个毫秒级并行 spawn 在每次 row 提交中原子发布完整 running 投影", () => {
  3215. const turnId = "turn-parallel-subagents";
  3216. const log = new EventLog();
  3217. log.push(SessionEventType.SessionCreated, {
  3218. mode: "default",
  3219. contextWindow: 1000,
  3220. });
  3221. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "并行派生" }, { turnId });
  3222. for (let index = 1; index <= 7; index += 1) {
  3223. log.push(
  3224. SessionEventType.SubagentSpawned,
  3225. {
  3226. agentId: `agent-${index}`,
  3227. agentType: "Explore",
  3228. childSessionId: `sess_child_${index}`,
  3229. description: `并行子智能体 ${index}`,
  3230. parentToolCallId: `call-agent-${index}`,
  3231. status: "running",
  3232. },
  3233. { turnId, timestampMs: 1_700_000_000_000 + index },
  3234. );
  3235. }
  3236. const projection = new ProductProjection("session-1", "epoch-1");
  3237. for (const event of log.events) {
  3238. const deltas = projection.applyEvent(event);
  3239. if (event.type !== SessionEventType.SubagentSpawned) continue;
  3240. const expectedCount = Number((event.payload as { agentId: string }).agentId.split("-")[1]);
  3241. const subagentPatch = deltas.find(
  3242. (delta) => delta.op === "state.updated" && delta.patch.subagents,
  3243. );
  3244. expect(deltas.some((delta) => delta.op === "row.appended")).toBe(true);
  3245. expect(subagentPatch).toMatchObject({
  3246. op: "state.updated",
  3247. patch: {
  3248. subagents: {
  3249. childSessionIds: expect.arrayContaining([`sess_child_${expectedCount}`]),
  3250. endedTotal: 0,
  3251. },
  3252. },
  3253. });
  3254. expect(projection.getSnapshot().subagents?.running).toHaveLength(expectedCount);
  3255. }
  3256. expect(projection.getSnapshot().subagents).toMatchObject({
  3257. childSessionIds: Array.from({ length: 7 }, (_, index) => `sess_child_${index + 1}`),
  3258. endedTotal: 0,
  3259. });
  3260. });
  3261. it("SAT22:cold seed 持续排除未持久化 ghost,直到新的合法 spawn", () => {
  3262. const turnId = "turn-cold-subagent-seed";
  3263. const log = new EventLog();
  3264. log.push(SessionEventType.SessionCreated, {
  3265. mode: "default",
  3266. contextWindow: 1000,
  3267. });
  3268. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "历史派生" }, { turnId });
  3269. log.push(
  3270. SessionEventType.SubagentSpawned,
  3271. {
  3272. agentId: "agent-reliable",
  3273. agentType: "Explore",
  3274. childSessionId: "sess-reliable",
  3275. description: "可靠 child",
  3276. status: "running",
  3277. },
  3278. { turnId },
  3279. );
  3280. log.push(
  3281. SessionEventType.SubagentSpawned,
  3282. {
  3283. agentId: "agent-ghost",
  3284. agentType: "Explore",
  3285. childSessionId: "sess-ghost",
  3286. description: "旧版本 ghost",
  3287. status: "running",
  3288. },
  3289. { turnId },
  3290. );
  3291. const projection = new ProductProjection("session-1", "epoch-1");
  3292. for (const event of log.events) projection.applyEvent(event);
  3293. projection.seedSubagents({
  3294. revision: 10,
  3295. childSessionIds: ["sess-reliable"],
  3296. running: [
  3297. {
  3298. agentId: "agent-reliable",
  3299. childSessionId: "sess-reliable",
  3300. status: "running",
  3301. subagentType: "Explore",
  3302. title: "可靠 child",
  3303. },
  3304. ],
  3305. });
  3306. expect(projection.getSnapshot().subagents).toMatchObject({
  3307. revision: 10,
  3308. childSessionIds: ["sess-reliable"],
  3309. running: [{ childSessionId: "sess-reliable" }],
  3310. endedTotal: 0,
  3311. });
  3312. projection.applyEvent(
  3313. log.push(SessionEventType.ModelSelected, {
  3314. modelSelection: {
  3315. providerId: "test-provider",
  3316. modelId: "test-model",
  3317. },
  3318. }),
  3319. );
  3320. expect(projection.getSnapshot().subagents?.childSessionIds).toEqual(["sess-reliable"]);
  3321. projection.applyEvent(
  3322. log.push(
  3323. SessionEventType.SubagentSpawned,
  3324. {
  3325. agentId: "agent-ghost",
  3326. agentType: "Explore",
  3327. childSessionId: "sess-ghost",
  3328. description: "已持久化后恢复",
  3329. resumed: true,
  3330. status: "running",
  3331. },
  3332. { turnId },
  3333. ),
  3334. );
  3335. expect(projection.getSnapshot().subagents?.childSessionIds).toEqual([
  3336. "sess-reliable",
  3337. "sess-ghost",
  3338. ]);
  3339. expect(projection.getSnapshot().subagents?.running).toHaveLength(2);
  3340. });
  3341. it("SAT22:非空 cold manifest 即使旧查询 revision 为 0 也会建立有效版本", () => {
  3342. const projection = new ProductProjection("session-1", "epoch-1");
  3343. projection.seedSubagents({
  3344. revision: 0,
  3345. childSessionIds: ["sess-reliable"],
  3346. running: [],
  3347. });
  3348. expect(projection.getSnapshot().subagents).toMatchObject({
  3349. revision: 1,
  3350. childSessionIds: ["sess-reliable"],
  3351. endedTotal: 1,
  3352. });
  3353. });
  3354. // ── M 组:turn steer 队列 ──
  3355. it("M:steer 入队/注入 —— queue.items 生命周期", () => {
  3356. const turnId = "turn-1";
  3357. const log = new EventLog();
  3358. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3359. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  3360. log.push(
  3361. SessionEventType.TurnSteerQueued,
  3362. {
  3363. pendingInputId: "pi-1",
  3364. inputId: "command-original",
  3365. input: "顺便加个测试",
  3366. inputPreview: "顺便加个测试",
  3367. inputSize: 6,
  3368. targetTurnId: turnId,
  3369. queueLength: 1,
  3370. delivery: "guide",
  3371. intent: {
  3372. sourceCommandId: "command-original",
  3373. queueItemId: "pi-1",
  3374. clientId: "mobile-client",
  3375. kind: "sendText",
  3376. admissionSeq: 12,
  3377. admittedAt: 1234,
  3378. requestedDelivery: "guide",
  3379. admittedDelivery: "guide",
  3380. highspeed: {
  3381. schemaVersion: 1,
  3382. cardId: "hsc-queue",
  3383. taskId: "session-1",
  3384. provider: "builtin:bigmodel-coding-plan",
  3385. model: "GLM-5.3",
  3386. issuedAt: 1_700_000_000_000,
  3387. expiresAt: 1_700_000_900_000,
  3388. },
  3389. attachmentRefs: [
  3390. { ref: "artifact://one", fileName: "one.txt", mime: "text/plain", bytes: 3 },
  3391. ],
  3392. },
  3393. },
  3394. { turnId },
  3395. );
  3396. const { projection } = runAll(log.events);
  3397. expect(projection.getSnapshot().queue.items).toHaveLength(1);
  3398. expect(projection.getSnapshot().queue.items[0]).toMatchObject({
  3399. queueItemId: "pi-1",
  3400. kind: "sendText",
  3401. text: "顺便加个测试",
  3402. sourceCommandId: "command-original",
  3403. clientId: "mobile-client",
  3404. attachments: [{ ref: "artifact://one", fileName: "one.txt", mime: "text/plain", bytes: 3 }],
  3405. delivery: { requested: "guide", admitted: "guide" },
  3406. order: { admissionSeq: 12, queuePosition: 0 },
  3407. steer: { state: "steering" },
  3408. dispatch: { state: "queued" },
  3409. highspeed: { cardId: "hsc-queue", expiresAt: 1_700_000_900_000 },
  3410. admittedAt: 1234,
  3411. });
  3412. const drain = new EventLog();
  3413. drain.push(
  3414. SessionEventType.TurnSteerDrained,
  3415. {
  3416. pendingInputIds: ["pi-1"],
  3417. targetTurnId: turnId,
  3418. injectedMessageIds: ["message-drained"],
  3419. drainedInputs: [
  3420. {
  3421. pendingInputId: "pi-1",
  3422. messageId: "message-drained",
  3423. text: "顺便加个测试",
  3424. delivery: "guide",
  3425. intent: {
  3426. sourceCommandId: "command-original",
  3427. queueItemId: "pi-1",
  3428. clientId: "mobile-client",
  3429. kind: "sendText",
  3430. admissionSeq: 12,
  3431. admittedAt: 1234,
  3432. requestedDelivery: "guide",
  3433. admittedDelivery: "guide",
  3434. attachmentRefs: [
  3435. {
  3436. ref: "artifact://one",
  3437. fileName: "one.txt",
  3438. mime: "text/plain",
  3439. bytes: 3,
  3440. },
  3441. ],
  3442. },
  3443. },
  3444. ],
  3445. },
  3446. { turnId },
  3447. );
  3448. for (const event of drain.events) projection.applyEvent(event);
  3449. expect(projection.getSnapshot().queue.items).toHaveLength(0);
  3450. expect(projection.getSnapshot().rows.window.at(-1)).toMatchObject({
  3451. kind: "userInput",
  3452. text: "顺便加个测试",
  3453. guided: true,
  3454. sourceCommandId: "command-original",
  3455. clientId: "mobile-client",
  3456. attachments: [{ ref: "artifact://one", fileName: "one.txt", mime: "text/plain", bytes: 3 }],
  3457. });
  3458. });
  3459. it("M:goal command 入队 —— queue item 保留 sendGoalCommand kind", () => {
  3460. const turnId = "turn-1";
  3461. const log = new EventLog();
  3462. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3463. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  3464. log.push(
  3465. SessionEventType.TurnSteerQueued,
  3466. {
  3467. pendingInputId: "pi-goal",
  3468. commandKind: "sendGoalCommand",
  3469. input: "/goal 新目标",
  3470. inputPreview: "/goal 新目标",
  3471. inputSize: 12,
  3472. targetTurnId: turnId,
  3473. queueLength: 1,
  3474. },
  3475. { turnId },
  3476. );
  3477. const { projection } = runAll(log.events);
  3478. expect(projection.getSnapshot().queue.items[0]).toMatchObject({
  3479. queueItemId: "pi-goal",
  3480. kind: "sendGoalCommand",
  3481. text: "/goal 新目标",
  3482. });
  3483. });
  3484. it("M:guide/附件 fallback 保留 requested/admitted 与 reasonCode", () => {
  3485. const log = new EventLog();
  3486. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3487. log.push(
  3488. SessionEventType.TurnSteerQueued,
  3489. {
  3490. pendingInputId: "queue-fallback",
  3491. inputId: "command-fallback",
  3492. input: "带附件",
  3493. inputPreview: "带附件",
  3494. inputSize: 9,
  3495. delivery: "queue",
  3496. targetTurnId: "turn-1",
  3497. queueLength: 1,
  3498. intent: {
  3499. sourceCommandId: "command-fallback",
  3500. queueItemId: "queue-fallback",
  3501. clientId: "desktop-client",
  3502. kind: "sendText",
  3503. admissionSeq: 2,
  3504. admittedAt: 50,
  3505. requestedDelivery: "guide",
  3506. admittedDelivery: "queue",
  3507. fallbackReasonCode: "guide.attachmentsUnsupported",
  3508. attachmentRefs: [
  3509. { ref: "artifact://a", fileName: "a.txt", mime: "text/plain", bytes: 1 },
  3510. ],
  3511. },
  3512. },
  3513. { turnId: "turn-1" },
  3514. );
  3515. const { projection } = runAll(log.events);
  3516. expect(projection.getSnapshot().queue.items[0]).toMatchObject({
  3517. sourceCommandId: "command-fallback",
  3518. attachments: [{ ref: "artifact://a" }],
  3519. delivery: {
  3520. requested: "guide",
  3521. admitted: "queue",
  3522. fallbackReasonCode: "guide.attachmentsUnsupported",
  3523. },
  3524. steer: { state: "fellBack", reasonCode: "guide.attachmentsUnsupported" },
  3525. });
  3526. });
  3527. it("M:text-only terminal 以 delivery changed 原地把 guide 改投 queue", () => {
  3528. const log = new EventLog();
  3529. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3530. log.push(
  3531. SessionEventType.TurnSteerQueued,
  3532. {
  3533. pendingInputId: "queue-guide-terminal",
  3534. input: "等下一个工具边界",
  3535. inputPreview: "等下一个工具边界",
  3536. inputSize: 9,
  3537. delivery: "guide",
  3538. targetTurnId: "turn-1",
  3539. queueLength: 1,
  3540. intent: {
  3541. sourceCommandId: "command-guide-terminal",
  3542. queueItemId: "queue-guide-terminal",
  3543. clientId: "desktop-client",
  3544. kind: "sendText",
  3545. admissionSeq: 3,
  3546. admittedAt: 60,
  3547. requestedDelivery: "guide",
  3548. admittedDelivery: "guide",
  3549. },
  3550. },
  3551. { turnId: "turn-1" },
  3552. );
  3553. log.push(
  3554. SessionEventType.TurnSteerDeliveryChanged,
  3555. {
  3556. pendingInputId: "queue-guide-terminal",
  3557. targetTurnId: "turn-1",
  3558. requestedDelivery: "guide",
  3559. admittedDelivery: "queue",
  3560. fallbackReasonCode: "guide.noToolBoundary",
  3561. },
  3562. { turnId: "turn-1" },
  3563. );
  3564. const { projection } = runAll(log.events);
  3565. expect(projection.getSnapshot().queue.items).toEqual([
  3566. expect.objectContaining({
  3567. queueItemId: "queue-guide-terminal",
  3568. text: "等下一个工具边界",
  3569. delivery: {
  3570. requested: "guide",
  3571. admitted: "queue",
  3572. fallbackReasonCode: "guide.noToolBoundary",
  3573. },
  3574. steer: { state: "fellBack", reasonCode: "guide.noToolBoundary" },
  3575. }),
  3576. ]);
  3577. });
  3578. // ── 错误态 ──
  3579. it("错误:turn_error → phase=error + lastError + turnHeader failed", () => {
  3580. const turnId = "turn-1";
  3581. const log = new EventLog();
  3582. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3583. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  3584. log.push(
  3585. SessionEventType.TurnError,
  3586. { error: { type: "ProviderError", message: "rate limited" }, turnPhase: "model" },
  3587. { turnId },
  3588. );
  3589. const { projection } = runAll(log.events);
  3590. const snapshot = projection.getSnapshot();
  3591. expect(snapshot.control.phase).toBe("error");
  3592. expect(snapshot.control.lastError).toMatchObject({
  3593. code: "ProviderError",
  3594. message: "rate limited",
  3595. recoverable: true,
  3596. source: "runtime",
  3597. });
  3598. expect(snapshot.rows.window.find((row) => row.kind === "turnHeader")).toMatchObject({
  3599. state: "failed",
  3600. });
  3601. });
  3602. it("错误:TurnError 保留底层错误详情到 V4 lastError", () => {
  3603. const log = new EventLog();
  3604. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3605. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  3606. log.push(
  3607. SessionEventType.TurnError,
  3608. {
  3609. error: {
  3610. type: "ModelError",
  3611. message: "Model request failed",
  3612. underlyingErrorMessage: "Runtime headers request failed",
  3613. underlyingErrorDetail: "Runtime headers helper timed out after 10000ms.",
  3614. },
  3615. turnPhase: "model",
  3616. },
  3617. { turnId: "turn-1" },
  3618. );
  3619. expect(runAll(log.events).projection.getSnapshot().control.lastError).toMatchObject({
  3620. underlyingErrorMessage: "Runtime headers request failed",
  3621. underlyingErrorDetail: "Runtime headers helper timed out after 10000ms.",
  3622. });
  3623. });
  3624. it.each([
  3625. ["card-highspeed-1", "card-highspeed-1"],
  3626. [null, null],
  3627. ] as const)("错误:TurnError 的 Highspeed 卡归因 %s 透传到 V4 lastError", (value, expected) => {
  3628. const log = new EventLog();
  3629. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3630. log.push(
  3631. SessionEventType.TurnError,
  3632. {
  3633. error: {
  3634. type: "ModelError",
  3635. message: "Model creation failed",
  3636. code: "provider_not_found",
  3637. attribution: { source: "provider", highspeedCardId: value },
  3638. },
  3639. turnPhase: "model_creation",
  3640. },
  3641. { turnId: "turn-1" },
  3642. );
  3643. expect(runAll(log.events).projection.getSnapshot().control.lastError).toMatchObject({
  3644. code: "provider_not_found",
  3645. attribution: { source: "provider", highspeedCardId: expected },
  3646. });
  3647. });
  3648. it("错误:请求期 Highspeed 无处可退的归因原样透传到 V4 lastError", () => {
  3649. // 3402 是 provider 错误码而非目录错误;Renderer 退卡只能依赖 Core 发布的结构化事实。
  3650. const log = new EventLog();
  3651. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3652. log.push(
  3653. SessionEventType.TurnError,
  3654. {
  3655. error: {
  3656. type: "ModelError",
  3657. message: "highspeed card is invalid",
  3658. code: "3402",
  3659. attribution: {
  3660. source: "provider",
  3661. providerId: "account:bigmodel-highspeed-card",
  3662. providerErrorCode: "3402",
  3663. statusCode: 400,
  3664. highspeedCardId: "card-highspeed-request",
  3665. highspeedFallbackUnavailable: true,
  3666. },
  3667. },
  3668. turnPhase: "model",
  3669. },
  3670. { turnId: "turn-1" },
  3671. );
  3672. expect(runAll(log.events).projection.getSnapshot().control.lastError).toMatchObject({
  3673. code: "3402",
  3674. source: "provider",
  3675. attribution: {
  3676. providerErrorCode: "3402",
  3677. highspeedCardId: "card-highspeed-request",
  3678. highspeedFallbackUnavailable: true,
  3679. },
  3680. });
  3681. });
  3682. it("错误:TurnError 保留 future queue 并暂停自动消费", () => {
  3683. const turnId = "turn-error-queue";
  3684. const log = new EventLog();
  3685. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3686. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "首轮失败" }, { turnId });
  3687. log.push(
  3688. SessionEventType.TurnSteerQueued,
  3689. {
  3690. pendingInputId: "queue-after-error",
  3691. inputId: "input-after-error",
  3692. input: "错误后仍要发送",
  3693. inputPreview: "错误后仍要发送",
  3694. inputSize: 24,
  3695. targetTurnId: turnId,
  3696. queueLength: 1,
  3697. delivery: "queue",
  3698. },
  3699. { turnId },
  3700. );
  3701. log.push(
  3702. SessionEventType.TurnError,
  3703. { error: { type: "ProviderError", message: "provider 失败" }, turnPhase: "model" },
  3704. { turnId },
  3705. );
  3706. const { projection } = runAll(log.events);
  3707. const snapshot = projection.getSnapshot();
  3708. expect(snapshot.control.phase).toBe("error");
  3709. expect(snapshot.queue).toMatchObject({
  3710. autoDrain: false,
  3711. pauseReason: "error",
  3712. items: [expect.objectContaining({ queueItemId: "queue-after-error" })],
  3713. });
  3714. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  3715. });
  3716. it.each([true, false])("错误:TurnError retryable=%s 原样映射 recoverable", (retryable) => {
  3717. const turnId = "turn-retryable";
  3718. const log = new EventLog();
  3719. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3720. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  3721. log.push(
  3722. SessionEventType.TurnError,
  3723. {
  3724. error: { type: "ProviderError", message: "failed", retryable },
  3725. turnPhase: "model",
  3726. },
  3727. { turnId },
  3728. );
  3729. const { projection } = runAll(log.events);
  3730. expect(projection.getSnapshot().control.lastError?.recoverable).toBe(retryable);
  3731. });
  3732. it("错误:TurnError 结构化归因进入 lastError,但不改写既有 recoverable", () => {
  3733. const turnId = "turn-attribution";
  3734. const log = new EventLog();
  3735. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3736. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  3737. log.push(
  3738. SessionEventType.TurnError,
  3739. {
  3740. error: {
  3741. type: "model_request_failed",
  3742. message: "Provider stream failed",
  3743. attribution: {
  3744. source: "network",
  3745. reason: "network_error",
  3746. providerId: "default-deepseek",
  3747. modelId: "deepseek-v4-flash",
  3748. providerKind: "anthropic",
  3749. transport: "sse",
  3750. statusCode: 503,
  3751. retryable: false,
  3752. },
  3753. },
  3754. turnPhase: "model",
  3755. },
  3756. { turnId },
  3757. );
  3758. const { projection } = runAll(log.events);
  3759. const snapshot = projection.getSnapshot();
  3760. expect(snapshot.control.lastError).toMatchObject({
  3761. source: "network",
  3762. recoverable: true,
  3763. attribution: {
  3764. source: "network",
  3765. reason: "network_error",
  3766. providerId: "default-deepseek",
  3767. modelId: "deepseek-v4-flash",
  3768. providerKind: "anthropic",
  3769. transport: "sse",
  3770. statusCode: 503,
  3771. retryable: false,
  3772. },
  3773. });
  3774. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  3775. });
  3776. it("错误后新 turn 清除 lastError(与旧 reducer 同一裁决)", () => {
  3777. const log = new EventLog();
  3778. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3779. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  3780. log.push(
  3781. SessionEventType.TurnError,
  3782. { error: { type: "X", message: "boom" }, turnPhase: "model" },
  3783. { turnId: "turn-1" },
  3784. );
  3785. log.push(SessionEventType.TurnStarted, { turnNumber: 2, input: "retry" }, { turnId: "turn-2" });
  3786. const { projection } = runAll(log.events);
  3787. expect(projection.getSnapshot().control.lastError).toBeNull();
  3788. expect(projection.getSnapshot().control.phase).toBe("running");
  3789. });
  3790. it("K10:retry 目标只允许全时间线最后一条 assistantText row", () => {
  3791. const log = new EventLog();
  3792. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3793. for (const turnNumber of [1, 2]) {
  3794. const turnId = `turn-${turnNumber}`;
  3795. log.push(
  3796. SessionEventType.TurnStarted,
  3797. { turnNumber, input: `Q${turnNumber}`, messageId: `user-${turnNumber}` },
  3798. { turnId },
  3799. );
  3800. log.push(
  3801. SessionEventType.ModelStreaming,
  3802. {
  3803. kind: "text_start",
  3804. delta: "",
  3805. done: false,
  3806. assistantMessageId: `assistant-${turnNumber}`,
  3807. },
  3808. { turnId },
  3809. );
  3810. log.push(
  3811. SessionEventType.ModelStreaming,
  3812. { kind: "text_delta", delta: `A${turnNumber}`, done: false },
  3813. { turnId },
  3814. );
  3815. log.push(
  3816. SessionEventType.ModelStreaming,
  3817. { kind: "text_end", delta: "", done: false },
  3818. { turnId },
  3819. );
  3820. log.push(
  3821. SessionEventType.TurnComplete,
  3822. {
  3823. response: `A${turnNumber}`,
  3824. tokenCount: 1,
  3825. toolCallCount: 0,
  3826. duration: 100,
  3827. resultType: "success",
  3828. },
  3829. { turnId },
  3830. );
  3831. }
  3832. const { projection } = runAll(log.events);
  3833. const assistantRows = projection
  3834. .getSnapshot()
  3835. .rows.window.filter((row) => row.kind === "assistantText");
  3836. expect(assistantRows).toHaveLength(2);
  3837. expect(projection.isLatestRetryAssistantRow(assistantRows[0]!.rowId)).toBe(false);
  3838. expect(projection.isLatestRetryAssistantRow(assistantRows[1]!.rowId)).toBe(true);
  3839. expect(assistantRows[0]!.actions?.canRetry).not.toBe(true);
  3840. expect(assistantRows[1]!.actions?.canRetry).toBe(true);
  3841. expect(projection.getMessageIdForRow(assistantRows[1]!.rowId)).toBe("assistant-2");
  3842. });
  3843. it("BG33/K11:background 结果轮无普通 retry,且不会恢复更早真实用户轮", () => {
  3844. const log = new EventLog();
  3845. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3846. const { projection } = runAll(log.events);
  3847. const apply = (type: SessionEventTypeUnion, payload: unknown, turnId: string): void => {
  3848. projection.applyEvent(log.push(type, payload, { turnId }));
  3849. };
  3850. const appendCompletedTurn = (input: {
  3851. assistantMessageId: string;
  3852. input: string;
  3853. inputSource?: "background_task";
  3854. messageId: string;
  3855. turnId: string;
  3856. turnNumber: number;
  3857. }): void => {
  3858. apply(
  3859. SessionEventType.TurnStarted,
  3860. {
  3861. turnNumber: input.turnNumber,
  3862. input: input.input,
  3863. messageId: input.messageId,
  3864. ...(input.inputSource
  3865. ? { inputSource: input.inputSource, inputVisibility: "model-only" }
  3866. : {}),
  3867. },
  3868. input.turnId,
  3869. );
  3870. apply(
  3871. SessionEventType.ModelStreaming,
  3872. {
  3873. kind: "text_start",
  3874. delta: "",
  3875. done: false,
  3876. assistantMessageId: input.assistantMessageId,
  3877. },
  3878. input.turnId,
  3879. );
  3880. apply(
  3881. SessionEventType.ModelStreaming,
  3882. { kind: "text_delta", delta: `answer ${input.turnNumber}`, done: false },
  3883. input.turnId,
  3884. );
  3885. apply(
  3886. SessionEventType.ModelStreaming,
  3887. { kind: "text_end", delta: "", done: false },
  3888. input.turnId,
  3889. );
  3890. apply(
  3891. SessionEventType.TurnComplete,
  3892. {
  3893. response: `answer ${input.turnNumber}`,
  3894. tokenCount: 1,
  3895. toolCallCount: 0,
  3896. duration: 100,
  3897. resultType: "success",
  3898. },
  3899. input.turnId,
  3900. );
  3901. };
  3902. appendCompletedTurn({
  3903. assistantMessageId: "assistant-user-1",
  3904. input: "Q1",
  3905. messageId: "user-1",
  3906. turnId: "turn-user-1",
  3907. turnNumber: 1,
  3908. });
  3909. let assistantRows = projection
  3910. .getSnapshot()
  3911. .rows.window.filter((row) => row.kind === "assistantText");
  3912. expect(assistantRows.map((row) => row.actions?.canRetry === true)).toEqual([true]);
  3913. appendCompletedTurn({
  3914. assistantMessageId: "assistant-background-1",
  3915. input: "background result",
  3916. inputSource: "background_task",
  3917. messageId: "wake-1",
  3918. turnId: "turn-background-1",
  3919. turnNumber: 2,
  3920. });
  3921. assistantRows = projection
  3922. .getSnapshot()
  3923. .rows.window.filter((row) => row.kind === "assistantText");
  3924. expect(assistantRows.map((row) => row.actions?.canRetry === true)).toEqual([false, false]);
  3925. expect(assistantRows[1]!.actions?.canFork).toBe(true);
  3926. const backgroundEntityId = projection.getEntityIdForRow(assistantRows[1]!.rowId);
  3927. expect(backgroundEntityId).toBeTruthy();
  3928. expect(
  3929. projection.resolveRowActionTarget(
  3930. { rowId: assistantRows[1]!.rowId, entityId: backgroundEntityId! },
  3931. "retryTurn",
  3932. ),
  3933. ).toEqual({ ok: false, status: "rejected", reasonCode: "guard.actionUnavailable" });
  3934. appendCompletedTurn({
  3935. assistantMessageId: "assistant-user-2",
  3936. input: "Q2",
  3937. messageId: "user-2",
  3938. turnId: "turn-user-2",
  3939. turnNumber: 3,
  3940. });
  3941. assistantRows = projection
  3942. .getSnapshot()
  3943. .rows.window.filter((row) => row.kind === "assistantText");
  3944. expect(assistantRows.map((row) => row.actions?.canRetry === true)).toEqual([
  3945. false,
  3946. false,
  3947. true,
  3948. ]);
  3949. });
  3950. });
  3951. describe("V4 API 重试状态投影", () => {
  3952. function runningProjection(): { log: EventLog; projection: ProductProjection } {
  3953. const log = new EventLog();
  3954. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  3955. log.push(
  3956. SessionEventType.TurnStarted,
  3957. { turnNumber: 1, input: "触发模型请求", messageId: "user-retry-1" },
  3958. { turnId: "turn-retry-1" },
  3959. );
  3960. return { log, projection: runAll(log.events).projection };
  3961. }
  3962. function modelStatus(overrides: Record<string, unknown>): Record<string, unknown> {
  3963. return {
  3964. timestamp: "2026-07-14T07:25:25.985Z",
  3965. traceId: "trace-1",
  3966. requestId: "request-retry-1",
  3967. model: { providerId: "bigmodel", modelId: "glm-5.2" },
  3968. transport: "sse",
  3969. attempt: 1,
  3970. maxAttempts: 11,
  3971. ...overrides,
  3972. };
  3973. }
  3974. it("配置读取重试保留错误类别,桌面与手机使用同一状态", () => {
  3975. const { log, projection } = runningProjection();
  3976. const deltas = projection.applyEvent(
  3977. log.push(
  3978. SessionEventType.ModelNetworkStatus,
  3979. modelStatus({
  3980. type: "model_retry_scheduled",
  3981. delayMs: 2000,
  3982. nextAttempt: 2,
  3983. reason: "network_error",
  3984. errorCode: ModelErrorCode.ModelRequestVerificationConfigNetwork,
  3985. }),
  3986. { turnId: "turn-retry-1" },
  3987. ),
  3988. );
  3989. expect(projection.getSnapshot().control.apiRetry?.reasonCode).toBe(
  3990. "request_verification_config_network",
  3991. );
  3992. expect(() => conversationSnapshotSchema.parse(projection.getSnapshot())).not.toThrow();
  3993. for (const profile of [DELIVERY_PROFILES.continuous, DELIVERY_PROFILES.replayable]) {
  3994. expect(filterConversationDeltasForProfile(deltas, profile)).toEqual(deltas);
  3995. }
  3996. });
  3997. it("429 重试在两个 delivery profile 中可见,并保持到首次有效模型进展", () => {
  3998. const { log, projection } = runningProjection();
  3999. const scheduledAt = 1_721_000_000_000;
  4000. const scheduled = log.push(
  4001. SessionEventType.ModelNetworkStatus,
  4002. modelStatus({
  4003. type: "model_retry_scheduled",
  4004. delayMs: 44_000,
  4005. nextAttempt: 2,
  4006. reason: "rate_limited",
  4007. message: "rate limited",
  4008. statusCode: 429,
  4009. }),
  4010. { turnId: "turn-retry-1", timestampMs: scheduledAt },
  4011. );
  4012. const retryDeltas = projection.applyEvent(scheduled);
  4013. expect(projection.getSnapshot().control.apiRetry).toEqual({
  4014. attempt: 1,
  4015. maxAttempts: 11,
  4016. nextRetryAt: scheduledAt + 44_000,
  4017. reasonCode: "fault.provider.rateLimited",
  4018. });
  4019. expect(() => conversationSnapshotSchema.parse(projection.getSnapshot())).not.toThrow();
  4020. for (const profile of [DELIVERY_PROFILES.continuous, DELIVERY_PROFILES.replayable]) {
  4021. expect(filterConversationDeltasForProfile(retryDeltas, profile)).toEqual(retryDeltas);
  4022. }
  4023. const retryStarted = log.push(
  4024. SessionEventType.ModelNetworkStatus,
  4025. modelStatus({ type: "model_request_started", attempt: 2 }),
  4026. { turnId: "turn-retry-1" },
  4027. );
  4028. expect(projection.applyEvent(retryStarted)).toEqual([]);
  4029. expect(projection.getSnapshot().control.apiRetry?.attempt).toBe(1);
  4030. projection.applyEvent(
  4031. log.push(
  4032. SessionEventType.ModelStreaming,
  4033. {
  4034. kind: "text_start",
  4035. delta: "",
  4036. done: false,
  4037. assistantMessageId: "assistant-retry-1",
  4038. },
  4039. { turnId: "turn-retry-1" },
  4040. ),
  4041. );
  4042. expect(projection.getSnapshot().control.apiRetry?.attempt).toBe(1);
  4043. projection.applyEvent(
  4044. log.push(
  4045. SessionEventType.ModelStreaming,
  4046. { kind: "text_delta", delta: "连接已恢复", done: false },
  4047. { turnId: "turn-retry-1" },
  4048. ),
  4049. );
  4050. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  4051. });
  4052. it("签名修复复用 provider retry live-tail 状态", () => {
  4053. const { log, projection } = runningProjection();
  4054. const scheduledAt = 1_721_000_000_000;
  4055. projection.applyEvent(
  4056. log.push(
  4057. SessionEventType.ModelNetworkStatus,
  4058. modelStatus({
  4059. type: "model_retry_scheduled",
  4060. delayMs: 0,
  4061. maxAttempts: 2,
  4062. nextAttempt: 2,
  4063. reason: "reasoning_signature_repair",
  4064. message: "thinking signature rejected",
  4065. statusCode: 400,
  4066. }),
  4067. { turnId: "turn-retry-1", timestampMs: scheduledAt },
  4068. ),
  4069. );
  4070. expect(projection.getSnapshot().control.apiRetry).toEqual({
  4071. attempt: 1,
  4072. maxAttempts: 2,
  4073. nextRetryAt: scheduledAt,
  4074. reasonCode: "fault.provider.requestFailed",
  4075. });
  4076. });
  4077. it("忽略非当前 turn 的迟到重试与完成事件", () => {
  4078. const { log, projection } = runningProjection();
  4079. const retryPayload = modelStatus({
  4080. type: "model_retry_scheduled",
  4081. delayMs: 1_000,
  4082. nextAttempt: 2,
  4083. reason: "rate_limited",
  4084. message: "rate limited",
  4085. statusCode: 429,
  4086. });
  4087. projection.applyEvent(
  4088. log.push(SessionEventType.ModelNetworkStatus, retryPayload, { turnId: "turn-stale" }),
  4089. );
  4090. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  4091. projection.applyEvent(
  4092. log.push(SessionEventType.ModelNetworkStatus, retryPayload, { turnId: "turn-retry-1" }),
  4093. );
  4094. expect(projection.getSnapshot().control.apiRetry).not.toBeNull();
  4095. projection.applyEvent(
  4096. log.push(
  4097. SessionEventType.ModelNetworkStatus,
  4098. modelStatus({ type: "model_request_completed", durationMs: 50 }),
  4099. { turnId: "turn-stale" },
  4100. ),
  4101. );
  4102. expect(projection.getSnapshot().control.apiRetry).not.toBeNull();
  4103. });
  4104. it("请求完成、不可重试失败和 turn 终态都会清理重试状态", () => {
  4105. const { log, projection } = runningProjection();
  4106. const scheduleRetry = (attempt: number) =>
  4107. projection.applyEvent(
  4108. log.push(
  4109. SessionEventType.ModelNetworkStatus,
  4110. modelStatus({
  4111. type: "model_retry_scheduled",
  4112. attempt,
  4113. delayMs: 1_000,
  4114. nextAttempt: attempt + 1,
  4115. reason: "server_error",
  4116. message: "server error",
  4117. statusCode: 503,
  4118. }),
  4119. { turnId: "turn-retry-1" },
  4120. ),
  4121. );
  4122. scheduleRetry(1);
  4123. projection.applyEvent(
  4124. log.push(
  4125. SessionEventType.ModelNetworkStatus,
  4126. modelStatus({
  4127. type: "model_request_failed",
  4128. reason: "server_error",
  4129. retryable: true,
  4130. message: "retryable",
  4131. statusCode: 503,
  4132. }),
  4133. { turnId: "turn-retry-1" },
  4134. ),
  4135. );
  4136. expect(projection.getSnapshot().control.apiRetry).not.toBeNull();
  4137. projection.applyEvent(
  4138. log.push(
  4139. SessionEventType.ModelNetworkStatus,
  4140. modelStatus({ type: "model_request_completed", attempt: 2, durationMs: 50 }),
  4141. { turnId: "turn-retry-1" },
  4142. ),
  4143. );
  4144. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  4145. scheduleRetry(2);
  4146. projection.applyEvent(
  4147. log.push(
  4148. SessionEventType.ModelNetworkStatus,
  4149. modelStatus({
  4150. type: "model_request_failed",
  4151. attempt: 3,
  4152. reason: "server_error",
  4153. retryable: false,
  4154. message: "exhausted",
  4155. statusCode: 503,
  4156. }),
  4157. { turnId: "turn-retry-1" },
  4158. ),
  4159. );
  4160. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  4161. scheduleRetry(3);
  4162. projection.applyEvent(
  4163. log.push(
  4164. SessionEventType.TurnComplete,
  4165. {
  4166. response: "done",
  4167. tokenCount: 1,
  4168. toolCallCount: 0,
  4169. duration: 100,
  4170. resultType: "success",
  4171. },
  4172. { turnId: "turn-retry-1" },
  4173. ),
  4174. );
  4175. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  4176. });
  4177. it("core SSE 恢复次数进入同一 apiRetry,并在工具进展后清理", () => {
  4178. const { log, projection } = runningProjection();
  4179. const recoveryStartedAt = 1_721_000_100_000;
  4180. projection.applyEvent(
  4181. log.push(
  4182. SessionEventType.StreamRecoveryStarted,
  4183. {
  4184. attemptId: "stream-attempt-1",
  4185. assistantMessageId: "assistant-retry-1",
  4186. failedRequestId: "request-retry-1",
  4187. failureKind: "provider_stream_error",
  4188. message: "stream disconnected",
  4189. retryNumber: 3,
  4190. maxRetries: 10,
  4191. },
  4192. { turnId: "turn-retry-1", timestampMs: recoveryStartedAt },
  4193. ),
  4194. );
  4195. expect(projection.getSnapshot().control.apiRetry).toEqual({
  4196. attempt: 3,
  4197. maxAttempts: 11,
  4198. nextRetryAt: recoveryStartedAt,
  4199. reasonCode: "fault.network.sseDisconnected",
  4200. });
  4201. projection.applyEvent(
  4202. log.push(
  4203. SessionEventType.StreamRecoveryRetryStarted,
  4204. {
  4205. attemptId: "stream-attempt-1",
  4206. anchorId: "anchor-1",
  4207. failedRequestId: "request-retry-1",
  4208. retryNumber: 3,
  4209. maxRetries: 10,
  4210. streamMode: "sse",
  4211. },
  4212. { turnId: "turn-retry-1" },
  4213. ),
  4214. );
  4215. projection.applyEvent(
  4216. log.push(
  4217. SessionEventType.ModelNetworkStatus,
  4218. modelStatus({
  4219. type: "model_request_started",
  4220. streamRecovery: {
  4221. attemptId: "stream-attempt-1",
  4222. anchorId: "anchor-1",
  4223. recoveredFromRequestId: "request-retry-1",
  4224. retryNumber: 3,
  4225. maxRetries: 10,
  4226. },
  4227. }),
  4228. { turnId: "turn-retry-1" },
  4229. ),
  4230. );
  4231. expect(projection.getSnapshot().control.apiRetry).toMatchObject({
  4232. attempt: 3,
  4233. maxAttempts: 11,
  4234. reasonCode: "fault.network.sseDisconnected",
  4235. });
  4236. projection.applyEvent(
  4237. log.push(
  4238. SessionEventType.ModelStreaming,
  4239. {
  4240. kind: "tool_input_start",
  4241. delta: "",
  4242. done: false,
  4243. toolCallId: "tool-retry-1",
  4244. toolName: "Read",
  4245. },
  4246. { turnId: "turn-retry-1" },
  4247. ),
  4248. );
  4249. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  4250. });
  4251. it("reasoning-only recovery 将旧思考行收口为 interrupted,再用新行承接恢复流", () => {
  4252. const { log, projection } = runningProjection();
  4253. projection.applyEvent(
  4254. log.push(
  4255. SessionEventType.ModelStreaming,
  4256. { kind: "reasoning_start", delta: "", done: false },
  4257. { turnId: "turn-retry-1" },
  4258. ),
  4259. );
  4260. projection.applyEvent(
  4261. log.push(
  4262. SessionEventType.ModelStreaming,
  4263. { kind: "reasoning_delta", delta: "unfinished", done: false },
  4264. { turnId: "turn-retry-1" },
  4265. ),
  4266. );
  4267. projection.applyEvent(
  4268. log.push(
  4269. SessionEventType.StreamRecoveryTailDiscarded,
  4270. {
  4271. attemptId: "stream-attempt-1",
  4272. anchorId: "anchor-1",
  4273. assistantMessageId: "assistant-retry-1",
  4274. discardedReasoningBytes: 10,
  4275. discardedTextBytes: 0,
  4276. discardedToolCallIds: [],
  4277. },
  4278. { turnId: "turn-retry-1" },
  4279. ),
  4280. );
  4281. expect(projection.getSnapshot().rows.window.filter((row) => row.kind === "reasoning")).toEqual([
  4282. expect.objectContaining({ state: "interrupted", text: "unfinished" }),
  4283. ]);
  4284. projection.applyEvent(
  4285. log.push(
  4286. SessionEventType.ModelStreaming,
  4287. { kind: "reasoning_delta", delta: "fresh", done: false },
  4288. { turnId: "turn-retry-1" },
  4289. ),
  4290. );
  4291. expect(
  4292. projection
  4293. .getSnapshot()
  4294. .rows.window.filter((row) => row.kind === "reasoning")
  4295. .map((row) => ({ state: row.state, text: row.text })),
  4296. ).toEqual([
  4297. { state: "interrupted", text: "unfinished" },
  4298. { state: "streaming", text: "fresh" },
  4299. ]);
  4300. });
  4301. it("tail_discarded 收口未定稿的流式 tool row,已提交的 running 行不动,恢复流用新 id 重开", () => {
  4302. const { log, projection } = runningProjection();
  4303. const turnId = "turn-retry-1";
  4304. // 已提交并在执行中的工具:它的终态由 executor 发布,recovery 不能替它收口。
  4305. projection.applyEvent(
  4306. log.push(
  4307. SessionEventType.ToolCallScheduled,
  4308. {
  4309. toolCallId: "tool-committed",
  4310. assistantMessageId: "assistant-retry-1",
  4311. toolName: "Read",
  4312. input: { file_path: "a.ts" },
  4313. schedule: { parallelGroups: [["tool-committed"]], executionOrder: ["tool-committed"] },
  4314. },
  4315. { turnId },
  4316. ),
  4317. );
  4318. projection.applyEvent(
  4319. log.push(
  4320. SessionEventType.ToolCallStarted,
  4321. { toolCallId: "tool-committed", toolName: "Read", startedAt: new Date() },
  4322. { turnId },
  4323. ),
  4324. );
  4325. // 断流时只写到一半的 CreateWorkflow:tool_input_start 已开行,tool_call 永远不会来。
  4326. projection.applyEvent(
  4327. log.push(
  4328. SessionEventType.ModelStreaming,
  4329. {
  4330. kind: "tool_input_start",
  4331. delta: "",
  4332. done: false,
  4333. toolCallId: "tool-orphan",
  4334. toolName: "CreateWorkflow",
  4335. },
  4336. { turnId },
  4337. ),
  4338. );
  4339. projection.applyEvent(
  4340. log.push(
  4341. SessionEventType.ModelStreaming,
  4342. {
  4343. kind: "tool_input_delta",
  4344. delta: '{"script":"const a = agent(',
  4345. done: false,
  4346. toolCallId: "tool-orphan",
  4347. },
  4348. { turnId },
  4349. ),
  4350. );
  4351. projection.applyEvent(
  4352. log.push(
  4353. SessionEventType.StreamRecoveryTailDiscarded,
  4354. {
  4355. attemptId: "stream-attempt-1",
  4356. anchorId: "anchor-1",
  4357. assistantMessageId: "assistant-retry-1",
  4358. discardedReasoningBytes: 0,
  4359. discardedTextBytes: 12,
  4360. discardedToolCallIds: [],
  4361. },
  4362. { turnId },
  4363. ),
  4364. );
  4365. const toolRows = () =>
  4366. projection
  4367. .getSnapshot()
  4368. .rows.window.filter((row) => row.kind === "toolCall")
  4369. .map((row) => ({
  4370. toolCallId: row.toolCallId,
  4371. status: row.status,
  4372. inputText: row.inputText,
  4373. }));
  4374. expect(toolRows()).toEqual([
  4375. { toolCallId: "tool-committed", status: "running", inputText: '{"file_path":"a.ts"}' },
  4376. { toolCallId: "tool-orphan", status: "cancelled", inputText: '{"script":"const a = agent(' },
  4377. ]);
  4378. // 恢复请求重新写脚本:新 id 开新行,旧行保持已收口,不会并排两张「正在编写工作流」。
  4379. projection.applyEvent(
  4380. log.push(
  4381. SessionEventType.ModelStreaming,
  4382. {
  4383. kind: "tool_input_start",
  4384. delta: "",
  4385. done: false,
  4386. toolCallId: "tool-retry",
  4387. toolName: "CreateWorkflow",
  4388. },
  4389. { turnId },
  4390. ),
  4391. );
  4392. expect(toolRows().map((row) => [row.toolCallId, row.status])).toEqual([
  4393. ["tool-committed", "running"],
  4394. ["tool-orphan", "cancelled"],
  4395. ["tool-retry", "inputStreaming"],
  4396. ]);
  4397. });
  4398. });
  4399. // ── 结构性黄金测试(13-golden-test-mapping §v4 新增)──
  4400. describe("结构性不变量", () => {
  4401. function fullDeltaStream(events: readonly SessionEvent[]): {
  4402. deltasPerEvent: ConversationDelta[][];
  4403. snapshots: ConversationSnapshot[];
  4404. } {
  4405. const { deltasPerEvent, snapshots } = runAll(events);
  4406. return { deltasPerEvent, snapshots };
  4407. }
  4408. it("结构性1:任意水位 W 取 snapshot + 续流 ≡ 全量重放(R-03)", () => {
  4409. const log = new EventLog();
  4410. basicTurnEvents(log);
  4411. const { deltasPerEvent, snapshots } = fullDeltaStream(log.events);
  4412. const final = snapshots[snapshots.length - 1]!;
  4413. for (let w = 0; w < log.events.length; w++) {
  4414. const snapshotAtW = snapshots[w + 1]!;
  4415. const tail = deltasPerEvent.slice(w + 1).flat();
  4416. const resumed = applyConversationDeltas(snapshotAtW, tail);
  4417. // seq 由帧区间记账推进(不在 delta 内),对比时对齐到终值。
  4418. expect({ ...resumed, seq: final.seq }).toEqual(final);
  4419. }
  4420. });
  4421. it("结构性4(半):coalesce 后的 delta 流与逐条投递终态逐字节一致", () => {
  4422. const log = new EventLog();
  4423. basicTurnEvents(log);
  4424. const { deltasPerEvent, snapshots } = fullDeltaStream(log.events);
  4425. const base = snapshots[0]!;
  4426. const all = deltasPerEvent.flat();
  4427. const direct = applyConversationDeltas(base, all);
  4428. const coalesced = applyConversationDeltas(base, coalesceConversationDeltas(all));
  4429. expect(coalesced).toEqual(direct);
  4430. });
  4431. it("结构性10:fault 注入 session A,session B 投影逐字节不变(X 组)", () => {
  4432. const logA = new EventLog("session-a");
  4433. logA.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4434. logA.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-a" });
  4435. const logB = new EventLog("session-b");
  4436. basicTurnEvents(logB, "turn-b");
  4437. const projectionA = new ProductProjection("session-a", "epoch-1");
  4438. const projectionB = new ProductProjection("session-b", "epoch-1");
  4439. for (const event of logB.events) projectionB.applyEvent(event);
  4440. const snapshotB = structuredClone(projectionB.getSnapshot());
  4441. for (const event of logA.events) projectionA.applyEvent(event);
  4442. const fault = new EventLog("session-a");
  4443. fault.push(
  4444. SessionEventType.TurnError,
  4445. { error: { type: "fault.network.unreachable", message: "ECONNREFUSED" }, turnPhase: "model" },
  4446. { turnId: "turn-a" },
  4447. );
  4448. for (const event of fault.events) projectionA.applyEvent(event);
  4449. expect(projectionA.getSnapshot().control.phase).toBe("error");
  4450. expect(projectionB.getSnapshot()).toEqual(snapshotB);
  4451. });
  4452. it("revision 递进:结构性事件 +1 且随帧携带;纯 row.delta 不递增(R-04)", () => {
  4453. const log = new EventLog();
  4454. basicTurnEvents(log);
  4455. const { deltasPerEvent, snapshots } = fullDeltaStream(log.events);
  4456. deltasPerEvent.forEach((deltas, index) => {
  4457. const structural = deltas.some(
  4458. (delta) =>
  4459. delta.op === "row.appended" ||
  4460. delta.op === "row.upserted" ||
  4461. delta.op === "row.removed" ||
  4462. (delta.op === "state.updated" &&
  4463. Object.keys(delta.patch).some((key) => key !== "revision" && key !== "usage")),
  4464. );
  4465. const prev = snapshots[index]!.revision;
  4466. const next = snapshots[index + 1]!.revision;
  4467. if (structural) {
  4468. expect(next).toBe(prev + 1);
  4469. // 携带规则:含 revision 递增事件的帧,deltas 必含 state.updated.revision。
  4470. const carried = deltas.some(
  4471. (delta) => delta.op === "state.updated" && delta.patch.revision === next,
  4472. );
  4473. expect(carried).toBe(true);
  4474. } else {
  4475. expect(next).toBe(prev);
  4476. }
  4477. });
  4478. // 纯文本流事件(text_delta)revision 不动。
  4479. const textDeltaIndex = log.events.findIndex(
  4480. (event) =>
  4481. event.type === SessionEventType.ModelStreaming &&
  4482. (event.payload as { kind?: string }).kind === "text_delta",
  4483. );
  4484. expect(snapshots[textDeltaIndex + 1]!.revision).toBe(snapshots[textDeltaIndex]!.revision);
  4485. });
  4486. it("确定性:同一事件日志重放两次,投影与 delta 流逐字节一致(rowId 纯函数,R-04)", () => {
  4487. const log = new EventLog();
  4488. basicTurnEvents(log);
  4489. const first = runAll(log.events);
  4490. const second = runAll(log.events);
  4491. expect(second.projection.getSnapshot()).toEqual(first.projection.getSnapshot());
  4492. expect(second.deltasPerEvent).toEqual(first.deltasPerEvent);
  4493. });
  4494. });
  4495. // ── 结构性4:两 profile 终态逐字节一致(05 §delivery-profile 收敛性黄金测试)──
  4496. // 同一事件序列跑 continuous / replayable 两档 flush 管线(filter → coalesce → apply),
  4497. // 断言终态与逐条直投逐字节一致。replayable 只是中间帧少,终态必须相同——
  4498. // 这同时机械验证收口不变量:被 profile 过滤的 row.delta(inputText/output.text/
  4499. // summaryText)必须被后续不可过滤的 row.upserted 蕴含。
  4500. describe("结构性4:两 profile 终态一致", () => {
  4501. function pipelineFinalState(
  4502. events: readonly SessionEvent[],
  4503. profile: DeliveryProfile,
  4504. ): ConversationSnapshot {
  4505. const { deltasPerEvent, snapshots } = runAll(events);
  4506. const base = snapshots[0]!;
  4507. const piped = coalesceConversationDeltas(
  4508. filterConversationDeltasForProfile(deltasPerEvent.flat(), profile),
  4509. );
  4510. return applyConversationDeltas(base, piped);
  4511. }
  4512. function assertProfileConvergence(events: readonly SessionEvent[]): void {
  4513. const { deltasPerEvent, snapshots } = runAll(events);
  4514. const direct = applyConversationDeltas(snapshots[0]!, deltasPerEvent.flat());
  4515. expect(pipelineFinalState(events, DELIVERY_PROFILES.continuous)).toEqual(direct);
  4516. expect(pipelineFinalState(events, DELIVERY_PROFILES.replayable)).toEqual(direct);
  4517. }
  4518. it("基础 turn(文本流式)", () => {
  4519. const log = new EventLog();
  4520. basicTurnEvents(log);
  4521. assertProfileConvergence(log.events);
  4522. });
  4523. it("tool 输入流式 → 权限 → 执行成功(inputText 被 upsert 收口)", () => {
  4524. const turnId = "turn-1";
  4525. const log = new EventLog();
  4526. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4527. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run ls" }, { turnId });
  4528. log.push(
  4529. SessionEventType.ModelStreaming,
  4530. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-1", toolName: "bash" },
  4531. { turnId },
  4532. );
  4533. log.push(
  4534. SessionEventType.ModelStreaming,
  4535. { kind: "tool_input_delta", delta: '{"command":', done: false, toolCallId: "tc-1" },
  4536. { turnId },
  4537. );
  4538. log.push(
  4539. SessionEventType.ModelStreaming,
  4540. { kind: "tool_input_delta", delta: '"ls"}', done: false, toolCallId: "tc-1" },
  4541. { turnId },
  4542. );
  4543. log.push(
  4544. SessionEventType.ToolCallScheduled,
  4545. {
  4546. toolCallId: "tc-1",
  4547. toolName: "bash",
  4548. input: { command: "ls" },
  4549. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  4550. },
  4551. { turnId },
  4552. );
  4553. log.push(
  4554. SessionEventType.PermissionRequested,
  4555. {
  4556. requestId: "req-1",
  4557. toolCallId: "tc-1",
  4558. toolName: "bash",
  4559. riskLevel: "medium",
  4560. reason: "Run",
  4561. input: { command: "ls" },
  4562. },
  4563. { turnId },
  4564. );
  4565. log.push(
  4566. SessionEventType.PermissionResolved,
  4567. { requestId: "req-1", toolCallId: "tc-1", decision: "allow" },
  4568. { turnId },
  4569. );
  4570. log.push(
  4571. SessionEventType.ToolCallStarted,
  4572. { toolCallId: "tc-1", toolName: "bash", startedAt: new Date() },
  4573. { turnId },
  4574. );
  4575. log.push(
  4576. SessionEventType.ToolCallResult,
  4577. { toolCallId: "tc-1", result: { success: true, content: "file-a" }, duration: 42 },
  4578. { turnId },
  4579. );
  4580. log.push(
  4581. SessionEventType.TurnComplete,
  4582. { response: "done", tokenCount: 1, toolCallCount: 1, duration: 100, resultType: "success" },
  4583. { turnId },
  4584. );
  4585. assertProfileConvergence(log.events);
  4586. });
  4587. it("BG13:foreground subagent child tool 只留在 child conversation,main 仍由父 Agent 保持 running", () => {
  4588. const turnId = "turn-foreground-agent";
  4589. const parentToolCallId = "call_parent_agent";
  4590. const childToolCallId = "tool_subagent_agent-1_call_child_todo";
  4591. const mirrored = {
  4592. agentId: "agent-1",
  4593. agentType: "general-purpose",
  4594. childSessionId: "session-child-1",
  4595. childToolCallId: "call_child_todo",
  4596. description: "Inspect the project",
  4597. parentToolCallId,
  4598. source: "subagent",
  4599. };
  4600. const log = new EventLog();
  4601. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4602. log.push(
  4603. SessionEventType.TurnStarted,
  4604. { turnNumber: 1, input: "inspect with a foreground agent" },
  4605. { turnId },
  4606. );
  4607. log.push(
  4608. SessionEventType.ToolCallScheduled,
  4609. {
  4610. toolCallId: parentToolCallId,
  4611. toolName: "Agent",
  4612. input: { description: "Inspect the project", prompt: "Inspect the project" },
  4613. schedule: {
  4614. parallelGroups: [[parentToolCallId]],
  4615. executionOrder: [parentToolCallId],
  4616. },
  4617. },
  4618. { turnId },
  4619. );
  4620. log.push(
  4621. SessionEventType.ToolCallStarted,
  4622. { toolCallId: parentToolCallId, toolName: "Agent", startedAt: new Date() },
  4623. { turnId },
  4624. );
  4625. log.push(
  4626. SessionEventType.SubagentSpawned,
  4627. {
  4628. agentId: "agent-1",
  4629. agentType: "general-purpose",
  4630. childSessionId: "session-child-1",
  4631. description: "Inspect the project",
  4632. parentToolCallId,
  4633. status: "running",
  4634. },
  4635. { turnId },
  4636. );
  4637. log.push(
  4638. SessionEventType.ToolCallScheduled,
  4639. {
  4640. ...mirrored,
  4641. toolCallId: childToolCallId,
  4642. toolName: "TodoWrite",
  4643. input: { todos: [{ id: "child-only", content: "Read files", status: "in_progress" }] },
  4644. schedule: {
  4645. parallelGroups: [[childToolCallId]],
  4646. executionOrder: [childToolCallId],
  4647. },
  4648. },
  4649. { turnId },
  4650. );
  4651. log.push(
  4652. SessionEventType.ToolCallStarted,
  4653. { ...mirrored, toolCallId: childToolCallId, toolName: "TodoWrite", startedAt: new Date() },
  4654. { turnId },
  4655. );
  4656. log.push(
  4657. SessionEventType.ToolCallResult,
  4658. {
  4659. ...mirrored,
  4660. toolCallId: childToolCallId,
  4661. result: { success: true, content: "child todo updated" },
  4662. duration: 10,
  4663. },
  4664. { turnId },
  4665. );
  4666. assertProfileConvergence(log.events);
  4667. const snapshot = runAll(log.events).projection.getSnapshot();
  4668. expect(snapshot.control.phase).toBe("running");
  4669. expect(snapshot.plan).toBeNull();
  4670. expect(
  4671. snapshot.rows.window.filter((row) => row.kind === "toolCall").map((row) => row.toolCallId),
  4672. ).toEqual([parentToolCallId]);
  4673. expect(snapshot.rows.window).toContainEqual(
  4674. expect.objectContaining({
  4675. kind: "subagent",
  4676. childSessionId: "session-child-1",
  4677. parentToolCallId,
  4678. status: "running",
  4679. }),
  4680. );
  4681. const childLog = new EventLog();
  4682. childLog.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4683. childLog.push(
  4684. SessionEventType.TurnStarted,
  4685. { turnNumber: 1, input: "Inspect the project" },
  4686. { turnId: "turn-child-1" },
  4687. );
  4688. childLog.push(
  4689. SessionEventType.ToolCallScheduled,
  4690. {
  4691. toolCallId: "call_child_todo",
  4692. toolName: "TodoWrite",
  4693. input: { todos: [{ id: "child-only", content: "Read files", status: "in_progress" }] },
  4694. schedule: {
  4695. parallelGroups: [["call_child_todo"]],
  4696. executionOrder: ["call_child_todo"],
  4697. },
  4698. },
  4699. { turnId: "turn-child-1" },
  4700. );
  4701. childLog.push(
  4702. SessionEventType.ToolCallStarted,
  4703. { toolCallId: "call_child_todo", toolName: "TodoWrite", startedAt: new Date() },
  4704. { turnId: "turn-child-1" },
  4705. );
  4706. childLog.push(
  4707. SessionEventType.ToolCallResult,
  4708. {
  4709. toolCallId: "call_child_todo",
  4710. result: { success: true, content: "child todo updated" },
  4711. duration: 10,
  4712. },
  4713. { turnId: "turn-child-1" },
  4714. );
  4715. assertProfileConvergence(childLog.events);
  4716. expect(runAll(childLog.events).projection.getSnapshot().rows.window).toContainEqual(
  4717. expect.objectContaining({
  4718. kind: "toolCall",
  4719. toolCallId: "call_child_todo",
  4720. status: "success",
  4721. }),
  4722. );
  4723. });
  4724. it("M07n:立即发送把等待审批的前台子代理转后台,父轮结束后审批仍待处理", () => {
  4725. // 事件顺序取自 core 运行时:child 的审批经镜像进入父会话,立即发送后 Agent 返回 async_launched,
  4726. // 旧轮以 cancelled 结束、新轮正常结束;child 仍在等用户作答,父界面必须继续显示这条审批。
  4727. const turnId = "turn-send-now-approval";
  4728. const parentToolCallId = "call_parent_agent_approval";
  4729. const agentId = "agent-approval";
  4730. const childSessionId = "session-child-approval";
  4731. const childToolCallId = `tool_subagent_${agentId}_call_child_ask`;
  4732. const mirrored = {
  4733. agentId,
  4734. agentType: "general-purpose",
  4735. childSessionId,
  4736. childToolCallId: "call_child_ask",
  4737. description: "Ask from child",
  4738. parentToolCallId,
  4739. source: "subagent",
  4740. };
  4741. const log = new EventLog();
  4742. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4743. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "ask via agent" }, { turnId });
  4744. log.push(
  4745. SessionEventType.ToolCallScheduled,
  4746. {
  4747. toolCallId: parentToolCallId,
  4748. toolName: "Agent",
  4749. input: { description: "Ask from child", prompt: "Ask the user" },
  4750. schedule: { parallelGroups: [[parentToolCallId]], executionOrder: [parentToolCallId] },
  4751. },
  4752. { turnId },
  4753. );
  4754. log.push(
  4755. SessionEventType.ToolCallStarted,
  4756. { toolCallId: parentToolCallId, toolName: "Agent", startedAt: new Date() },
  4757. { turnId },
  4758. );
  4759. log.push(
  4760. SessionEventType.SubagentSpawned,
  4761. {
  4762. agentId,
  4763. agentType: "general-purpose",
  4764. childSessionId,
  4765. description: "Ask from child",
  4766. parentToolCallId,
  4767. status: "running",
  4768. },
  4769. { turnId },
  4770. );
  4771. log.push(
  4772. SessionEventType.ToolCallScheduled,
  4773. {
  4774. ...mirrored,
  4775. toolCallId: childToolCallId,
  4776. toolName: "AskUserQuestion",
  4777. input: { questions: [{ question: "Which path?", header: "Path", options: [] }] },
  4778. schedule: { parallelGroups: [[childToolCallId]], executionOrder: [childToolCallId] },
  4779. },
  4780. { turnId },
  4781. );
  4782. log.push(
  4783. SessionEventType.PermissionRequested,
  4784. {
  4785. requestId: "ask-request-moved",
  4786. toolCallId: childToolCallId,
  4787. toolName: "AskUserQuestion",
  4788. riskLevel: "low",
  4789. reason: "Tool AskUserQuestion requires user interaction",
  4790. childSessionId,
  4791. origin: {
  4792. kind: "subagent",
  4793. agentId,
  4794. agentType: "general-purpose",
  4795. childSessionId,
  4796. description: "Ask from child",
  4797. parentSessionId: "session-1",
  4798. parentToolCallId,
  4799. parentTurnId: turnId,
  4800. },
  4801. input: {
  4802. questions: [
  4803. {
  4804. question: "Which path?",
  4805. header: "Path",
  4806. options: [
  4807. { label: "A", description: "Use path A" },
  4808. { label: "B", description: "Use path B" },
  4809. ],
  4810. },
  4811. ],
  4812. },
  4813. },
  4814. { turnId },
  4815. );
  4816. log.push(
  4817. SessionEventType.ToolCallResult,
  4818. {
  4819. toolCallId: parentToolCallId,
  4820. result: { success: true, content: "Async agent launched successfully." },
  4821. duration: 8,
  4822. },
  4823. { turnId },
  4824. );
  4825. log.push(
  4826. SessionEventType.BackgroundTaskStarted,
  4827. {
  4828. taskId: agentId,
  4829. toolCallId: parentToolCallId,
  4830. toolName: "Agent",
  4831. taskKind: "subagent",
  4832. childSessionId,
  4833. cancellable: true,
  4834. description: "Ask from child",
  4835. status: "running",
  4836. },
  4837. { turnId },
  4838. );
  4839. log.push(
  4840. SessionEventType.TurnComplete,
  4841. {
  4842. response: "",
  4843. tokenCount: 0,
  4844. toolCallCount: 0,
  4845. duration: 30,
  4846. resultType: "cancelled",
  4847. preserveQueueAutoDrainOnCancel: true,
  4848. },
  4849. { turnId },
  4850. );
  4851. log.push(
  4852. SessionEventType.TurnStarted,
  4853. { turnNumber: 2, input: "send this now" },
  4854. { turnId: "turn-send-now" },
  4855. );
  4856. log.push(
  4857. SessionEventType.TurnComplete,
  4858. { response: "parent reply", tokenCount: 2, toolCallCount: 0, duration: 2 },
  4859. { turnId: "turn-send-now" },
  4860. );
  4861. let snapshot = runAll(log.events).projection.getSnapshot();
  4862. expect(snapshot.pendingInteractions).toHaveLength(1);
  4863. expect(snapshot.pendingInteractions[0]).toMatchObject({
  4864. interactionId: "ask-request-moved",
  4865. kind: "userInput",
  4866. payload: { toolCallId: childToolCallId, origin: { kind: "subagent", agentId } },
  4867. });
  4868. expect(snapshot.backgroundWorks).toContainEqual(
  4869. expect.objectContaining({ workId: agentId, status: "running" }),
  4870. );
  4871. // 用户作答后审批收口。
  4872. log.push(
  4873. SessionEventType.PermissionResolved,
  4874. { requestId: "ask-request-moved", toolCallId: childToolCallId, decision: "allow" },
  4875. { turnId },
  4876. );
  4877. snapshot = runAll(log.events).projection.getSnapshot();
  4878. expect(snapshot.pendingInteractions).toEqual([]);
  4879. });
  4880. it("BG26:真实失败 lifecycle 归并 hydration 合成行并补齐 child session 身份", () => {
  4881. const turnId = "turn-background-agent-rate-limit";
  4882. const parentToolCallId = "call-background-agent-rate-limit";
  4883. const realAgentId = "agent-background-rate-limit";
  4884. const childSessionId = "session-child-rate-limit";
  4885. const log = new EventLog();
  4886. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4887. log.push(
  4888. SessionEventType.TurnStarted,
  4889. { turnNumber: 1, input: "launch background agent" },
  4890. { turnId },
  4891. );
  4892. log.push(
  4893. SessionEventType.ToolCallScheduled,
  4894. {
  4895. toolCallId: parentToolCallId,
  4896. toolName: "Agent",
  4897. input: {
  4898. description: "Trigger provider rate limit",
  4899. prompt: "Trigger provider rate limit",
  4900. run_in_background: true,
  4901. },
  4902. schedule: {
  4903. parallelGroups: [[parentToolCallId]],
  4904. executionOrder: [parentToolCallId],
  4905. },
  4906. },
  4907. { turnId },
  4908. );
  4909. log.push(
  4910. SessionEventType.ToolCallStarted,
  4911. { toolCallId: parentToolCallId, toolName: "Agent", startedAt: new Date() },
  4912. { turnId },
  4913. );
  4914. // transcript hydration 只能从文本 tool output 合成出 toolCallId 身份,拿不到 childSessionId。
  4915. log.push(
  4916. SessionEventType.SubagentSpawned,
  4917. {
  4918. agentId: parentToolCallId,
  4919. agentType: "general-purpose",
  4920. description: "Trigger provider rate limit",
  4921. parentToolCallId,
  4922. status: "running",
  4923. },
  4924. { turnId },
  4925. );
  4926. // hydration await 窗口内补回的真实 spawned 也必须复用合成行,并建立真实 agentId 映射。
  4927. log.push(
  4928. SessionEventType.SubagentSpawned,
  4929. {
  4930. agentId: realAgentId,
  4931. agentType: "general-purpose",
  4932. background: true,
  4933. childSessionId,
  4934. description: "Trigger provider rate limit",
  4935. parentToolCallId,
  4936. status: "running",
  4937. },
  4938. { turnId },
  4939. );
  4940. // live terminal 事件携带真实 runtime 身份,必须更新上一行而不是追加重复 SubagentRow。
  4941. log.push(
  4942. SessionEventType.SubagentStopped,
  4943. {
  4944. agentId: realAgentId,
  4945. agentType: "general-purpose",
  4946. background: true,
  4947. parentToolCallId,
  4948. status: "failed",
  4949. error: "PROVIDER_ERROR: 429 rate limited",
  4950. },
  4951. { turnId },
  4952. );
  4953. const snapshot = runAll(log.events).projection.getSnapshot();
  4954. const subagentRows = snapshot.rows.window.filter(
  4955. (row): row is Extract<(typeof snapshot.rows.window)[number], { kind: "subagent" }> =>
  4956. row.kind === "subagent",
  4957. );
  4958. expect(subagentRows).toHaveLength(1);
  4959. expect(subagentRows[0]).toMatchObject({
  4960. childSessionId,
  4961. parentToolCallId,
  4962. status: "failed",
  4963. summaryText: "PROVIDER_ERROR: 429 rate limited",
  4964. });
  4965. });
  4966. it("BG35:background subagent child tool 不生成父 row,迟到终态也不复活", () => {
  4967. const turnId = "turn-background-agent";
  4968. const parentToolCallId = "call_parent_agent";
  4969. const childToolCallId = "tool_subagent_agent-1_call_child_bash";
  4970. const mirrored = {
  4971. agentId: "agent-1",
  4972. agentType: "general-purpose",
  4973. background: true,
  4974. childSessionId: "session-child-1",
  4975. childToolCallId: "call_child_bash",
  4976. description: "Run delayed Bash",
  4977. parentToolCallId,
  4978. source: "subagent",
  4979. };
  4980. const log = new EventLog();
  4981. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4982. log.push(
  4983. SessionEventType.TurnStarted,
  4984. { turnNumber: 1, input: "launch background agent" },
  4985. { turnId },
  4986. );
  4987. log.push(
  4988. SessionEventType.ToolCallScheduled,
  4989. {
  4990. toolCallId: parentToolCallId,
  4991. toolName: "Agent",
  4992. input: {
  4993. description: "Run delayed Bash",
  4994. prompt: "Run delayed Bash",
  4995. run_in_background: true,
  4996. },
  4997. schedule: {
  4998. parallelGroups: [[parentToolCallId]],
  4999. executionOrder: [parentToolCallId],
  5000. },
  5001. },
  5002. { turnId },
  5003. );
  5004. log.push(
  5005. SessionEventType.ToolCallStarted,
  5006. { toolCallId: parentToolCallId, toolName: "Agent", startedAt: new Date() },
  5007. { turnId },
  5008. );
  5009. log.push(
  5010. SessionEventType.ToolCallResult,
  5011. {
  5012. toolCallId: parentToolCallId,
  5013. result: { success: true, content: "background agent launched" },
  5014. duration: 5,
  5015. },
  5016. { turnId },
  5017. );
  5018. log.push(
  5019. SessionEventType.ToolCallScheduled,
  5020. {
  5021. ...mirrored,
  5022. toolCallId: childToolCallId,
  5023. toolName: "Bash",
  5024. input: { command: "sleep 60 && date" },
  5025. schedule: {
  5026. parallelGroups: [[childToolCallId]],
  5027. executionOrder: [childToolCallId],
  5028. },
  5029. },
  5030. { turnId },
  5031. );
  5032. log.push(
  5033. SessionEventType.ToolCallStarted,
  5034. { ...mirrored, toolCallId: childToolCallId, toolName: "Bash", startedAt: new Date() },
  5035. { turnId },
  5036. );
  5037. log.push(
  5038. SessionEventType.TurnComplete,
  5039. {
  5040. response: "launched",
  5041. tokenCount: 1,
  5042. toolCallCount: 1,
  5043. duration: 10,
  5044. resultType: "success",
  5045. },
  5046. { turnId },
  5047. );
  5048. const beforeChildTerminal = runAll(log.events).projection.getSnapshot();
  5049. expect(beforeChildTerminal.control.phase).toBe("completedSuccess");
  5050. expect(
  5051. beforeChildTerminal.rows.window
  5052. .filter((row) => row.kind === "toolCall")
  5053. .map((row) => row.toolCallId),
  5054. ).toEqual([parentToolCallId]);
  5055. log.push(
  5056. SessionEventType.ToolCallResult,
  5057. {
  5058. ...mirrored,
  5059. toolCallId: childToolCallId,
  5060. result: { success: true, content: "Fri Jul 17 12:40:36 CST 2026" },
  5061. duration: 60_000,
  5062. },
  5063. { turnId },
  5064. );
  5065. log.push(
  5066. SessionEventType.ToolCallError,
  5067. {
  5068. ...mirrored,
  5069. toolCallId: "tool_subagent_agent-1_call_child_error",
  5070. error: { type: "fault.runtime.toolFailed", message: "late child failure" },
  5071. },
  5072. { turnId },
  5073. );
  5074. assertProfileConvergence(log.events);
  5075. const terminalSnapshot = runAll(log.events).projection.getSnapshot();
  5076. expect(terminalSnapshot.control.phase).toBe("completedSuccess");
  5077. expect(
  5078. terminalSnapshot.rows.window
  5079. .filter((row) => row.kind === "toolCall")
  5080. .map((row) => row.toolCallId),
  5081. ).toEqual([parentToolCallId]);
  5082. });
  5083. it("BG18:父轮结束后的 child tool 事件不应清掉原 background Agent 控制身份", () => {
  5084. const parentTurnId = "turn-background-parent-anchor";
  5085. const followUpTurnId = "turn-background-parent-anchor-follow-up";
  5086. const parentToolCallId = "toolu_e2e_background_parent_anchor_agent";
  5087. const agentId = "agent-parent-anchor";
  5088. const childSessionId = "session-child-parent-anchor";
  5089. const log = new EventLog();
  5090. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5091. log.push(
  5092. SessionEventType.TurnStarted,
  5093. { turnNumber: 1, input: "launch background agent" },
  5094. { turnId: parentTurnId },
  5095. );
  5096. log.push(
  5097. SessionEventType.SubagentSpawned,
  5098. {
  5099. agentId,
  5100. agentType: "general-purpose",
  5101. background: true,
  5102. childSessionId,
  5103. description: "E2E background child tool parent anchor",
  5104. parentToolCallId,
  5105. status: "running",
  5106. },
  5107. { turnId: parentTurnId },
  5108. );
  5109. log.push(SessionEventType.TurnComplete, {}, { turnId: parentTurnId });
  5110. log.push(
  5111. SessionEventType.TurnStarted,
  5112. { turnNumber: 2, input: "finish a main follow-up first" },
  5113. { turnId: followUpTurnId },
  5114. );
  5115. log.push(SessionEventType.TurnComplete, {}, { turnId: followUpTurnId });
  5116. log.push(
  5117. SessionEventType.ToolCallStarted,
  5118. {
  5119. agentId,
  5120. childSessionId,
  5121. parentToolCallId,
  5122. source: "subagent",
  5123. toolCallId: "toolu_e2e_background_parent_anchor_child_bash",
  5124. toolName: "Bash",
  5125. },
  5126. { turnId: parentTurnId },
  5127. );
  5128. const snapshot = runAll(log.events).projection.getSnapshot();
  5129. expect(snapshot.subagents.running).toEqual([
  5130. expect.objectContaining({
  5131. agentId,
  5132. childSessionId,
  5133. title: "E2E background child tool parent anchor",
  5134. }),
  5135. ]);
  5136. });
  5137. it("tool 输入流到一半被 stop(cancelled 收口,inputStreaming 不悬挂)", () => {
  5138. const turnId = "turn-1";
  5139. const log = new EventLog();
  5140. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5141. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  5142. log.push(
  5143. SessionEventType.ModelStreaming,
  5144. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-1", toolName: "bash" },
  5145. { turnId },
  5146. );
  5147. log.push(
  5148. SessionEventType.ModelStreaming,
  5149. { kind: "tool_input_delta", delta: '{"command":"rm', done: false, toolCallId: "tc-1" },
  5150. { turnId },
  5151. );
  5152. log.push(
  5153. SessionEventType.TurnComplete,
  5154. { response: "", tokenCount: 0, toolCallCount: 0, duration: 50, resultType: "cancelled" },
  5155. { turnId },
  5156. );
  5157. assertProfileConvergence(log.events);
  5158. // 收口语义本体:中断后 tool row 必须离开 inputStreaming(cancelled + 完整 inputText)。
  5159. const { projection } = runAll(log.events);
  5160. expect(
  5161. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  5162. ).toMatchObject({ status: "cancelled", inputText: '{"command":"rm' });
  5163. });
  5164. it("success turn 兜底收口缺少 terminal event 的 foreground tool", () => {
  5165. const turnId = "turn-1";
  5166. const log = new EventLog();
  5167. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5168. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "search" }, { turnId });
  5169. log.push(
  5170. SessionEventType.ModelStreaming,
  5171. {
  5172. kind: "tool_input_start",
  5173. delta: "",
  5174. done: false,
  5175. toolCallId: "tc-missing",
  5176. toolName: "GrepMissingFromRegistry",
  5177. },
  5178. { turnId },
  5179. );
  5180. log.push(
  5181. SessionEventType.ModelStreaming,
  5182. {
  5183. kind: "tool_input_delta",
  5184. delta: '{"pattern":"needle"}',
  5185. done: false,
  5186. toolCallId: "tc-missing",
  5187. },
  5188. { turnId },
  5189. );
  5190. log.push(
  5191. SessionEventType.PermissionRequested,
  5192. {
  5193. requestId: "req-missing",
  5194. toolCallId: "tc-missing",
  5195. toolName: "GrepMissingFromRegistry",
  5196. riskLevel: "low",
  5197. reason: "Search",
  5198. input: { pattern: "needle" },
  5199. },
  5200. { turnId },
  5201. );
  5202. log.push(
  5203. SessionEventType.TurnComplete,
  5204. { response: "done", tokenCount: 1, toolCallCount: 1, duration: 50, resultType: "success" },
  5205. { turnId },
  5206. );
  5207. assertProfileConvergence(log.events);
  5208. const { projection } = runAll(log.events);
  5209. expect(
  5210. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  5211. ).toMatchObject({
  5212. status: "error",
  5213. inputText: '{"pattern":"needle"}',
  5214. error: { code: "fault.runtime.toolLifecycleIncomplete" },
  5215. });
  5216. expect(projection.getSnapshot().pendingInteractions).toEqual([]);
  5217. });
  5218. it("reasoning 流式 + 中断", () => {
  5219. const turnId = "turn-1";
  5220. const log = new EventLog();
  5221. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5222. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "think" }, { turnId });
  5223. log.push(
  5224. SessionEventType.ModelStreaming,
  5225. { kind: "reasoning_start", delta: "", done: false },
  5226. { turnId },
  5227. );
  5228. log.push(
  5229. SessionEventType.ModelStreaming,
  5230. { kind: "reasoning_delta", delta: "hmm...", done: false },
  5231. { turnId },
  5232. );
  5233. log.push(
  5234. SessionEventType.ModelStreaming,
  5235. { kind: "text_start", delta: "", done: false },
  5236. { turnId },
  5237. );
  5238. log.push(
  5239. SessionEventType.ModelStreaming,
  5240. { kind: "text_delta", delta: "part", done: false },
  5241. { turnId },
  5242. );
  5243. log.push(
  5244. SessionEventType.TurnComplete,
  5245. { response: "", tokenCount: 0, toolCallCount: 0, duration: 10, resultType: "cancelled" },
  5246. { turnId },
  5247. );
  5248. assertProfileConvergence(log.events);
  5249. });
  5250. it("compact 生命周期(marker + usage 回落)", () => {
  5251. const log = new EventLog();
  5252. basicTurnEvents(log);
  5253. log.push(SessionEventType.CompactStarted, {
  5254. operationId: "op-1",
  5255. messageId: "msg-1",
  5256. status: "started",
  5257. trigger: "manual",
  5258. display: "separator",
  5259. sourceCommandId: "command-compact",
  5260. });
  5261. log.push(SessionEventType.CompactCompleted, {
  5262. operationId: "op-1",
  5263. messageId: "msg-1",
  5264. status: "completed",
  5265. trigger: "manual",
  5266. display: "separator",
  5267. preCompactTokenCount: 150,
  5268. postCompactTokenCount: 50,
  5269. });
  5270. assertProfileConvergence(log.events);
  5271. });
  5272. it("goal set → verify pass → fork → modelChange 全链路", () => {
  5273. const log = new EventLog();
  5274. basicTurnEvents(log);
  5275. log.push(SessionEventType.TargetChanged, {
  5276. action: "set",
  5277. source: "command",
  5278. target: {
  5279. sessionID: "session-1",
  5280. targetID: "target-1",
  5281. objective: "修绿",
  5282. summaryTitle: null,
  5283. status: "active",
  5284. tokenBudget: null,
  5285. tokensUsed: 0,
  5286. timeUsedSeconds: 0,
  5287. time: { created: 0, updated: 0 },
  5288. },
  5289. previousTarget: null,
  5290. });
  5291. log.push(SessionEventType.TargetCompletionVerification, {
  5292. targetId: "target-1",
  5293. status: "started",
  5294. verificationId: "verify-1",
  5295. goalIteration: 1,
  5296. });
  5297. log.push(SessionEventType.TargetCompletionVerification, {
  5298. targetId: "target-1",
  5299. status: "completed",
  5300. verificationId: "verify-1",
  5301. goalIteration: 1,
  5302. verification: { passed: true, reason: "ok" },
  5303. });
  5304. log.push(SessionEventType.SessionForked, {
  5305. originalSessionId: "session-1",
  5306. forkedSessionId: "session-child",
  5307. });
  5308. log.push(SessionEventType.ModelSelected, {
  5309. modelSelection: { providerId: "anthropic", modelId: "claude-4" },
  5310. });
  5311. log.push(SessionEventType.ModelSelected, {
  5312. modelSelection: { providerId: "openai", modelId: "gpt-6" },
  5313. });
  5314. assertProfileConvergence(log.events);
  5315. });
  5316. });
  5317. // ── G 组:compact marker ──
  5318. describe("compact marker(10 §4.4.7 / §6.4)", () => {
  5319. it("G:manual compact running→success —— 同一 marker row 状态迁移 + usage 回落", () => {
  5320. const log = new EventLog();
  5321. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  5322. log.push(SessionEventType.CompactStarted, {
  5323. operationId: "op-1",
  5324. messageId: "msg-marker",
  5325. status: "started",
  5326. trigger: "manual",
  5327. display: "separator",
  5328. sourceCommandId: "command-compact",
  5329. });
  5330. const { projection, deltasPerEvent } = runAll(log.events);
  5331. const runningMarker = projection
  5332. .getSnapshot()
  5333. .rows.window.find((row) => row.kind === "timelineMarker");
  5334. expect(runningMarker).toMatchObject({
  5335. sourceCommandId: "command-compact",
  5336. marker: { type: "compact", origin: "manual", status: "running" },
  5337. });
  5338. expect(deltasPerEvent[1]![0]!.op).toBe("row.appended");
  5339. projection.applyEvent(
  5340. new EventLog().push(SessionEventType.CompactCompleted, {
  5341. operationId: "op-1",
  5342. messageId: "msg-marker",
  5343. status: "completed",
  5344. trigger: "manual",
  5345. display: "separator",
  5346. sourceCommandId: "command-compact",
  5347. preCompactTokenCount: 100_000,
  5348. postCompactTokenCount: 30_000,
  5349. truePostCompactTokenCount: 20_000,
  5350. summaryMessageId: "msg-summary",
  5351. }),
  5352. );
  5353. const snapshot = projection.getSnapshot();
  5354. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  5355. const markers = snapshot.rows.window.filter((row) => row.kind === "timelineMarker");
  5356. // 全生命周期占同一行:终态是 upsert 不是新行。
  5357. expect(markers).toHaveLength(1);
  5358. expect(markers[0]).toMatchObject({
  5359. rowId: runningMarker?.rowId,
  5360. sourceCommandId: "command-compact",
  5361. marker: {
  5362. type: "compact",
  5363. origin: "manual",
  5364. status: "success",
  5365. tokensBefore: 100_000,
  5366. tokensAfter: 20_000,
  5367. summaryRef: "msg-summary",
  5368. },
  5369. });
  5370. // compact 成功 → context 水位立即回落(§6.4)。
  5371. expect(snapshot.usage.contextWindow?.usedTokens).toBe(20_000);
  5372. });
  5373. it("G12:auto compact 被 stop —— marker=cancelled,usage 不动", () => {
  5374. const log = new EventLog();
  5375. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5376. log.push(SessionEventType.CompactStarted, {
  5377. operationId: "op-1",
  5378. messageId: "msg-1",
  5379. status: "started",
  5380. trigger: "auto",
  5381. display: "separator",
  5382. });
  5383. log.push(SessionEventType.CompactFailed, {
  5384. operationId: "op-1",
  5385. messageId: "msg-1",
  5386. status: "interrupted",
  5387. trigger: "auto",
  5388. display: "separator",
  5389. });
  5390. const { projection } = runAll(log.events);
  5391. const snapshot = projection.getSnapshot();
  5392. expect(snapshot.rows.window.find((row) => row.kind === "timelineMarker")).toMatchObject({
  5393. marker: { type: "compact", origin: "auto", status: "cancelled" },
  5394. });
  5395. expect(snapshot.usage.contextWindow).toBeNull();
  5396. });
  5397. it("F09:compact 失败 —— marker=failed(retry 入口),会话状态不受污染", () => {
  5398. const log = new EventLog();
  5399. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5400. log.push(SessionEventType.CompactStarted, {
  5401. operationId: "op-1",
  5402. messageId: "msg-1",
  5403. status: "started",
  5404. trigger: "manual",
  5405. display: "separator",
  5406. });
  5407. log.push(SessionEventType.CompactFailed, {
  5408. operationId: "op-1",
  5409. messageId: "msg-1",
  5410. status: "failed",
  5411. trigger: "manual",
  5412. display: "separator",
  5413. reason: "api_error",
  5414. });
  5415. const { projection } = runAll(log.events);
  5416. const snapshot = projection.getSnapshot();
  5417. expect(snapshot.rows.window.find((row) => row.kind === "timelineMarker")).toMatchObject({
  5418. marker: { type: "compact", status: "failed" },
  5419. });
  5420. expect(snapshot.control.lastError).toBeNull();
  5421. });
  5422. });
  5423. // ── goal 状态机(10 §4.2.8)──
  5424. describe("goal 状态机", () => {
  5425. const goalTarget = (status: string, objective = "把测试全修绿") => ({
  5426. sessionID: "session-1",
  5427. targetID: "target-1",
  5428. objective,
  5429. summaryTitle: null,
  5430. status,
  5431. tokenBudget: null,
  5432. tokensUsed: 0,
  5433. timeUsedSeconds: 0,
  5434. time: { created: 0, updated: 0 },
  5435. });
  5436. it("goal set → stateOnly(不产 row)+ GoalState.active;verify pass → verified + 摘要锚点", () => {
  5437. const log = new EventLog();
  5438. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5439. log.push(SessionEventType.TargetChanged, {
  5440. action: "set",
  5441. source: "command",
  5442. target: goalTarget("active"),
  5443. previousTarget: null,
  5444. });
  5445. log.push(SessionEventType.TargetCompletionVerification, {
  5446. targetId: "target-1",
  5447. status: "started",
  5448. verificationId: "verify-1",
  5449. foregroundExecutionId: "foreground-1",
  5450. goalIteration: 1,
  5451. });
  5452. const { projection } = runAll(log.events);
  5453. const verifying = projection.getSnapshot();
  5454. expect(verifying.goal).toMatchObject({
  5455. objective: "把测试全修绿",
  5456. status: "verifying",
  5457. iteration: 1,
  5458. });
  5459. expect(verifying.control).toMatchObject({
  5460. phase: "running",
  5461. canStop: true,
  5462. stopState: "stoppable",
  5463. stopTargetKind: "goalVerifier",
  5464. sessionEnded: false,
  5465. });
  5466. expect(verifying.control.activeWorks).toEqual([
  5467. expect.objectContaining({
  5468. kind: "goalVerifier",
  5469. foregroundExecutionId: "foreground-1",
  5470. }),
  5471. ]);
  5472. expect(verifying.inputRouting).toEqual({
  5473. mode: "enqueue",
  5474. reasonCode: "goalVerifierAcceptsFutureInput",
  5475. });
  5476. const verifyMarker = verifying.rows.window.find(
  5477. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  5478. );
  5479. expect(verifyMarker).toMatchObject({
  5480. marker: { type: "goalVerify", iteration: 1, outcome: "running" },
  5481. });
  5482. // S10(16-plan,2026-07-08 裁决):goalSet 是 stateOnly——不进 rows.window
  5483. //(旧实现产「渲染 null」的隐形行,污染 turn 分组),目标由 goal 面板承载。
  5484. expect(
  5485. verifying.rows.window.find(
  5486. (row) => row.kind === "timelineMarker" && row.marker.type === "goalSet",
  5487. ),
  5488. ).toBeUndefined();
  5489. projection.applyEvent(
  5490. new EventLog().push(SessionEventType.TargetCompletionVerification, {
  5491. targetId: "target-1",
  5492. status: "completed",
  5493. verificationId: "verify-1",
  5494. goalIteration: 1,
  5495. verification: { passed: true, reason: "全部通过" },
  5496. }),
  5497. );
  5498. const done = projection.getSnapshot();
  5499. expect(() => conversationSnapshotSchema.parse(done)).not.toThrow();
  5500. expect(done.goal).toMatchObject({ status: "verified", iteration: 1 });
  5501. expect(done.control).toMatchObject({
  5502. phase: "completedSuccess",
  5503. canStop: false,
  5504. stopState: "idle",
  5505. stopTargetKind: "unknown",
  5506. sessionEnded: true,
  5507. });
  5508. expect(done.control.activeWorks).toEqual([]);
  5509. expect(done.goal?.verifications).toEqual([
  5510. expect.objectContaining({
  5511. iteration: 1,
  5512. outcome: "pass",
  5513. anchorRowId: verifyMarker?.rowId,
  5514. }),
  5515. ]);
  5516. // marker 就地终态化(同 rowId)。
  5517. expect(
  5518. done.rows.window.find(
  5519. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  5520. ),
  5521. ).toMatchObject({
  5522. rowId: verifyMarker?.rowId,
  5523. marker: { outcome: "pass", detail: "全部通过" },
  5524. });
  5525. });
  5526. it("goal verifier 被 Stop 时暂停已有 future queue", () => {
  5527. const log = new EventLog();
  5528. log.push(SessionEventType.SessionCreated, {
  5529. mode: "default",
  5530. contextWindow: 1000,
  5531. });
  5532. log.push(SessionEventType.TargetChanged, {
  5533. action: "set",
  5534. source: "command",
  5535. target: goalTarget("active"),
  5536. previousTarget: null,
  5537. });
  5538. log.push(SessionEventType.TargetCompletionVerification, {
  5539. targetId: "target-1",
  5540. status: "started",
  5541. verificationId: "verify-stop",
  5542. foregroundExecutionId: "foreground-stop",
  5543. goalIteration: 1,
  5544. });
  5545. log.push(SessionEventType.TurnSteerQueued, {
  5546. pendingInputId: "queue-after-verifier",
  5547. inputId: "command-after-verifier",
  5548. input: "verifier 后继续的问题",
  5549. inputPreview: "verifier 后继续的问题",
  5550. inputSize: 13,
  5551. targetTurnId: "turn-goal",
  5552. queueLength: 1,
  5553. delivery: "queue",
  5554. });
  5555. log.push(SessionEventType.TargetCompletionVerification, {
  5556. targetId: "target-1",
  5557. status: "cancelled",
  5558. verificationId: "verify-stop",
  5559. foregroundExecutionId: "foreground-stop",
  5560. goalIteration: 1,
  5561. });
  5562. const { projection } = runAll(log.events);
  5563. const snapshot = projection.getSnapshot();
  5564. expect(snapshot.goal?.status).toBe("paused");
  5565. expect(snapshot.queue).toMatchObject({
  5566. autoDrain: false,
  5567. pauseReason: "stopped",
  5568. items: [expect.objectContaining({ queueItemId: "queue-after-verifier" })],
  5569. });
  5570. expect(snapshot.inputRouting).toEqual({
  5571. mode: "choice",
  5572. reasonCode: "heldQueueInputRequiresChoice",
  5573. });
  5574. });
  5575. it("M07j:sendQueuedNow 抢占 goal verifier 时不暂停 future queue", () => {
  5576. const log = new EventLog();
  5577. log.push(SessionEventType.SessionCreated, {
  5578. mode: "default",
  5579. contextWindow: 1000,
  5580. });
  5581. log.push(SessionEventType.TargetChanged, {
  5582. action: "set",
  5583. source: "command",
  5584. target: goalTarget("active"),
  5585. previousTarget: null,
  5586. });
  5587. log.push(SessionEventType.TargetCompletionVerification, {
  5588. targetId: "target-1",
  5589. status: "started",
  5590. verificationId: "verify-send-now",
  5591. foregroundExecutionId: "foreground-send-now",
  5592. goalIteration: 1,
  5593. });
  5594. log.push(SessionEventType.TurnSteerQueued, {
  5595. pendingInputId: "queue-send-now",
  5596. inputId: "command-send-now",
  5597. input: "立即发送的问题",
  5598. inputPreview: "立即发送的问题",
  5599. inputSize: 21,
  5600. targetTurnId: "turn-goal",
  5601. queueLength: 1,
  5602. delivery: "queue",
  5603. });
  5604. log.push(SessionEventType.TargetCompletionVerification, {
  5605. targetId: "target-1",
  5606. status: "cancelled",
  5607. verificationId: "verify-send-now",
  5608. foregroundExecutionId: "foreground-send-now",
  5609. preserveQueueAutoDrainOnCancel: true,
  5610. goalIteration: 1,
  5611. });
  5612. const { projection } = runAll(log.events);
  5613. const snapshot = projection.getSnapshot();
  5614. expect(snapshot.goal?.status).toBe("paused");
  5615. expect(snapshot.queue).toMatchObject({
  5616. autoDrain: true,
  5617. items: [expect.objectContaining({ queueItemId: "queue-send-now" })],
  5618. });
  5619. expect(snapshot.queue.pauseReason).toBeUndefined();
  5620. expect(snapshot.inputRouting.mode).toBe("startNow");
  5621. });
  5622. it("verify notSatisfied —— 有效结论与过程失败分离(goalVerificationOutcomeSeparation)", () => {
  5623. const log = new EventLog();
  5624. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5625. log.push(SessionEventType.TargetChanged, {
  5626. action: "set",
  5627. source: "command",
  5628. target: goalTarget("active"),
  5629. });
  5630. log.push(SessionEventType.TargetCompletionVerification, {
  5631. targetId: "target-1",
  5632. status: "started",
  5633. verificationId: "verify-1",
  5634. goalIteration: 1,
  5635. });
  5636. log.push(SessionEventType.TargetCompletionVerification, {
  5637. targetId: "target-1",
  5638. status: "completed",
  5639. verificationId: "verify-1",
  5640. goalIteration: 1,
  5641. verification: { passed: false, reason: "还有 2 个用例红" },
  5642. });
  5643. const { projection } = runAll(log.events);
  5644. expect(projection.getSnapshot().goal).toMatchObject({ status: "notSatisfied" });
  5645. expect(projection.getSnapshot().goal?.verifications[0]).toMatchObject({
  5646. outcome: "notSatisfied",
  5647. });
  5648. });
  5649. it("H13-H16:投影 target 计时/标题、verifier action 与逐轮 Todo 状态", () => {
  5650. const log = new EventLog();
  5651. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5652. log.push(SessionEventType.TargetChanged, {
  5653. action: "set",
  5654. source: "command",
  5655. target: {
  5656. ...goalTarget("active"),
  5657. summaryTitle: "第一轮:恢复摘要",
  5658. timeUsedSeconds: 7,
  5659. activeRunStartedAtMs: 1_700_000_001_000,
  5660. },
  5661. });
  5662. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "first" }, { turnId: "turn-1" });
  5663. log.push(
  5664. SessionEventType.ToolCallScheduled,
  5665. {
  5666. toolCallId: "todo-1",
  5667. toolName: "TodoWrite",
  5668. input: {
  5669. todos: [{ content: "恢复计时", status: "completed", priority: "high" }],
  5670. },
  5671. schedule: { parallelGroups: [["todo-1"]], executionOrder: ["todo-1"] },
  5672. },
  5673. { turnId: "turn-1" },
  5674. );
  5675. log.push(
  5676. SessionEventType.TurnComplete,
  5677. { response: "done", tokenCount: 1, toolCallCount: 1, duration: 1, resultType: "success" },
  5678. { turnId: "turn-1" },
  5679. );
  5680. log.push(SessionEventType.TargetCompletionVerification, {
  5681. targetId: "target-1",
  5682. status: "started",
  5683. verificationId: "verify-1",
  5684. goalIteration: 1,
  5685. });
  5686. log.push(SessionEventType.TargetCompletionVerification, {
  5687. targetId: "target-1",
  5688. status: "completed",
  5689. verificationId: "verify-1",
  5690. goalIteration: 1,
  5691. verification: {
  5692. passed: false,
  5693. reason: "还缺暂停状态",
  5694. nextAction: "第二轮:补暂停和完成态",
  5695. },
  5696. });
  5697. log.push(SessionEventType.TargetChanged, {
  5698. action: "run_started",
  5699. source: "runtime",
  5700. target: {
  5701. ...goalTarget("active"),
  5702. summaryTitle: "第一轮:恢复摘要",
  5703. timeUsedSeconds: 11,
  5704. activeRunStartedAtMs: 1_700_000_009_000,
  5705. },
  5706. });
  5707. log.push(
  5708. SessionEventType.TurnStarted,
  5709. { turnNumber: 2, input: "second" },
  5710. { turnId: "turn-2" },
  5711. );
  5712. log.push(
  5713. SessionEventType.ToolCallScheduled,
  5714. {
  5715. toolCallId: "todo-2",
  5716. toolName: "todo_write",
  5717. input: {
  5718. todos: [
  5719. { content: "恢复暂停按钮", status: "in_progress", priority: "high" },
  5720. { content: "恢复完成图标", status: "pending", priority: "medium" },
  5721. ],
  5722. },
  5723. schedule: { parallelGroups: [["todo-2"]], executionOrder: ["todo-2"] },
  5724. },
  5725. { turnId: "turn-2" },
  5726. );
  5727. const { projection } = runAll(log.events);
  5728. const snapshot = projection.getSnapshot();
  5729. expect(snapshot.goal).toMatchObject({
  5730. targetId: "target-1",
  5731. summaryTitle: "第一轮:恢复摘要",
  5732. timeUsedSeconds: 11,
  5733. activeRunStartedAtMs: 1_700_000_009_000,
  5734. status: "active",
  5735. iteration: 1,
  5736. verifications: [
  5737. expect.objectContaining({
  5738. iteration: 1,
  5739. outcome: "notSatisfied",
  5740. reason: "还缺暂停状态",
  5741. nextAction: "第二轮:补暂停和完成态",
  5742. }),
  5743. ],
  5744. iterations: [
  5745. expect.objectContaining({
  5746. iteration: 1,
  5747. items: [expect.objectContaining({ content: "恢复计时", status: "completed" })],
  5748. }),
  5749. expect.objectContaining({
  5750. iteration: 2,
  5751. items: [
  5752. expect.objectContaining({ content: "恢复暂停按钮", status: "inProgress" }),
  5753. expect.objectContaining({ content: "恢复完成图标", status: "pending" }),
  5754. ],
  5755. }),
  5756. ],
  5757. });
  5758. expect(snapshot.plan?.items).toHaveLength(2);
  5759. expect(snapshot.availability.pauseGoal).toEqual({ allowed: true });
  5760. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  5761. });
  5762. it("stopPausesActiveGoalTarget:stop(cancelled turn)把 active goal 压成 paused,resumeGoal 放行", () => {
  5763. const log = new EventLog();
  5764. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5765. log.push(SessionEventType.TargetChanged, {
  5766. action: "set",
  5767. source: "command",
  5768. target: goalTarget("active"),
  5769. });
  5770. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "go" }, { turnId: "turn-1" });
  5771. log.push(
  5772. SessionEventType.TurnComplete,
  5773. { response: "", tokenCount: 0, toolCallCount: 0, duration: 100, resultType: "cancelled" },
  5774. { turnId: "turn-1" },
  5775. );
  5776. const { projection } = runAll(log.events);
  5777. const snapshot = projection.getSnapshot();
  5778. expect(snapshot.goal).toMatchObject({ status: "paused" });
  5779. expect(snapshot.availability.resumeGoal).toEqual({ allowed: true });
  5780. });
  5781. it("verify 被 stop(cancelled)—— marker=failed(detail=cancelled),goal 回 paused,摘要不追加", () => {
  5782. const log = new EventLog();
  5783. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5784. log.push(SessionEventType.TargetChanged, {
  5785. action: "set",
  5786. source: "command",
  5787. target: goalTarget("active"),
  5788. });
  5789. log.push(SessionEventType.TargetCompletionVerification, {
  5790. targetId: "target-1",
  5791. status: "started",
  5792. verificationId: "verify-1",
  5793. goalIteration: 1,
  5794. });
  5795. log.push(SessionEventType.TargetCompletionVerification, {
  5796. targetId: "target-1",
  5797. status: "cancelled",
  5798. verificationId: "verify-1",
  5799. goalIteration: 1,
  5800. });
  5801. const { projection } = runAll(log.events);
  5802. const snapshot = projection.getSnapshot();
  5803. expect(snapshot.goal).toMatchObject({ status: "paused" });
  5804. expect(snapshot.goal?.verifications).toHaveLength(0);
  5805. expect(
  5806. snapshot.rows.window.find(
  5807. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  5808. ),
  5809. ).toMatchObject({ marker: { outcome: "failed", detail: "cancelled" } });
  5810. expect(snapshot.availability.resumeGoal).toEqual({ allowed: true });
  5811. });
  5812. it("goal cleared → GoalState=null;重复 status_updated 值未变不下发(conflation)", () => {
  5813. const log = new EventLog();
  5814. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5815. log.push(SessionEventType.TargetChanged, {
  5816. action: "set",
  5817. source: "command",
  5818. target: goalTarget("active"),
  5819. });
  5820. const { projection } = runAll(log.events);
  5821. const noop = new EventLog().push(SessionEventType.TargetChanged, {
  5822. action: "status_updated",
  5823. source: "runtime",
  5824. target: goalTarget("active"),
  5825. });
  5826. expect(projection.applyEvent(noop)).toEqual([]);
  5827. projection.applyEvent(
  5828. new EventLog().push(SessionEventType.TargetChanged, {
  5829. action: "cleared",
  5830. source: "command",
  5831. target: null,
  5832. }),
  5833. );
  5834. expect(projection.getSnapshot().goal).toBeNull();
  5835. expect(projection.getSnapshot().availability.resumeGoal).toEqual({
  5836. allowed: false,
  5837. reasonCode: "noGoalToResume",
  5838. });
  5839. });
  5840. });
  5841. // ── fork marker 与 modelChange marker ──
  5842. describe("fork / modelChange marker", () => {
  5843. it("fork:parent 时间线不显示 forkCreated(S7);child 首部 forkNotice", () => {
  5844. const parentLog = new EventLog("session-1");
  5845. basicTurnEvents(parentLog);
  5846. parentLog.push(SessionEventType.SessionForked, {
  5847. originalSessionId: "session-1",
  5848. forkedSessionId: "session-child",
  5849. targetMessageId: "msg-3",
  5850. });
  5851. const { projection: parent } = runAll(parentLog.events);
  5852. const parentSnapshot = parent.getSnapshot();
  5853. expect(() => conversationSnapshotSchema.parse(parentSnapshot)).not.toThrow();
  5854. // S7(16-plan,2026-07-08 裁决):fork 关系只在 sessions 树体现,父时间线零入侵
  5855. //(旧实现的 forkCreated 是「渲染 null」的隐形行 + nextRowId-1 近似锚点)。
  5856. expect(
  5857. parentSnapshot.rows.window.find(
  5858. (row) => row.kind === "timelineMarker" && row.marker.type === "forkCreated",
  5859. ),
  5860. ).toBeUndefined();
  5861. const childProjection = new ProductProjection("session-child", "epoch-1");
  5862. const childLog = new EventLog("session-child");
  5863. childLog.push(SessionEventType.SessionForked, {
  5864. originalSessionId: "session-1",
  5865. forkedSessionId: "session-child",
  5866. });
  5867. for (const event of childLog.events) childProjection.applyEvent(event);
  5868. expect(childProjection.getSnapshot().rows.window[0]).toMatchObject({
  5869. kind: "timelineMarker",
  5870. marker: { type: "forkNotice", parentSessionId: "session-1" },
  5871. });
  5872. });
  5873. it("modelChange(R-17 时机):marker 只在下一 turn 开始且与上一轮选型不同时产生", () => {
  5874. // 场景 1(草稿态 bug 复现,2026-07-07):turn 前任意切换选择器 → 不产 marker,
  5875. // 首轮以最终选型启动也不产(「第一次用什么模型」不构成「变化」)。
  5876. const log = new EventLog();
  5877. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5878. log.push(SessionEventType.ModelSelected, {
  5879. modelSelection: {
  5880. providerId: "anthropic",
  5881. modelId: "claude-4",
  5882. options: { reasoningLevel: "thinking" },
  5883. },
  5884. });
  5885. log.push(SessionEventType.ModelSelected, {
  5886. previousModelSelection: {
  5887. providerId: "anthropic",
  5888. modelId: "claude-4",
  5889. options: { reasoningLevel: "thinking" },
  5890. },
  5891. modelSelection: { providerId: "openai", modelId: "gpt-6" },
  5892. });
  5893. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  5894. const { projection } = runAll(log.events);
  5895. expect(projection.getSnapshot().config).toMatchObject({
  5896. provider: "openai",
  5897. model: "gpt-6",
  5898. });
  5899. expect(
  5900. projection
  5901. .getSnapshot()
  5902. .rows.window.filter(
  5903. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5904. ),
  5905. ).toHaveLength(0);
  5906. // 重复选同一配置:conflation,无 delta。
  5907. const repeat = new EventLog().push(SessionEventType.ModelSelected, {
  5908. modelSelection: { providerId: "openai", modelId: "gpt-6" },
  5909. });
  5910. expect(projection.applyEvent(repeat)).toEqual([]);
  5911. // 场景 2:turn-1 用 gpt-6,期间切换 A→B→A(净变化为零)→ turn-2 不产 marker。
  5912. projection.applyEvent(
  5913. new EventLog().push(SessionEventType.ModelSelected, {
  5914. modelSelection: { providerId: "anthropic", modelId: "claude-4" },
  5915. }),
  5916. );
  5917. projection.applyEvent(
  5918. new EventLog().push(SessionEventType.ModelSelected, {
  5919. modelSelection: { providerId: "openai", modelId: "gpt-6" },
  5920. }),
  5921. );
  5922. projection.applyEvent(
  5923. new EventLog().push(
  5924. SessionEventType.TurnStarted,
  5925. { turnNumber: 2, input: "again" },
  5926. { turnId: "turn-2" },
  5927. ),
  5928. );
  5929. expect(
  5930. projection
  5931. .getSnapshot()
  5932. .rows.window.filter(
  5933. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5934. ),
  5935. ).toHaveLength(0);
  5936. // 场景 3:切到不同选型后 turn-3 启动 → marker 落在 turnHeader 之前,
  5937. // from = 上一轮实际选型(gpt-6),to = 本轮选型(claude-4)。
  5938. projection.applyEvent(
  5939. new EventLog().push(SessionEventType.ModelSelected, {
  5940. modelSelection: { providerId: "anthropic", modelId: "claude-4" },
  5941. }),
  5942. );
  5943. projection.applyEvent(
  5944. new EventLog().push(
  5945. SessionEventType.TurnStarted,
  5946. { turnNumber: 3, input: "switch" },
  5947. { turnId: "turn-3" },
  5948. ),
  5949. );
  5950. const rows = projection.getSnapshot().rows.window;
  5951. const markerIndex = rows.findIndex(
  5952. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5953. );
  5954. expect(rows[markerIndex]).toMatchObject({
  5955. marker: {
  5956. type: "modelChange",
  5957. fromProvider: "openai",
  5958. fromModel: "gpt-6",
  5959. toProvider: "anthropic",
  5960. toModel: "claude-4",
  5961. toThought: "",
  5962. },
  5963. });
  5964. // marker 紧邻 turn-3 的 turnHeader 之前。
  5965. expect(rows[markerIndex + 1]).toMatchObject({
  5966. kind: "turnHeader",
  5967. turnId: "turn-3",
  5968. });
  5969. });
  5970. it("显式 source-less 模型边界经原子投影只在首个 turn 生成一次 marker", () => {
  5971. const log = new EventLog("child-session");
  5972. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  5973. log.push(SessionEventType.ModelSelected, {
  5974. previousModelSelection: null,
  5975. modelSelection: {
  5976. providerId: "child-provider",
  5977. modelId: "child-model",
  5978. options: { reasoningLevel: "high" },
  5979. },
  5980. });
  5981. log.push(SessionEventType.ModelSelected, {
  5982. previousModelSelection: {
  5983. providerId: "child-provider",
  5984. modelId: "child-model",
  5985. options: { reasoningLevel: "high" },
  5986. },
  5987. modelSelection: {
  5988. providerId: "child-provider",
  5989. modelId: "child-model-final",
  5990. options: { reasoningLevel: "max" },
  5991. },
  5992. });
  5993. log.push(
  5994. SessionEventType.TurnStarted,
  5995. { turnNumber: 1, input: "first child prompt" },
  5996. { turnId: "child-turn-1" },
  5997. );
  5998. log.push(
  5999. SessionEventType.TurnComplete,
  6000. {
  6001. response: "done",
  6002. tokenCount: 1,
  6003. toolCallCount: 0,
  6004. duration: 1,
  6005. resultType: "success",
  6006. },
  6007. { turnId: "child-turn-1" },
  6008. );
  6009. log.push(
  6010. SessionEventType.TurnStarted,
  6011. { turnNumber: 2, input: "second child prompt" },
  6012. { turnId: "child-turn-2" },
  6013. );
  6014. const projection = new ProductProjection("child-session", "epoch-1");
  6015. for (const event of log.events) {
  6016. expect(projection.applyEventAtomically(event, () => true)).not.toBeNull();
  6017. }
  6018. const rows = projection.getSnapshot().rows.window;
  6019. const markers = rows.filter(
  6020. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  6021. );
  6022. expect(markers).toHaveLength(1);
  6023. expect(markers[0]).toMatchObject({
  6024. turnId: "child-turn-1",
  6025. marker: {
  6026. type: "modelChange",
  6027. toProvider: "child-provider",
  6028. toModel: "child-model-final",
  6029. toThought: "max",
  6030. },
  6031. });
  6032. expect(markers[0]?.kind === "timelineMarker" ? markers[0].marker : {}).not.toHaveProperty(
  6033. "fromProvider",
  6034. );
  6035. const markerIndex = rows.indexOf(markers[0]!);
  6036. expect(rows[markerIndex + 1]).toMatchObject({
  6037. kind: "turnHeader",
  6038. turnId: "child-turn-1",
  6039. });
  6040. expect(() => conversationSnapshotSchema.parse(projection.getSnapshot())).not.toThrow();
  6041. });
  6042. it("H17:切模型后 /goal 控制输入不创建工作生命周期,只有 continuation 为 running", () => {
  6043. const log = new EventLog();
  6044. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  6045. log.push(SessionEventType.ModelSelected, {
  6046. modelSelection: { providerId: "zhipu", modelId: "glm-5.2-highspeed" },
  6047. });
  6048. log.push(
  6049. SessionEventType.TurnStarted,
  6050. { turnNumber: 1, input: "上一轮", messageId: "user-previous" },
  6051. { turnId: "turn-previous" },
  6052. );
  6053. log.push(
  6054. SessionEventType.TurnComplete,
  6055. { response: "done", tokenCount: 1, toolCallCount: 0, duration: 1000, resultType: "success" },
  6056. { turnId: "turn-previous" },
  6057. );
  6058. log.push(SessionEventType.ModelSelected, {
  6059. modelSelection: {
  6060. providerId: "deepseek",
  6061. modelId: "deepseek-v4-flash",
  6062. options: { reasoningLevel: "max" },
  6063. },
  6064. });
  6065. log.push(
  6066. SessionEventType.TurnStarted,
  6067. {
  6068. turnNumber: 2,
  6069. input: "/Goal 开发一个招投标管理系统",
  6070. messageId: "user-goal",
  6071. executionKind: "controlOnly",
  6072. intent: {
  6073. sourceCommandId: "command-goal",
  6074. queueItemId: "queue-goal",
  6075. clientId: "desktop",
  6076. kind: "sendGoalCommand",
  6077. text: "开发一个招投标管理系统",
  6078. admissionSeq: 1,
  6079. admittedAt: 1,
  6080. requestedDelivery: "startNow",
  6081. admittedDelivery: "startNow",
  6082. },
  6083. },
  6084. { turnId: "turn-goal-query" },
  6085. );
  6086. const projection = new ProductProjection("session-1", "epoch-1");
  6087. for (const event of log.events) projection.applyEvent(event);
  6088. expect(projection.getSnapshot().control).toMatchObject({
  6089. phase: "completedSuccess",
  6090. canStop: false,
  6091. activeWorks: [],
  6092. });
  6093. log.push(
  6094. SessionEventType.TurnComplete,
  6095. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  6096. { turnId: "turn-goal-query" },
  6097. );
  6098. projection.applyEvent(log.events.at(-1)!);
  6099. const goalHeader = projection
  6100. .getSnapshot()
  6101. .rows.window.find((row) => row.kind === "turnHeader" && row.turnId === "user-goal");
  6102. expect(goalHeader).toMatchObject({
  6103. kind: "turnHeader",
  6104. executionKind: "controlOnly",
  6105. state: "completedSuccess",
  6106. });
  6107. expect(goalHeader).not.toHaveProperty("activeMs");
  6108. expect(projection.getSnapshot().control).toMatchObject({
  6109. phase: "completedSuccess",
  6110. canStop: false,
  6111. activeWorks: [],
  6112. });
  6113. log.push(
  6114. SessionEventType.TurnStarted,
  6115. {
  6116. turnNumber: 3,
  6117. input: "继续执行目标",
  6118. messageId: "goal-continuation-1",
  6119. inputSource: "goal-continuation",
  6120. inputVisibility: "model-only",
  6121. },
  6122. { turnId: "turn-goal-continuation" },
  6123. );
  6124. projection.applyEvent(log.events.at(-1)!);
  6125. const snapshot = projection.getSnapshot();
  6126. expect(snapshot.control).toMatchObject({
  6127. phase: "running",
  6128. canStop: true,
  6129. activeWorks: [{ kind: "goalContinuation" }],
  6130. });
  6131. expect(
  6132. snapshot.rows.window.find(
  6133. (row) => row.kind === "turnHeader" && row.turnId === "goal-continuation-1",
  6134. ),
  6135. ).toMatchObject({ executionKind: "agent", state: "running" });
  6136. expect(
  6137. snapshot.rows.window.filter(
  6138. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  6139. ),
  6140. ).toHaveLength(1);
  6141. });
  6142. it("modelChange:仅思考深度变化不产 marker", () => {
  6143. const log = new EventLog();
  6144. log.push(SessionEventType.ModelSelected, {
  6145. modelSelection: { providerId: "default-deepseek", modelId: "deepseek-v4-flash" },
  6146. });
  6147. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "first" }, { turnId: "turn-1" });
  6148. const { projection } = runAll(log.events);
  6149. projection.applyEvent(
  6150. new EventLog().push(SessionEventType.ModelSelected, {
  6151. modelSelection: {
  6152. providerId: "default-deepseek",
  6153. modelId: "deepseek-v4-flash",
  6154. options: { reasoningLevel: "max" },
  6155. },
  6156. }),
  6157. );
  6158. projection.applyEvent(
  6159. new EventLog().push(
  6160. SessionEventType.TurnStarted,
  6161. { turnNumber: 2, input: "same model, deeper thought" },
  6162. { turnId: "turn-2" },
  6163. ),
  6164. );
  6165. expect(projection.getSnapshot().config).toMatchObject({
  6166. provider: "default-deepseek",
  6167. model: "deepseek-v4-flash",
  6168. thought: "max",
  6169. });
  6170. expect(
  6171. projection
  6172. .getSnapshot()
  6173. .rows.window.filter(
  6174. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  6175. ),
  6176. ).toHaveLength(0);
  6177. });
  6178. // ── M4:rowId → messageId 侧表(forkAssistant/editUserQuery 桥接翻译,13 §E 组前置)──
  6179. it("E:assistant 行记录 assistantMessageId,getMessageIdForRow 可翻译", () => {
  6180. const log = new EventLog();
  6181. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6182. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  6183. log.push(
  6184. SessionEventType.ModelStreaming,
  6185. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-assist-1" },
  6186. { turnId: "turn-1" },
  6187. );
  6188. log.push(
  6189. SessionEventType.ModelStreaming,
  6190. { kind: "text_delta", delta: "hello", done: false, assistantMessageId: "msg-assist-1" },
  6191. { turnId: "turn-1" },
  6192. );
  6193. log.push(
  6194. SessionEventType.ModelStreaming,
  6195. { kind: "text_end", delta: "", done: false },
  6196. { turnId: "turn-1" },
  6197. );
  6198. const { projection } = runAll(log.events);
  6199. const assistantRow = projection
  6200. .getSnapshot()
  6201. .rows.window.find((row) => row.kind === "assistantText");
  6202. expect(assistantRow).toBeDefined();
  6203. expect(projection.getMessageIdForRow(assistantRow!.rowId)).toBe("msg-assist-1");
  6204. // 非 assistant 行 / 未知 rowId → null(桥接层据此 reject,不静默兜底 fork 错点)。
  6205. expect(projection.getMessageIdForRow(9999)).toBeNull();
  6206. const turnHeaderRow = projection
  6207. .getSnapshot()
  6208. .rows.window.find((row) => row.kind === "turnHeader");
  6209. expect(projection.getMessageIdForRow(turnHeaderRow!.rowId)).toBeNull();
  6210. });
  6211. it("E:无 assistantMessageId 的流(老 provider)→ 行存在但翻译为 null", () => {
  6212. const log = new EventLog();
  6213. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6214. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  6215. log.push(
  6216. SessionEventType.ModelStreaming,
  6217. { kind: "text_start", delta: "", done: false },
  6218. { turnId: "turn-1" },
  6219. );
  6220. log.push(
  6221. SessionEventType.ModelStreaming,
  6222. { kind: "text_delta", delta: "hello", done: false },
  6223. { turnId: "turn-1" },
  6224. );
  6225. const { projection } = runAll(log.events);
  6226. const assistantRow = projection
  6227. .getSnapshot()
  6228. .rows.window.find((row) => row.kind === "assistantText");
  6229. expect(assistantRow).toBeDefined();
  6230. expect(projection.getMessageIdForRow(assistantRow!.rowId)).toBeNull();
  6231. });
  6232. it("P0:user messageId 缺失时不得用同 turn assistant anchor 冒充 canEdit target", () => {
  6233. const log = new EventLog();
  6234. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6235. log.push(
  6236. SessionEventType.TurnStarted,
  6237. { turnNumber: 1, input: "缺少持久 user id" },
  6238. { turnId: "turn-1" },
  6239. );
  6240. log.push(
  6241. SessionEventType.ModelStreaming,
  6242. {
  6243. kind: "text_start",
  6244. delta: "",
  6245. done: false,
  6246. assistantMessageId: "assistant-only-anchor",
  6247. },
  6248. { turnId: "turn-1" },
  6249. );
  6250. log.push(
  6251. SessionEventType.ModelStreaming,
  6252. { kind: "text_delta", delta: "回答", done: false },
  6253. { turnId: "turn-1" },
  6254. );
  6255. log.push(
  6256. SessionEventType.TurnComplete,
  6257. { response: "回答", tokenCount: 1, toolCallCount: 0, duration: 1, resultType: "success" },
  6258. { turnId: "turn-1" },
  6259. );
  6260. const { projection } = runAll(log.events);
  6261. const userRow = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput");
  6262. expect(userRow).toBeDefined();
  6263. expect(projection.getMessageIdForRow(userRow!.rowId)).toBeNull();
  6264. // turn rewind 仍能找到 assistant anchor,但 exact user target 不存在。
  6265. expect(projection.getTurnRewindAnchor(userRow!.rowId)).toBe("assistant-only-anchor");
  6266. expect(userRow!.actions?.canEdit).not.toBe(true);
  6267. expect(projection.isLatestEditableUserRow(userRow!.rowId)).toBe(false);
  6268. });
  6269. it("P1:legacy 身份 fallback 必须由 normalizer 留下可观测诊断", () => {
  6270. const log = new EventLog();
  6271. log.push(
  6272. SessionEventType.TurnStarted,
  6273. { turnNumber: 1, input: "legacy query" },
  6274. { turnId: "turn-legacy" },
  6275. );
  6276. const { projection } = runAll(log.events);
  6277. expect(projection.getNormalizationDiagnostics()).toEqual([
  6278. {
  6279. code: "normalizer.user.missingTranscriptMessageId",
  6280. eventId: "event-1",
  6281. },
  6282. ]);
  6283. });
  6284. it("P1/P2:live 与 cold 合成事件的 command target/actions 逐实体等价", () => {
  6285. const project = (turnId: string) => {
  6286. const log = new EventLog();
  6287. log.push(
  6288. SessionEventType.TurnStarted,
  6289. { turnNumber: 1, input: "same query", messageId: "message-user-1" },
  6290. { turnId },
  6291. );
  6292. log.push(
  6293. SessionEventType.ModelStreaming,
  6294. {
  6295. kind: "text_start",
  6296. delta: "",
  6297. done: false,
  6298. assistantMessageId: "message-assistant-1",
  6299. partId: "part-1",
  6300. },
  6301. { turnId },
  6302. );
  6303. log.push(
  6304. SessionEventType.ModelStreaming,
  6305. { kind: "text_delta", delta: "same answer", done: false, partId: "part-1" },
  6306. { turnId },
  6307. );
  6308. log.push(
  6309. SessionEventType.ModelStreaming,
  6310. { kind: "text_end", delta: "", done: false, partId: "part-1" },
  6311. { turnId },
  6312. );
  6313. log.push(
  6314. SessionEventType.TurnComplete,
  6315. {
  6316. response: "same answer",
  6317. tokenCount: 1,
  6318. toolCallCount: 0,
  6319. duration: 1,
  6320. resultType: "success",
  6321. },
  6322. { turnId },
  6323. );
  6324. return runAll(log.events).projection;
  6325. };
  6326. const live = project("runtime-turn-1");
  6327. const cold = project("hydrate-turn-1");
  6328. const semanticRows = (projection: ProductProjection) =>
  6329. projection
  6330. .getSnapshot()
  6331. .rows.window.filter((row) => row.kind === "userInput" || row.kind === "assistantText")
  6332. .map((row) => ({
  6333. kind: row.kind,
  6334. text: row.text,
  6335. productTurnId: row.turnId,
  6336. actions: row.actions,
  6337. entityId: projection.getEntityIdForRow(row.rowId),
  6338. target: projection.getMessageIdForRow(row.rowId),
  6339. }));
  6340. expect(semanticRows(cold)).toEqual(semanticRows(live));
  6341. expect(semanticRows(live).map((row) => row.productTurnId)).toEqual([
  6342. "message-user-1",
  6343. "message-user-1",
  6344. ]);
  6345. expect(live.getNormalizationDiagnostics()).toEqual([]);
  6346. expect(cold.getNormalizationDiagnostics()).toEqual([]);
  6347. });
  6348. it("P2:entity resolver 只允许当前 canEdit 的真实用户实体", () => {
  6349. const log = new EventLog();
  6350. for (const turnNumber of [1, 2]) {
  6351. const turnId = `turn-${turnNumber}`;
  6352. log.push(
  6353. SessionEventType.TurnStarted,
  6354. {
  6355. turnNumber,
  6356. input: `query ${turnNumber}`,
  6357. messageId: `message-user-${turnNumber}`,
  6358. },
  6359. { turnId },
  6360. );
  6361. log.push(
  6362. SessionEventType.TurnComplete,
  6363. {
  6364. response: "",
  6365. tokenCount: 0,
  6366. toolCallCount: 0,
  6367. duration: 1,
  6368. resultType: "success",
  6369. },
  6370. { turnId },
  6371. );
  6372. }
  6373. const { projection } = runAll(log.events);
  6374. const userRows = projection.getSnapshot().rows.window.filter((row) => row.kind === "userInput");
  6375. expect(userRows.map((row) => row.actions?.canEdit === true)).toEqual([false, true]);
  6376. expect(projection.resolveEditTargetByEntityId("message-user-1")).toBeNull();
  6377. expect(projection.resolveEditTargetByEntityId("message-user-2")).toMatchObject({
  6378. entityId: "message-user-2",
  6379. productTurnId: "message-user-2",
  6380. transcriptMessageId: "message-user-2",
  6381. });
  6382. });
  6383. it("Task3:row.actions 与 target resolver 同源并声明 edit disposition", () => {
  6384. const log = new EventLog();
  6385. log.push(
  6386. SessionEventType.TurnStarted,
  6387. { turnNumber: 1, input: "query", messageId: "message-user-1" },
  6388. { turnId: "turn-1" },
  6389. );
  6390. log.push(
  6391. SessionEventType.ModelStreaming,
  6392. {
  6393. kind: "text_start",
  6394. delta: "",
  6395. done: false,
  6396. assistantMessageId: "message-assistant-1",
  6397. },
  6398. { turnId: "turn-1" },
  6399. );
  6400. log.push(
  6401. SessionEventType.ModelStreaming,
  6402. { kind: "text_end", delta: "", done: false },
  6403. { turnId: "turn-1" },
  6404. );
  6405. log.push(
  6406. SessionEventType.TurnComplete,
  6407. {
  6408. response: "",
  6409. tokenCount: 0,
  6410. toolCallCount: 0,
  6411. duration: 1,
  6412. resultType: "success",
  6413. },
  6414. { turnId: "turn-1" },
  6415. );
  6416. const { projection } = runAll(log.events);
  6417. const userRow = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput")!;
  6418. const assistantRow = projection
  6419. .getSnapshot()
  6420. .rows.window.find((row) => row.kind === "assistantText")!;
  6421. const target = { rowId: userRow.rowId, entityId: "message-user-1" };
  6422. expect(userRow.actions).toMatchObject({
  6423. canEdit: true,
  6424. editDisposition: "rewind",
  6425. });
  6426. expect(assistantRow.actions).toMatchObject({
  6427. canFork: true,
  6428. canRetry: true,
  6429. });
  6430. expect(projection.resolveRowActionTarget(target, "editUserQuery")).toMatchObject({
  6431. ok: true,
  6432. action: "editUserQuery",
  6433. editTarget: { transcriptMessageId: "message-user-1" },
  6434. });
  6435. expect(
  6436. projection.resolveRowActionTarget(
  6437. { rowId: userRow.rowId, entityId: "reused-for-another-entity" },
  6438. "editUserQuery",
  6439. ),
  6440. ).toEqual({ ok: false, status: "stale", reasonCode: "proto.staleTarget" });
  6441. expect(projection.resolveRowActionTarget(target, "retryTurn")).toEqual({
  6442. ok: false,
  6443. status: "rejected",
  6444. reasonCode: "guard.actionUnavailable",
  6445. });
  6446. projection.applyEvent(
  6447. new EventLog().push(SessionEventType.CompactStarted, {
  6448. operationId: "compact-1",
  6449. messageId: "compact-message",
  6450. status: "started",
  6451. trigger: "manual",
  6452. display: "separator",
  6453. }),
  6454. );
  6455. const lockedRow = projection
  6456. .getSnapshot()
  6457. .rows.window.find((row) => row.rowId === userRow.rowId)!;
  6458. const lockedAssistantRow = projection
  6459. .getSnapshot()
  6460. .rows.window.find((row) => row.rowId === assistantRow.rowId)!;
  6461. expect(lockedRow.actions?.canEdit).toBeUndefined();
  6462. // compact 锁在 availability.fork,不写进行级 canFork(02-projection「会话锁与行级资格」)。
  6463. expect(lockedAssistantRow.actions?.canFork).toBe(true);
  6464. expect(projection.getSnapshot().availability.fork).toEqual({
  6465. allowed: false,
  6466. reasonCode: "compactOperationLock",
  6467. });
  6468. expect(
  6469. projection.resolveRowActionTarget(
  6470. { rowId: assistantRow.rowId, entityId: assistantRow.entityId! },
  6471. "forkAssistant",
  6472. ),
  6473. ).toEqual({ ok: false, status: "rejected", reasonCode: "guard.actionUnavailable" });
  6474. expect(lockedAssistantRow.actions?.canRetry).toBeUndefined();
  6475. expect(projection.getSnapshot().availability.sendQueuedNow).toEqual({
  6476. allowed: false,
  6477. reasonCode: "compactOperationLock",
  6478. });
  6479. projection.applyEvent(
  6480. new EventLog().push(SessionEventType.CompactCompleted, {
  6481. operationId: "compact-1",
  6482. messageId: "compact-message",
  6483. status: "completed",
  6484. trigger: "manual",
  6485. display: "separator",
  6486. tailStartMessageId: "message-user-1",
  6487. }),
  6488. );
  6489. const compactedRow = projection
  6490. .getSnapshot()
  6491. .rows.window.find((row) => row.rowId === userRow.rowId)!;
  6492. expect(compactedRow.actions).toMatchObject({
  6493. canEdit: true,
  6494. editDisposition: "rewind",
  6495. });
  6496. expect(projection.resolveRowActionTarget(target, "editUserQuery")).toMatchObject({
  6497. ok: true,
  6498. action: "editUserQuery",
  6499. editTarget: { coveredByStableCompact: true },
  6500. });
  6501. });
  6502. it("root review:primary/goal continuation/verifier running 时 retry 与 file rewind 同源禁用", () => {
  6503. const completedProjection = () => {
  6504. const log = new EventLog();
  6505. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6506. log.push(
  6507. SessionEventType.TurnStarted,
  6508. { turnNumber: 1, input: "改文件", messageId: "message-user-base" },
  6509. { turnId: "turn-base" },
  6510. );
  6511. log.push(
  6512. SessionEventType.ModelStreaming,
  6513. {
  6514. kind: "text_start",
  6515. delta: "",
  6516. done: false,
  6517. assistantMessageId: "message-assistant-base",
  6518. },
  6519. { turnId: "turn-base" },
  6520. );
  6521. log.push(
  6522. SessionEventType.ModelStreaming,
  6523. { kind: "text_delta", delta: "done", done: false },
  6524. { turnId: "turn-base" },
  6525. );
  6526. log.push(
  6527. SessionEventType.ModelComplete,
  6528. {
  6529. content: "done",
  6530. stopReason: "stop",
  6531. querySource: "main_turn",
  6532. contextWindow: 200_000,
  6533. usage: { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 },
  6534. fileChanges: {
  6535. files: 1,
  6536. additions: 2,
  6537. deletions: 1,
  6538. items: [{ path: "/work/a.ts", additions: 2, deletions: 1, writeCount: 1 }],
  6539. },
  6540. },
  6541. { turnId: "turn-base" },
  6542. );
  6543. log.push(
  6544. SessionEventType.TurnComplete,
  6545. { response: "done", tokenCount: 2, toolCallCount: 0, duration: 1, resultType: "success" },
  6546. { turnId: "turn-base" },
  6547. );
  6548. return runAll(log.events).projection;
  6549. };
  6550. const contexts = [
  6551. {
  6552. kind: "primaryTurn",
  6553. event: () =>
  6554. new EventLog().push(
  6555. SessionEventType.TurnStarted,
  6556. { turnNumber: 2, input: "next", messageId: "message-user-next" },
  6557. { turnId: "turn-next" },
  6558. ),
  6559. },
  6560. {
  6561. kind: "goalContinuation",
  6562. event: () =>
  6563. new EventLog().push(
  6564. SessionEventType.TurnStarted,
  6565. {
  6566. turnNumber: 2,
  6567. input: "continue",
  6568. inputSource: "goal-continuation",
  6569. inputVisibility: "model-only",
  6570. },
  6571. { turnId: "turn-goal-continuation" },
  6572. ),
  6573. },
  6574. {
  6575. kind: "goalVerifier",
  6576. event: () =>
  6577. new EventLog().push(SessionEventType.TargetCompletionVerification, {
  6578. targetId: "target-1",
  6579. status: "started",
  6580. verificationId: "verify-1",
  6581. goalIteration: 1,
  6582. }),
  6583. },
  6584. ] as const;
  6585. for (const context of contexts) {
  6586. const projection = completedProjection();
  6587. const base = projection.getSnapshot();
  6588. const header = base.rows.window.find((row) => row.kind === "turnHeader")!;
  6589. const assistant = base.rows.window.find((row) => row.kind === "assistantText")!;
  6590. const headerTarget = { rowId: header.rowId, entityId: header.entityId! };
  6591. const assistantTarget = { rowId: assistant.rowId, entityId: assistant.entityId! };
  6592. projection.applyEvent(context.event());
  6593. const running = projection.getSnapshot();
  6594. const lockedHeader = running.rows.window.find((row) => row.rowId === header.rowId)!;
  6595. const lockedAssistant = running.rows.window.find((row) => row.rowId === assistant.rowId)!;
  6596. expect(running.control.activeWorks.some((work) => work.kind === context.kind)).toBe(true);
  6597. expect(lockedHeader.actions?.canRewindFiles, context.kind).toBe(true);
  6598. expect(running.availability.rewindFiles, context.kind).toEqual({
  6599. allowed: false,
  6600. reasonCode: "fileRewindUnavailable",
  6601. });
  6602. expect(lockedAssistant.actions?.canRetry, context.kind).toBeUndefined();
  6603. expect(lockedAssistant.actions?.canFork, context.kind).toBe(true);
  6604. expect(projection.resolveRowActionTarget(headerTarget, "applyFileRewind")).toMatchObject({
  6605. ok: false,
  6606. reasonCode: "guard.actionUnavailable",
  6607. });
  6608. expect(projection.resolveRowActionTarget(assistantTarget, "retryTurn")).toMatchObject({
  6609. ok: false,
  6610. reasonCode: "guard.actionUnavailable",
  6611. });
  6612. expect(projection.resolveRowActionTarget(assistantTarget, "forkAssistant")).toMatchObject({
  6613. ok: true,
  6614. });
  6615. }
  6616. });
  6617. // ── composer 编辑态冻结:锁进入投影,同 id 重入 queued 不解锁,释放事件解锁 ──
  6618. it("TurnSteerEditLockChanged:锁投影到 queue item,重入 queued 保留锁,释放后移除", () => {
  6619. const log = new EventLog();
  6620. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6621. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6622. const queued = {
  6623. pendingInputId: "q1",
  6624. input: "第一条",
  6625. inputPreview: "第一条",
  6626. inputSize: 9,
  6627. queueLength: 1,
  6628. targetTurnId: "t1",
  6629. };
  6630. log.push(SessionEventType.TurnSteerQueued, queued, { turnId: "t1" });
  6631. const lock = { editorId: "editor-a", clientId: "desktop", inputOrigin: "desktop" };
  6632. log.push(
  6633. SessionEventType.TurnSteerEditLockChanged,
  6634. { pendingInputId: "q1", targetTurnId: "t1", editLock: lock },
  6635. { turnId: "t1" },
  6636. );
  6637. const locked = runAll(log.events).projection.getSnapshot();
  6638. expect(locked.queue.items[0]?.editLock).toEqual(lock);
  6639. expect(locked.inputRouting.mode).toBe("enqueue");
  6640. log.push(SessionEventType.TurnSteerQueued, { ...queued, input: "改" }, { turnId: "t1" });
  6641. expect(runAll(log.events).projection.getSnapshot().queue.items[0]?.editLock).toEqual(lock);
  6642. log.push(
  6643. SessionEventType.TurnSteerEditLockChanged,
  6644. { pendingInputId: "q1", targetTurnId: "t1" },
  6645. { turnId: "t1" },
  6646. );
  6647. const released = runAll(log.events).projection.getSnapshot();
  6648. expect(released.queue.items[0]).not.toHaveProperty("editLock");
  6649. expect(released.queue.items[0]?.text).toBe("改");
  6650. });
  6651. // ── M4:queue 单项编辑(同 id 重入 TurnSteerQueued → 原地更新保位)──
  6652. it("A/B:editQueueItem —— 同 queueItemId 重入更新文本且保位", () => {
  6653. const log = new EventLog();
  6654. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6655. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6656. // 入队两条
  6657. log.push(
  6658. SessionEventType.TurnSteerQueued,
  6659. {
  6660. pendingInputId: "q1",
  6661. input: "第一条",
  6662. inputPreview: "第一条",
  6663. inputSize: 9,
  6664. automationId: "automation-queued",
  6665. queueLength: 1,
  6666. targetTurnId: "t1",
  6667. intent: {
  6668. botGroupSource: {
  6669. provider: "feishu",
  6670. botId: "bot",
  6671. chatId: "group",
  6672. senderId: "member",
  6673. senderName: "Member",
  6674. messageId: "message",
  6675. },
  6676. sourceCommandId: "command-q1",
  6677. queueItemId: "q1",
  6678. clientId: "mobile-client",
  6679. kind: "sendText",
  6680. admissionSeq: 1,
  6681. admittedAt: 10,
  6682. requestedDelivery: "guide",
  6683. admittedDelivery: "queue",
  6684. fallbackReasonCode: "guide.attachmentsUnsupported",
  6685. attachmentRefs: [
  6686. { ref: "artifact://q1", fileName: "q1.txt", mime: "text/plain", bytes: 2 },
  6687. ],
  6688. },
  6689. },
  6690. { turnId: "t1" },
  6691. );
  6692. log.push(
  6693. SessionEventType.TurnSteerQueued,
  6694. {
  6695. pendingInputId: "q2",
  6696. input: "第二条",
  6697. inputPreview: "第二条",
  6698. inputSize: 9,
  6699. queueLength: 2,
  6700. targetTurnId: "t1",
  6701. },
  6702. { turnId: "t1" },
  6703. );
  6704. // 编辑第一条(同 id 重入)
  6705. log.push(
  6706. SessionEventType.TurnSteerQueued,
  6707. {
  6708. pendingInputId: "q1",
  6709. input: "第一条改",
  6710. inputPreview: "第一条改",
  6711. inputSize: 12,
  6712. queueLength: 2,
  6713. targetTurnId: "t1",
  6714. },
  6715. { turnId: "t1" },
  6716. );
  6717. const { projection } = runAll(log.events);
  6718. const items = projection.getSnapshot().queue.items;
  6719. // 仍 2 条,q1 在原位(index 0)且文本已更新。
  6720. expect(items.map((i) => i.queueItemId)).toEqual(["q1", "q2"]);
  6721. expect(items[0]).toMatchObject({
  6722. text: "第一条改",
  6723. automationId: "automation-queued",
  6724. botGroupSource: { senderId: "member", chatId: "group" },
  6725. sourceCommandId: "command-q1",
  6726. clientId: "mobile-client",
  6727. attachments: [{ ref: "artifact://q1" }],
  6728. delivery: {
  6729. requested: "guide",
  6730. admitted: "queue",
  6731. fallbackReasonCode: "guide.attachmentsUnsupported",
  6732. },
  6733. order: { admissionSeq: 1, queuePosition: 0 },
  6734. steer: { state: "fellBack", reasonCode: "guide.attachmentsUnsupported" },
  6735. });
  6736. expect(items[1]!.text).toBe("第二条");
  6737. });
  6738. // ── M4:queue 重排(TurnSteerReordered → 按新序重排 queue rows)──
  6739. it("A/B:reorderQueueItem —— 按 orderedPendingInputIds 重排 queue", () => {
  6740. const log = new EventLog();
  6741. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6742. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6743. for (const [id, text, len] of [
  6744. ["q1", "一", 3],
  6745. ["q2", "二", 3],
  6746. ["q3", "三", 3],
  6747. ] as const) {
  6748. log.push(
  6749. SessionEventType.TurnSteerQueued,
  6750. {
  6751. pendingInputId: id,
  6752. input: text,
  6753. inputPreview: text,
  6754. inputSize: len,
  6755. queueLength: 3,
  6756. targetTurnId: "t1",
  6757. },
  6758. { turnId: "t1" },
  6759. );
  6760. }
  6761. // 把 q3 移到 q1 之前:新序 q3, q1, q2。
  6762. log.push(
  6763. SessionEventType.TurnSteerReordered,
  6764. { orderedPendingInputIds: ["q3", "q1", "q2"], targetTurnId: "t1" },
  6765. { turnId: "t1" },
  6766. );
  6767. const { projection } = runAll(log.events);
  6768. expect(projection.getSnapshot().queue.items.map((i) => i.queueItemId)).toEqual([
  6769. "q3",
  6770. "q1",
  6771. "q2",
  6772. ]);
  6773. expect(projection.getSnapshot().queue.items.map((i) => i.order.queuePosition)).toEqual([
  6774. 0, 1, 2,
  6775. ]);
  6776. });
  6777. it("sendQueuedNow dispatch:reserved/promoting 只更新目标项且保留完整 intent", () => {
  6778. const log = new EventLog();
  6779. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6780. log.push(
  6781. SessionEventType.TurnSteerQueued,
  6782. {
  6783. pendingInputId: "q1",
  6784. input: "带附件输入",
  6785. inputPreview: "带附件输入",
  6786. inputSize: 18,
  6787. queueLength: 1,
  6788. targetTurnId: "t1",
  6789. intent: {
  6790. sourceCommandId: "source-q1",
  6791. queueItemId: "q1",
  6792. clientId: "mobile-client",
  6793. kind: "sendText",
  6794. admissionSeq: 1,
  6795. admittedAt: 10,
  6796. requestedDelivery: "queue",
  6797. admittedDelivery: "queue",
  6798. attachmentRefs: [
  6799. { ref: "artifact://q1", fileName: "q1.txt", mime: "text/plain", bytes: 2 },
  6800. ],
  6801. },
  6802. },
  6803. { turnId: "t1" },
  6804. );
  6805. log.push(SessionEventType.TurnSteerDispatchChanged, {
  6806. pendingInputId: "q1",
  6807. reservationId: "send-now-1",
  6808. state: "reserved",
  6809. targetTurnId: "t1",
  6810. });
  6811. log.push(SessionEventType.TurnSteerDispatchChanged, {
  6812. pendingInputId: "q1",
  6813. reservationId: "send-now-1",
  6814. state: "promoting",
  6815. targetTurnId: "t1",
  6816. });
  6817. const { projection } = runAll(log.events);
  6818. expect(projection.getSnapshot().queue.items[0]).toMatchObject({
  6819. sourceCommandId: "source-q1",
  6820. clientId: "mobile-client",
  6821. attachments: [{ ref: "artifact://q1" }],
  6822. dispatch: { state: "promoting", reservationId: "send-now-1" },
  6823. });
  6824. });
  6825. it("sendQueuedNow commit:SessionInputPromoted 是 queue 移除的 durable 提交信号", () => {
  6826. const log = new EventLog();
  6827. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6828. log.push(
  6829. SessionEventType.TurnSteerQueued,
  6830. {
  6831. pendingInputId: "q1",
  6832. input: "已持久化输入",
  6833. inputPreview: "已持久化输入",
  6834. inputSize: 21,
  6835. queueLength: 1,
  6836. targetTurnId: "t1",
  6837. intent: {
  6838. sourceCommandId: "source-q1",
  6839. queueItemId: "q1",
  6840. clientId: "desktop-client",
  6841. kind: "sendText",
  6842. admissionSeq: 1,
  6843. admittedAt: 10,
  6844. requestedDelivery: "queue",
  6845. admittedDelivery: "queue",
  6846. attachmentRefs: [],
  6847. },
  6848. },
  6849. { turnId: "t1" },
  6850. );
  6851. log.push(SessionEventType.TurnSteerDispatchChanged, {
  6852. pendingInputId: "q1",
  6853. reservationId: "send-now-1",
  6854. state: "promoting",
  6855. targetTurnId: "t1",
  6856. });
  6857. // startPromptTurn 已把 user message + session_input promotion 同事务提交。
  6858. // 即使后续 TurnSteerDiscarded(promoted) 丢失,投影也不能留下幽灵 queue item。
  6859. log.push(SessionEventType.SessionInputPromoted, {
  6860. pendingInputId: "q1",
  6861. sourceCommandId: "source-q1",
  6862. messageId: "message-q1",
  6863. });
  6864. const { projection } = runAll(log.events);
  6865. expect(projection.getSnapshot().queue.items).toEqual([]);
  6866. });
  6867. // ── M4:setAutoDrain(QueueAutoDrainChanged → queue.autoDrain + held 派生)──
  6868. it("A/B:setAutoDrain(false) → queue.autoDrain=false,held 时 completed+queue>0 走 choice", () => {
  6869. const log = new EventLog();
  6870. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6871. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6872. log.push(
  6873. SessionEventType.TurnSteerQueued,
  6874. {
  6875. pendingInputId: "q1",
  6876. input: "排队项",
  6877. inputPreview: "排队项",
  6878. inputSize: 9,
  6879. queueLength: 1,
  6880. targetTurnId: "t1",
  6881. },
  6882. { turnId: "t1" },
  6883. );
  6884. // 关闭 autoDrain(保留队列)
  6885. log.push(SessionEventType.QueueAutoDrainChanged, { autoDrain: false });
  6886. // turn 结束 → completed + queue>0 + autoDrain=false → 输入路由为 choice
  6887. log.push(
  6888. SessionEventType.TurnComplete,
  6889. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  6890. { turnId: "t1" },
  6891. );
  6892. const { projection } = runAll(log.events);
  6893. const snapshot = projection.getSnapshot();
  6894. expect(snapshot.queue.autoDrain).toBe(false);
  6895. expect(snapshot.queue.pauseReason).toBe("manual");
  6896. expect(snapshot.inputRouting.mode).toBe("choice");
  6897. expect(snapshot.inputRouting.reasonCode).toBe("heldQueueInputRequiresChoice");
  6898. });
  6899. it("B:Stop 保留队列时记录 stopped 原因;恢复后清除暂停原因", () => {
  6900. const log = new EventLog();
  6901. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6902. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6903. log.push(
  6904. SessionEventType.TurnSteerQueued,
  6905. {
  6906. pendingInputId: "q1",
  6907. input: "排队项",
  6908. inputPreview: "排队项",
  6909. inputSize: 9,
  6910. queueLength: 1,
  6911. targetTurnId: "t1",
  6912. },
  6913. { turnId: "t1" },
  6914. );
  6915. log.push(
  6916. SessionEventType.TurnComplete,
  6917. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "cancelled" },
  6918. { turnId: "t1" },
  6919. );
  6920. log.push(SessionEventType.QueueAutoDrainChanged, { autoDrain: true });
  6921. const projection = new ProductProjection("s1", "epoch-1");
  6922. for (const event of log.events.slice(0, -1)) projection.applyEvent(event);
  6923. expect(projection.getSnapshot().queue).toMatchObject({
  6924. autoDrain: false,
  6925. pauseReason: "stopped",
  6926. });
  6927. projection.applyEvent(log.events.at(-1)!);
  6928. expect(projection.getSnapshot().queue.autoDrain).toBe(true);
  6929. expect(projection.getSnapshot().queue.pauseReason).toBeUndefined();
  6930. });
  6931. it("M07a:sendQueuedNow 内部抢占不把 future queue 投影为 stopped", () => {
  6932. const log = new EventLog();
  6933. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6934. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6935. log.push(
  6936. SessionEventType.TurnSteerQueued,
  6937. {
  6938. pendingInputId: "q1",
  6939. input: "立即发送",
  6940. inputPreview: "立即发送",
  6941. inputSize: 12,
  6942. queueLength: 1,
  6943. targetTurnId: "t1",
  6944. },
  6945. { turnId: "t1" },
  6946. );
  6947. log.push(
  6948. SessionEventType.TurnComplete,
  6949. {
  6950. response: "",
  6951. tokenCount: 0,
  6952. toolCallCount: 0,
  6953. duration: 0,
  6954. resultType: "cancelled",
  6955. preserveQueueAutoDrainOnCancel: true,
  6956. },
  6957. { turnId: "t1" },
  6958. );
  6959. const { projection } = runAll(log.events);
  6960. const snapshot = projection.getSnapshot();
  6961. expect(snapshot.control.phase).toBe("completedInterrupted");
  6962. expect(snapshot.queue).toMatchObject({
  6963. autoDrain: true,
  6964. items: [expect.objectContaining({ queueItemId: "q1" })],
  6965. });
  6966. expect(snapshot.queue.pauseReason).toBeUndefined();
  6967. expect(snapshot.inputRouting.mode).toBe("startNow");
  6968. });
  6969. it("A/B:setAutoDrain 幂等 —— 同值不产 delta", () => {
  6970. const log = new EventLog();
  6971. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6972. // 初始 autoDrain=true,再置 true 应无变化。
  6973. log.push(SessionEventType.QueueAutoDrainChanged, { autoDrain: true });
  6974. const { projection } = runAll(log.events);
  6975. expect(projection.getSnapshot().queue.autoDrain).toBe(true);
  6976. });
  6977. // ── M4:setFollowupMode(FollowupModeChanged → running 时 enqueue vs guide)──
  6978. it("A/B:setFollowupMode(guide) → running 时输入路由为 guide", () => {
  6979. const log = new EventLog();
  6980. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6981. log.push(SessionEventType.FollowupModeChanged, { mode: "guide" });
  6982. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6983. const { projection } = runAll(log.events);
  6984. const snapshot = projection.getSnapshot();
  6985. expect(snapshot.config.followupMode).toBe("guide");
  6986. expect(snapshot.inputRouting.mode).toBe("guide");
  6987. });
  6988. it("A/B:followupMode 默认 queue —— running 时输入入队", () => {
  6989. const log = new EventLog();
  6990. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6991. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6992. const { projection } = runAll(log.events);
  6993. const snapshot = projection.getSnapshot();
  6994. expect(snapshot.config.followupMode).toBe("queue");
  6995. expect(snapshot.inputRouting.mode).toBe("enqueue");
  6996. });
  6997. // ── M5:switchCollaborationMode(SessionModeChanged → config.mode)──
  6998. it("A/B:SessionModeChanged —— config.mode 更新且 revision 前进;同值不动", () => {
  6999. const log = new EventLog();
  7000. log.push(SessionEventType.SessionCreated, { mode: "build", contextWindow: 200_000 });
  7001. log.push(SessionEventType.SessionModeChanged, {
  7002. mode: "plan",
  7003. previousMode: "build",
  7004. source: "command",
  7005. });
  7006. const { projection } = runAll(log.events);
  7007. const snapshot = projection.getSnapshot();
  7008. expect(snapshot.config.mode).toBe("plan");
  7009. const revisionAfterSwitch = snapshot.revision;
  7010. // 同值再切:无 delta,revision 不前进。
  7011. log.push(SessionEventType.SessionModeChanged, {
  7012. mode: "plan",
  7013. previousMode: "plan",
  7014. source: "command",
  7015. });
  7016. const { projection: projection2 } = runAll(log.events);
  7017. expect(projection2.getSnapshot().config.mode).toBe("plan");
  7018. expect(projection2.getSnapshot().revision).toBe(revisionAfterSwitch);
  7019. });
  7020. it("A/B:config.mode 初值 = build(draft 期无 SessionModeChanged 时的回落)", () => {
  7021. const log = new EventLog();
  7022. log.push(SessionEventType.SessionCreated, { mode: "build", contextWindow: 200_000 });
  7023. const { projection } = runAll(log.events);
  7024. expect(projection.getSnapshot().config.mode).toBe("build");
  7025. });
  7026. // ── M4:renameSession / 自动标题(SessionTitleUpdated → meta.title)──
  7027. it("A/B:SessionTitleUpdated —— generated 更新,custom 覆盖且 custom 后不被 generated 回退", () => {
  7028. const log = new EventLog();
  7029. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7030. // 初始 default
  7031. expect(runAll(log.events).projection.getSnapshot().meta.titleSource).toBe("default");
  7032. // 自动生成标题
  7033. log.push(SessionEventType.SessionTitleUpdated, {
  7034. previousTitle: "",
  7035. source: "generated",
  7036. title: "自动标题",
  7037. });
  7038. // 用户重命名(custom)
  7039. log.push(SessionEventType.SessionTitleUpdated, {
  7040. previousTitle: "自动标题",
  7041. source: "custom",
  7042. title: "我的会话",
  7043. });
  7044. // custom 后再来一次 generated —— 应被忽略(custom 粘性)
  7045. log.push(SessionEventType.SessionTitleUpdated, {
  7046. previousTitle: "我的会话",
  7047. source: "generated",
  7048. title: "又一个自动标题",
  7049. });
  7050. const meta = runAll(log.events).projection.getSnapshot().meta;
  7051. expect(meta.title).toBe("我的会话");
  7052. expect(meta.titleSource).toBe("custom");
  7053. });
  7054. it("A/B:SessionTitleUpdated —— first_input 归一为 generated", () => {
  7055. const log = new EventLog();
  7056. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7057. log.push(SessionEventType.SessionTitleUpdated, {
  7058. previousTitle: "",
  7059. source: "first_input",
  7060. title: "首条输入标题",
  7061. });
  7062. const meta = runAll(log.events).projection.getSnapshot().meta;
  7063. expect(meta.title).toBe("首条输入标题");
  7064. expect(meta.titleSource).toBe("generated");
  7065. });
  7066. // ── M4:switchModelConfig(ModelSelected → config 更新 + 中途切换 modelChange marker)──
  7067. it("A/B:ModelSelected 首次 → config 更新,无 marker(首次选型不算切换)", () => {
  7068. const log = new EventLog();
  7069. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7070. log.push(SessionEventType.ModelSelected, {
  7071. modelSelection: { providerId: "e2e-deepseek", modelId: "deepseek-v4-flash" },
  7072. supportedThoughtLevels: ["max", "high", "nothink"],
  7073. });
  7074. const { projection } = runAll(log.events);
  7075. const snapshot = projection.getSnapshot();
  7076. expect(snapshot.config.provider).toBe("e2e-deepseek");
  7077. expect(snapshot.config.model).toBe("deepseek-v4-flash");
  7078. expect(snapshot.config.thoughtLevels).toEqual(["max", "high", "nothink"]);
  7079. // 首次选型不产 modelChange marker。
  7080. expect(
  7081. snapshot.rows.window.some(
  7082. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  7083. ),
  7084. ).toBe(false);
  7085. });
  7086. it("ModelSelected 分离稀疏 Session Selection 与 effective reasoning 展示事实", () => {
  7087. const log = new EventLog();
  7088. log.push(SessionEventType.ModelSelected, {
  7089. modelSelection: { providerId: "provider-a", modelId: "model-a" },
  7090. effectiveReasoningLevel: "high",
  7091. supportedThoughtLevels: ["low", "high"],
  7092. });
  7093. const snapshot = runAll(log.events).projection.getSnapshot();
  7094. expect(snapshot.config.modelSelection).toEqual({
  7095. providerId: "provider-a",
  7096. modelId: "model-a",
  7097. });
  7098. expect(snapshot.config.thought).toBe("high");
  7099. });
  7100. it("A/B:ModelSelected 中途切换 → config 更新;marker 归 turn 开始(R-17 时机)", () => {
  7101. const log = new EventLog();
  7102. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7103. log.push(SessionEventType.ModelSelected, {
  7104. modelSelection: { providerId: "e2e-deepseek", modelId: "deepseek-v4-flash" },
  7105. supportedThoughtLevels: ["max", "high", "nothink"],
  7106. });
  7107. log.push(SessionEventType.ModelSelected, {
  7108. modelSelection: {
  7109. providerId: "e2e-deepseek",
  7110. modelId: "deepseek-v4-pro",
  7111. options: { reasoningLevel: "max" },
  7112. },
  7113. supportedThoughtLevels: ["max", "nothink"],
  7114. });
  7115. const { projection } = runAll(log.events);
  7116. const snapshot = projection.getSnapshot();
  7117. expect(snapshot.config.model).toBe("deepseek-v4-pro");
  7118. expect(snapshot.config.thought).toBe("max");
  7119. expect(snapshot.config.thoughtLevels).toEqual(["max", "nothink"]);
  7120. // R-17 时机修复(2026-07-07):切换动作本身不落 marker——尚未有 turn 使用过
  7121. // 任何模型(草稿态截图 bug:首条消息上方挂 [modelChange])。
  7122. expect(
  7123. snapshot.rows.window.some(
  7124. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  7125. ),
  7126. ).toBe(false);
  7127. });
  7128. it("I56:registry fallback 投影稳定事件与起止模型,显式切换不伪造来源", () => {
  7129. const log = new EventLog();
  7130. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7131. log.push(SessionEventType.ModelSelected, {
  7132. modelSelection: { providerId: "provider-a", modelId: "model-a" },
  7133. });
  7134. const fallbackEvent = log.push(SessionEventType.ModelSelected, {
  7135. modelSelection: {
  7136. providerId: "provider-b",
  7137. modelId: "model-b",
  7138. options: { reasoningLevel: "deep" },
  7139. },
  7140. previousModelSelection: { providerId: "provider-a", modelId: "model-a" },
  7141. origin: "registryFallback",
  7142. });
  7143. const { projection } = runAll(log.events);
  7144. expect(projection.getSnapshot().modelTransition).toEqual({
  7145. eventId: fallbackEvent.id,
  7146. origin: "registryFallback",
  7147. from: { provider: "provider-a", model: "model-a" },
  7148. to: { provider: "provider-b", model: "model-b" },
  7149. });
  7150. projection.applyEvent(
  7151. log.push(SessionEventType.ModelSelected, {
  7152. modelSelection: { providerId: "provider-c", modelId: "model-c" },
  7153. previousModelSelection: {
  7154. providerId: "provider-b",
  7155. modelId: "model-b",
  7156. options: { reasoningLevel: "deep" },
  7157. },
  7158. }),
  7159. );
  7160. expect(projection.getSnapshot().modelTransition?.eventId).toBe(fallbackEvent.id);
  7161. });
  7162. it("A/B:历史会话切换模型后立即刷新 context window 分母并保留已用量", () => {
  7163. const log = new EventLog();
  7164. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7165. log.push(
  7166. SessionEventType.TurnStarted,
  7167. { turnNumber: 1, input: "history" },
  7168. { turnId: "turn-1" },
  7169. );
  7170. log.push(
  7171. SessionEventType.ModelComplete,
  7172. {
  7173. content: "done",
  7174. stopReason: "end_turn",
  7175. querySource: "main_turn",
  7176. contextWindow: 200_000,
  7177. usage: { inputTokens: 120, outputTokens: 30 },
  7178. },
  7179. { turnId: "turn-1" },
  7180. );
  7181. const { projection } = runAll(log.events);
  7182. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  7183. usedTokens: 150,
  7184. maxTokens: 200_000,
  7185. });
  7186. projection.applyEvent(
  7187. log.push(SessionEventType.ModelSelected, {
  7188. modelSelection: {
  7189. providerId: "deepseek",
  7190. modelId: "deepseek-v4-flash",
  7191. options: { reasoningLevel: "max" },
  7192. },
  7193. supportedThoughtLevels: ["max", "high", "nothink"],
  7194. }),
  7195. );
  7196. // 旧持久化事件没有 contextWindow,重放时保持既有分母,不能清零。
  7197. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  7198. usedTokens: 150,
  7199. maxTokens: 200_000,
  7200. });
  7201. projection.applyEvent(
  7202. log.push(SessionEventType.ModelSelected, {
  7203. modelSelection: {
  7204. providerId: "deepseek",
  7205. modelId: "deepseek-v4-flash",
  7206. options: { reasoningLevel: "max" },
  7207. },
  7208. contextWindow: 1_000_000,
  7209. supportedThoughtLevels: ["max", "high", "nothink"],
  7210. }),
  7211. );
  7212. // 修复目标:模型切换事件本身就是 runtime 新能力的权威提交点;不等下一轮发送完成。
  7213. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  7214. usedTokens: 150,
  7215. maxTokens: 1_000_000,
  7216. });
  7217. projection.applyEvent(
  7218. log.push(
  7219. SessionEventType.ModelComplete,
  7220. {
  7221. content: "next",
  7222. stopReason: "end_turn",
  7223. querySource: "main_turn",
  7224. usage: { inputTokens: 160, outputTokens: 40 },
  7225. },
  7226. { turnId: "turn-2" },
  7227. ),
  7228. );
  7229. // 后续旧 adapter 未携带 contextWindow 时,也必须回退到刚切换后的新窗口。
  7230. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  7231. usedTokens: 200,
  7232. maxTokens: 1_000_000,
  7233. });
  7234. });
  7235. it("A/B:清除 context window 后持续隐藏分母并在容量恢复时保留最新已用量", () => {
  7236. const log = new EventLog();
  7237. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7238. log.push(
  7239. SessionEventType.ModelComplete,
  7240. {
  7241. content: "before clear",
  7242. stopReason: "end_turn",
  7243. querySource: "main_turn",
  7244. contextWindow: 200_000,
  7245. usage: { inputTokens: 120, outputTokens: 30 },
  7246. },
  7247. { turnId: "turn-1" },
  7248. );
  7249. const { projection } = runAll(log.events);
  7250. projection.applyEvent(
  7251. log.push(SessionEventType.ModelSelected, {
  7252. modelSelection: { providerId: "custom", modelId: "unknown-context-model" },
  7253. contextWindow: null,
  7254. }),
  7255. );
  7256. expect(projection.getSnapshot().usage.contextWindow).toBeNull();
  7257. projection.applyEvent(
  7258. log.push(
  7259. SessionEventType.ModelComplete,
  7260. {
  7261. content: "while unknown",
  7262. stopReason: "end_turn",
  7263. querySource: "main_turn",
  7264. usage: { inputTokens: 160, outputTokens: 40 },
  7265. },
  7266. { turnId: "turn-2" },
  7267. ),
  7268. );
  7269. expect(projection.getSnapshot().usage.contextWindow).toBeNull();
  7270. expect(projection.getSnapshot().usage.cumulative).toMatchObject({
  7271. inputTokens: 280,
  7272. outputTokens: 70,
  7273. });
  7274. projection.applyEvent(
  7275. log.push(SessionEventType.ModelSelected, {
  7276. modelSelection: { providerId: "custom", modelId: "unknown-context-model" },
  7277. contextWindow: 1_000_000,
  7278. }),
  7279. );
  7280. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  7281. usedTokens: 200,
  7282. maxTokens: 1_000_000,
  7283. });
  7284. });
  7285. it("A/B:显式清除窗口后 hydration seed 只恢复用量而不覆盖容量", () => {
  7286. const log = new EventLog();
  7287. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7288. log.push(SessionEventType.ModelSelected, {
  7289. modelSelection: { providerId: "custom", modelId: "unknown-context-model" },
  7290. contextWindow: null,
  7291. });
  7292. const { projection } = runAll(log.events);
  7293. projection.seedUsage({
  7294. contextWindow: {
  7295. usedTokens: 999,
  7296. maxTokens: 200_000,
  7297. autoCompactThresholdTokens: null,
  7298. },
  7299. cumulative: {
  7300. inputTokens: 700,
  7301. outputTokens: 50,
  7302. cacheReadTokens: 20,
  7303. cacheWriteTokens: 10,
  7304. },
  7305. });
  7306. expect(projection.getSnapshot().usage.contextWindow).toBeNull();
  7307. expect(projection.getSnapshot().usage.cumulative).toEqual({
  7308. inputTokens: 700,
  7309. outputTokens: 50,
  7310. cacheReadTokens: 20,
  7311. cacheWriteTokens: 10,
  7312. });
  7313. projection.applyEvent(
  7314. log.push(SessionEventType.ModelSelected, {
  7315. modelSelection: { providerId: "custom", modelId: "unknown-context-model" },
  7316. contextWindow: 1_000_000,
  7317. }),
  7318. );
  7319. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  7320. usedTokens: 999,
  7321. maxTokens: 1_000_000,
  7322. });
  7323. });
  7324. it("Todo123: 未知容量种子保留用量,后续容量恢复不归零", () => {
  7325. const log = new EventLog();
  7326. log.push(SessionEventType.SessionCreated, { mode: "default" });
  7327. const { projection } = runAll(log.events);
  7328. projection.seedUsage({
  7329. contextWindow: { usedTokens: 29908, maxTokens: null, autoCompactThresholdTokens: null },
  7330. });
  7331. expect(projection.getSnapshot().usage.contextWindow).toBeNull();
  7332. projection.applyEvent(
  7333. log.push(SessionEventType.ModelSelected, {
  7334. modelSelection: { providerId: "glm", modelId: "GLM-5.3-Flash" },
  7335. contextWindow: 1_000_000,
  7336. }),
  7337. );
  7338. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  7339. usedTokens: 29908,
  7340. maxTokens: 1_000_000,
  7341. });
  7342. });
  7343. it("Todo123: 未知容量期间真实用量优先,迟到恢复种子不能覆盖", () => {
  7344. const log = new EventLog();
  7345. log.push(SessionEventType.SessionCreated, { mode: "default" });
  7346. log.push(SessionEventType.ModelSelected, {
  7347. modelSelection: { providerId: "glm", modelId: "GLM-5.3-Flash" },
  7348. contextWindow: null,
  7349. });
  7350. log.push(SessionEventType.ModelComplete, {
  7351. content: "",
  7352. stopReason: "end_turn",
  7353. querySource: "main_turn",
  7354. usage: { inputTokens: 700, outputTokens: 30 },
  7355. });
  7356. const { projection } = runAll(log.events);
  7357. projection.seedUsage({
  7358. contextWindow: { usedTokens: 29908, maxTokens: null, autoCompactThresholdTokens: null },
  7359. });
  7360. projection.applyEvent(
  7361. log.push(SessionEventType.ModelSelected, {
  7362. modelSelection: { providerId: "glm", modelId: "GLM-5.3-Flash" },
  7363. contextWindow: 1_000_000,
  7364. }),
  7365. );
  7366. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  7367. usedTokens: 730,
  7368. maxTokens: 1_000_000,
  7369. });
  7370. });
  7371. // ── M4:cancelBackgroundWork(BackgroundTask* → backgroundWorks 投影)──
  7372. it("A/B:BackgroundTaskStarted → backgroundWorks 出现 running 项,Completed(cancelled) → cancelled", () => {
  7373. const log = new EventLog();
  7374. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7375. log.push(SessionEventType.BackgroundTaskStarted, {
  7376. taskId: "bg-1",
  7377. toolName: "Bash",
  7378. command: "sleep 100",
  7379. description: "长任务",
  7380. status: "running",
  7381. });
  7382. let snapshot = runAll(log.events).projection.getSnapshot();
  7383. expect(snapshot.backgroundWorks).toHaveLength(1);
  7384. expect(snapshot.backgroundWorks[0]!.workId).toBe("bg-1");
  7385. expect(snapshot.backgroundWorks[0]!.kind).toBe("bash");
  7386. expect(snapshot.backgroundWorks[0]!.title).toBe("长任务");
  7387. expect(snapshot.backgroundWorks[0]!.status).toBe("running");
  7388. // 取消 → cancelled
  7389. log.push(SessionEventType.BackgroundTaskCompleted, {
  7390. taskId: "bg-1",
  7391. toolName: "Bash",
  7392. status: "cancelled",
  7393. });
  7394. snapshot = runAll(log.events).projection.getSnapshot();
  7395. expect(snapshot.backgroundWorks).toHaveLength(1);
  7396. expect(snapshot.backgroundWorks[0]!.status).toBe("cancelled");
  7397. });
  7398. it("A/B:真实 Agent 后台事件使用 runtime taskKind,且旧 Agent 事件兼容为 subagent", () => {
  7399. const log = new EventLog();
  7400. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7401. log.push(SessionEventType.BackgroundTaskStarted, {
  7402. taskId: "bg-2",
  7403. toolName: "Agent",
  7404. taskKind: "subagent",
  7405. childSessionId: "sess_child_bg_2",
  7406. description: "子代理",
  7407. status: "running",
  7408. cancellable: true,
  7409. });
  7410. let snapshot = runAll(log.events).projection.getSnapshot();
  7411. expect(snapshot.backgroundWorks[0]).toMatchObject({
  7412. kind: "subagent",
  7413. childSessionId: "sess_child_bg_2",
  7414. cancellable: true,
  7415. status: "running",
  7416. title: "子代理",
  7417. });
  7418. log.push(SessionEventType.BackgroundTaskCompleted, {
  7419. taskId: "bg-2",
  7420. toolName: "Agent",
  7421. taskKind: "subagent",
  7422. status: "completed",
  7423. cancellable: false,
  7424. });
  7425. snapshot = runAll(log.events).projection.getSnapshot();
  7426. expect(snapshot.backgroundWorks[0]).toMatchObject({
  7427. kind: "subagent",
  7428. childSessionId: "sess_child_bg_2",
  7429. cancellable: false,
  7430. status: "resultPending",
  7431. });
  7432. const lateIdentity = new EventLog();
  7433. lateIdentity.push(SessionEventType.SessionCreated, {
  7434. mode: "default",
  7435. contextWindow: 200_000,
  7436. });
  7437. lateIdentity.push(SessionEventType.BackgroundTaskStarted, {
  7438. taskId: "late-child-id",
  7439. toolName: "Agent",
  7440. taskKind: "subagent",
  7441. description: "晚到身份",
  7442. status: "running",
  7443. cancellable: true,
  7444. });
  7445. lateIdentity.push(SessionEventType.BackgroundTaskUpdated, {
  7446. taskId: "late-child-id",
  7447. toolName: "Agent",
  7448. taskKind: "subagent",
  7449. childSessionId: "sess_child_late",
  7450. description: "晚到身份",
  7451. status: "running",
  7452. cancellable: true,
  7453. });
  7454. expect(runAll(lateIdentity.events).projection.getSnapshot().backgroundWorks[0]).toMatchObject({
  7455. childSessionId: "sess_child_late",
  7456. status: "running",
  7457. });
  7458. const legacy = new EventLog();
  7459. legacy.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7460. legacy.push(SessionEventType.BackgroundTaskStarted, {
  7461. taskId: "legacy-agent",
  7462. toolName: "Agent",
  7463. description: "旧子代理",
  7464. status: "running",
  7465. });
  7466. legacy.push(SessionEventType.BackgroundTaskUpdated, {
  7467. taskId: "legacy-agent",
  7468. status: "running",
  7469. });
  7470. legacy.push(SessionEventType.BackgroundTaskCompleted, {
  7471. taskId: "legacy-agent",
  7472. status: "completed",
  7473. });
  7474. expect(runAll(legacy.events).projection.getSnapshot().backgroundWorks[0]).toMatchObject({
  7475. kind: "subagent",
  7476. status: "resultPending",
  7477. title: "旧子代理",
  7478. });
  7479. const explicit = new EventLog();
  7480. explicit.push(SessionEventType.SessionCreated, {
  7481. mode: "default",
  7482. contextWindow: 200_000,
  7483. });
  7484. explicit.push(SessionEventType.BackgroundTaskStarted, {
  7485. taskId: "explicit-bash",
  7486. // taskKind 是新事实;即使旧 toolName 数据矛盾也不得反向覆盖。
  7487. taskKind: "bash",
  7488. toolName: "Agent",
  7489. description: "显式进程",
  7490. status: "running",
  7491. });
  7492. expect(runAll(explicit.events).projection.getSnapshot().backgroundWorks[0]!.kind).toBe("bash");
  7493. });
  7494. // ── M4:RewindTriggered → row.removed(editUserQuery/retryTurn 的 live 截断)──
  7495. it("D/G:RewindTriggered(targetMessageId) 从目标 turn 首行整段移除", () => {
  7496. const log = new EventLog();
  7497. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7498. // turn1
  7499. log.push(
  7500. SessionEventType.TurnStarted,
  7501. { turnNumber: 1, input: "第一问", messageId: "msg-u1" },
  7502. { turnId: "t1" },
  7503. );
  7504. log.push(
  7505. SessionEventType.ModelStreaming,
  7506. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  7507. { turnId: "t1" },
  7508. );
  7509. log.push(
  7510. SessionEventType.ModelStreaming,
  7511. { kind: "text_delta", delta: "第一答", done: false, assistantMessageId: "msg-a1" },
  7512. { turnId: "t1" },
  7513. );
  7514. log.push(
  7515. SessionEventType.ModelStreaming,
  7516. { kind: "text_end", delta: "", done: false },
  7517. { turnId: "t1" },
  7518. );
  7519. log.push(
  7520. SessionEventType.TurnComplete,
  7521. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  7522. { turnId: "t1" },
  7523. );
  7524. // turn2
  7525. log.push(
  7526. SessionEventType.TurnStarted,
  7527. { turnNumber: 2, input: "第二问", messageId: "msg-u2" },
  7528. { turnId: "t2" },
  7529. );
  7530. log.push(
  7531. SessionEventType.ModelStreaming,
  7532. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a2" },
  7533. { turnId: "t2" },
  7534. );
  7535. log.push(
  7536. SessionEventType.ModelStreaming,
  7537. { kind: "text_delta", delta: "第二答", done: false, assistantMessageId: "msg-a2" },
  7538. { turnId: "t2" },
  7539. );
  7540. log.push(
  7541. SessionEventType.ModelStreaming,
  7542. { kind: "text_end", delta: "", done: false },
  7543. { turnId: "t2" },
  7544. );
  7545. log.push(
  7546. SessionEventType.TurnComplete,
  7547. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  7548. { turnId: "t2" },
  7549. );
  7550. // rewind 到 turn2 的 assistant 消息 → 整个 turn2 被移除。
  7551. // createdMessageId = applied 语义(unavailable/workspace 回滚不带,投影必须忽略)。
  7552. log.push(SessionEventType.RewindTriggered, {
  7553. targetMessageId: "msg-a2",
  7554. scope: "conversation",
  7555. createdMessageId: "msg-rewind-notice",
  7556. });
  7557. const { projection } = runAll(log.events);
  7558. const texts = projection
  7559. .getSnapshot()
  7560. .rows.window.filter((r) => r.kind === "userInput" || r.kind === "assistantText")
  7561. .map((r) => (r.kind === "userInput" || r.kind === "assistantText" ? r.text : ""));
  7562. // turn1 保留,turn2 整段被移除。
  7563. expect(texts).toEqual(["第一问", "第一答"]);
  7564. // 被移除的用户实体不可再解析为编辑目标。
  7565. expect(projection.resolveEditTargetByEntityId("msg-u2")).toBeNull();
  7566. expect(projection.resolveEditTargetByEntityId("msg-u1")).toMatchObject({
  7567. entityId: "msg-u1",
  7568. transcriptMessageId: "msg-u1",
  7569. });
  7570. });
  7571. it("PV4-10 回归:首轮 edit rewind 后分页首行切换到新 active branch", () => {
  7572. const log = new EventLog();
  7573. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7574. log.push(
  7575. SessionEventType.TurnStarted,
  7576. { turnNumber: 1, input: "你好", messageId: "msg-u1" },
  7577. { turnId: "t1" },
  7578. );
  7579. log.push(
  7580. SessionEventType.ModelStreaming,
  7581. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  7582. { turnId: "t1" },
  7583. );
  7584. log.push(
  7585. SessionEventType.ModelStreaming,
  7586. { kind: "text_delta", delta: "旧回答", done: false, assistantMessageId: "msg-a1" },
  7587. { turnId: "t1" },
  7588. );
  7589. log.push(
  7590. SessionEventType.ModelStreaming,
  7591. { kind: "text_end", delta: "", done: false },
  7592. { turnId: "t1" },
  7593. );
  7594. log.push(
  7595. SessionEventType.TurnComplete,
  7596. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  7597. { turnId: "t1" },
  7598. );
  7599. const original = runAll(log.events).projection.getSnapshot();
  7600. const originalMaxRowId = Math.max(...original.rows.window.map((row) => row.rowId));
  7601. log.push(SessionEventType.RewindTriggered, {
  7602. targetMessageId: "msg-u1",
  7603. scope: "conversation",
  7604. branchCutAfterMessageId: "msg-a1",
  7605. branchGeneration: 1,
  7606. });
  7607. const rewound = runAll(log.events).projection.getSnapshot();
  7608. expect(rewound.rows).toEqual({ window: [], totalCount: 0, firstRowId: null });
  7609. log.push(
  7610. SessionEventType.TurnStarted,
  7611. { turnNumber: 2, input: "你是谁", messageId: "msg-u2" },
  7612. { turnId: "t2" },
  7613. );
  7614. const rerun = runAll(log.events).projection.getSnapshot();
  7615. const newFirstRow = rerun.rows.window[0]!;
  7616. expect(newFirstRow.rowId).toBeGreaterThan(originalMaxRowId);
  7617. expect(rerun.rows.firstRowId).toBe(newFirstRow.rowId);
  7618. expect(rerun.rows.totalCount).toBe(rerun.rows.window.length);
  7619. });
  7620. it("D:getTurnRewindAnchor(user 行 rowId) → 同 turn 的 assistant messageId", () => {
  7621. const log = new EventLog();
  7622. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7623. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "问" }, { turnId: "t1" });
  7624. log.push(
  7625. SessionEventType.ModelStreaming,
  7626. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  7627. { turnId: "t1" },
  7628. );
  7629. log.push(
  7630. SessionEventType.ModelStreaming,
  7631. { kind: "text_delta", delta: "答", done: false, assistantMessageId: "msg-a1" },
  7632. { turnId: "t1" },
  7633. );
  7634. log.push(
  7635. SessionEventType.ModelStreaming,
  7636. { kind: "text_end", delta: "", done: false },
  7637. { turnId: "t1" },
  7638. );
  7639. const { projection } = runAll(log.events);
  7640. const userRow = projection.getSnapshot().rows.window.find((r) => r.kind === "userInput");
  7641. expect(userRow).toBeDefined();
  7642. // user 行自身无 messageId,但同 turn 的 assistant messageId 作 rewind 锚点。
  7643. expect(projection.getMessageIdForRow(userRow!.rowId)).toBeNull();
  7644. expect(projection.getTurnRewindAnchor(userRow!.rowId)).toBe("msg-a1");
  7645. });
  7646. it("D/G:RewindTriggered 目标 messageId 无法反查(user 行无 messageId)→ 不误删", () => {
  7647. const log = new EventLog();
  7648. basicTurnEvents(log);
  7649. const before = runAll(log.events).projection.getSnapshot().rows.window.length;
  7650. log.push(SessionEventType.RewindTriggered, {
  7651. targetMessageId: "unknown-msg",
  7652. scope: "conversation",
  7653. createdMessageId: "msg-rewind-notice",
  7654. });
  7655. const after = runAll(log.events).projection.getSnapshot().rows.window.length;
  7656. expect(after).toBe(before);
  7657. });
  7658. it("D/E09 回归:unavailable rewind(无 createdMessageId)与 workspace 回滚不得截断 live 行", () => {
  7659. // Bugfix 回归(2026-07-06 case catalog 战役):finishUnavailable 也发 RewindTriggered,
  7660. // 投影曾不加区分地截断 live 行——store/模型上下文却保留旧分支(假截断),
  7661. // fork child / 刷新 hydration 随后把旧分支复活(E09 失败形态)。
  7662. const log = new EventLog();
  7663. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7664. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "问" }, { turnId: "t1" });
  7665. log.push(
  7666. SessionEventType.ModelStreaming,
  7667. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  7668. { turnId: "t1" },
  7669. );
  7670. log.push(
  7671. SessionEventType.ModelStreaming,
  7672. { kind: "text_delta", delta: "答", done: false, assistantMessageId: "msg-a1" },
  7673. { turnId: "t1" },
  7674. );
  7675. log.push(
  7676. SessionEventType.ModelStreaming,
  7677. { kind: "text_end", delta: "", done: false },
  7678. { turnId: "t1" },
  7679. );
  7680. log.push(
  7681. SessionEventType.TurnComplete,
  7682. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  7683. { turnId: "t1" },
  7684. );
  7685. const beforeRows = runAll(log.events).projection.getSnapshot().rows.window.length;
  7686. expect(beforeRows).toBeGreaterThan(0);
  7687. // unavailable conversation rewind(无 createdMessageId)
  7688. log.push(SessionEventType.RewindTriggered, {
  7689. targetMessageId: "msg-a1",
  7690. scope: "conversation",
  7691. strategy: "unavailable",
  7692. reason: "target_message_is_not_user_prompt",
  7693. });
  7694. // workspace 文件回滚(带 createdMessageId 但 scope=workspace)
  7695. log.push(SessionEventType.RewindTriggered, {
  7696. targetMessageId: "msg-a1",
  7697. scope: "workspace",
  7698. createdMessageId: "msg-ws-notice",
  7699. });
  7700. const after = runAll(log.events).projection.getSnapshot().rows.window.length;
  7701. expect(after).toBe(beforeRows);
  7702. });
  7703. it("O10:ModelComplete.fileChanges 更新 turn header 摘要", () => {
  7704. const log = new EventLog();
  7705. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7706. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "改文件" }, { turnId: "t1" });
  7707. log.push(
  7708. SessionEventType.ModelComplete,
  7709. {
  7710. content: "done",
  7711. stopReason: "stop",
  7712. querySource: "main_turn",
  7713. contextWindow: 200_000,
  7714. usage: { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 },
  7715. fileChanges: {
  7716. files: 1,
  7717. additions: 2,
  7718. deletions: 1,
  7719. items: [{ path: "/work/src/demo.ts", additions: 2, deletions: 1, writeCount: 2 }],
  7720. },
  7721. },
  7722. { turnId: "t1" },
  7723. );
  7724. log.push(
  7725. SessionEventType.TurnComplete,
  7726. { response: "done", tokenCount: 2, toolCallCount: 0, duration: 1, resultType: "success" },
  7727. { turnId: "t1" },
  7728. );
  7729. const { projection } = runAll(log.events);
  7730. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  7731. expect(header).toMatchObject({
  7732. kind: "turnHeader",
  7733. fileChanges: {
  7734. additions: 2,
  7735. deletions: 1,
  7736. files: 1,
  7737. state: "active",
  7738. },
  7739. actions: { canRewindFiles: true },
  7740. });
  7741. const target = { rowId: header!.rowId, entityId: header!.entityId! };
  7742. expect(projection.resolveRowActionTarget(target, "applyFileRewind")).toMatchObject({
  7743. ok: true,
  7744. });
  7745. projection.applyEvent(
  7746. new EventLog().push(SessionEventType.CompactStarted, {
  7747. operationId: "compact-files",
  7748. messageId: "compact-files-message",
  7749. status: "started",
  7750. trigger: "manual",
  7751. display: "separator",
  7752. }),
  7753. );
  7754. const lockedHeader = projection
  7755. .getSnapshot()
  7756. .rows.window.find((row) => row.rowId === header!.rowId)!;
  7757. expect(lockedHeader.actions?.canRewindFiles).toBe(true);
  7758. expect(projection.getSnapshot().availability.rewindFiles).toEqual({
  7759. allowed: false,
  7760. reasonCode: "compactOperationLock",
  7761. });
  7762. expect(projection.resolveRowActionTarget(target, "applyFileRewind")).toEqual({
  7763. ok: false,
  7764. status: "rejected",
  7765. reasonCode: "guard.actionUnavailable",
  7766. });
  7767. });
  7768. it("O10:subagent ModelComplete 只更新 child turn 文件摘要,不覆盖 usage", () => {
  7769. const log = new EventLog();
  7770. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7771. log.push(
  7772. SessionEventType.TurnStarted,
  7773. { turnNumber: 1, input: "子会话改文件" },
  7774. { turnId: "t1" },
  7775. );
  7776. log.push(
  7777. SessionEventType.ModelComplete,
  7778. {
  7779. content: "done",
  7780. stopReason: "stop",
  7781. querySource: "subagent",
  7782. contextWindow: 999_999,
  7783. usage: { inputTokens: 100, outputTokens: 50, cacheReadTokens: 10, cacheWriteTokens: 5 },
  7784. fileChanges: {
  7785. files: 1,
  7786. additions: 1,
  7787. deletions: 0,
  7788. items: [{ path: "/work/src/child.ts", additions: 1, deletions: 0, writeCount: 1 }],
  7789. },
  7790. },
  7791. { turnId: "t1" },
  7792. );
  7793. log.push(
  7794. SessionEventType.TurnComplete,
  7795. { response: "done", tokenCount: 150, toolCallCount: 1, duration: 1, resultType: "success" },
  7796. { turnId: "t1" },
  7797. );
  7798. const { projection } = runAll(log.events);
  7799. const snapshot = projection.getSnapshot();
  7800. const header = snapshot.rows.window.find((row) => row.kind === "turnHeader");
  7801. expect(header).toMatchObject({
  7802. kind: "turnHeader",
  7803. fileChanges: {
  7804. additions: 1,
  7805. deletions: 0,
  7806. files: 1,
  7807. state: "active",
  7808. },
  7809. actions: { canRewindFiles: true },
  7810. });
  7811. expect(snapshot.usage.cumulative).toEqual({
  7812. inputTokens: 0,
  7813. outputTokens: 0,
  7814. cacheReadTokens: 0,
  7815. cacheWriteTokens: 0,
  7816. });
  7817. });
  7818. it("O10:普通 TurnStarted 的 user messageId 进入同轮文件摘要锚点", () => {
  7819. const log = new EventLog();
  7820. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7821. log.push(
  7822. SessionEventType.TurnStarted,
  7823. { turnNumber: 1, input: "改文件", messageId: "msg-user-1" },
  7824. { turnId: "t1" },
  7825. );
  7826. const { projection } = runAll(log.events);
  7827. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  7828. expect(header).toBeDefined();
  7829. expect(projection.getMessageIdsForTurnRow(header!.rowId)).toContain("msg-user-1");
  7830. });
  7831. it("O12:workspace 文件撤销只标记 fileChanges.reverted,不移除聊天行", () => {
  7832. const log = new EventLog();
  7833. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7834. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "改文件" }, { turnId: "t1" });
  7835. log.push(
  7836. SessionEventType.ModelStreaming,
  7837. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  7838. { turnId: "t1" },
  7839. );
  7840. log.push(
  7841. SessionEventType.ModelStreaming,
  7842. { kind: "text_delta", delta: "已改", done: false, assistantMessageId: "msg-a1" },
  7843. { turnId: "t1" },
  7844. );
  7845. log.push(
  7846. SessionEventType.ModelStreaming,
  7847. { kind: "text_end", delta: "", done: false },
  7848. { turnId: "t1" },
  7849. );
  7850. log.push(
  7851. SessionEventType.ModelComplete,
  7852. {
  7853. content: "已改",
  7854. stopReason: "stop",
  7855. querySource: "main_turn",
  7856. contextWindow: 200_000,
  7857. usage: { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 },
  7858. fileChanges: {
  7859. files: 1,
  7860. additions: 2,
  7861. deletions: 1,
  7862. items: [{ path: "/work/src/demo.ts", additions: 2, deletions: 1, writeCount: 1 }],
  7863. },
  7864. },
  7865. { turnId: "t1" },
  7866. );
  7867. log.push(
  7868. SessionEventType.TurnComplete,
  7869. { response: "已改", tokenCount: 1, toolCallCount: 1, duration: 10, resultType: "success" },
  7870. { turnId: "t1" },
  7871. );
  7872. const before = runAll(log.events).projection.getSnapshot().rows.window;
  7873. log.push(SessionEventType.RewindTriggered, {
  7874. targetMessageId: "msg-a1",
  7875. scope: "workspace",
  7876. reason: "file_summary_rewind",
  7877. });
  7878. const { projection } = runAll(log.events);
  7879. const rows = projection.getSnapshot().rows.window;
  7880. expect(rows).toHaveLength(before.length);
  7881. const header = rows.find((row) => row.kind === "turnHeader");
  7882. expect(header).toMatchObject({
  7883. kind: "turnHeader",
  7884. fileChanges: {
  7885. additions: 2,
  7886. deletions: 1,
  7887. files: 1,
  7888. state: "reverted",
  7889. },
  7890. });
  7891. expect(rows.some((row) => row.kind === "assistantText" && row.text === "已改")).toBe(true);
  7892. });
  7893. });
  7894. // ── M5④ 附件渲染:TurnStarted.attachments → userInput row.attachments ──
  7895. describe("userInput 附件投影(M5④)", () => {
  7896. it("TurnStarted 携带附件元信息 → row.attachments 保真映射且 schema 合法", () => {
  7897. const log = new EventLog();
  7898. log.push(SessionEventType.SessionCreated, {
  7899. mode: "default",
  7900. contextWindow: 200_000,
  7901. });
  7902. log.push(
  7903. SessionEventType.TurnStarted,
  7904. {
  7905. turnNumber: 1,
  7906. input: "看看这张图",
  7907. inputId: "command-start-now",
  7908. intent: {
  7909. sourceCommandId: "command-start-now",
  7910. queueItemId: "queue_command-start-now",
  7911. clientId: "desktop-client",
  7912. kind: "sendText",
  7913. admissionSeq: 3,
  7914. admittedAt: 100,
  7915. requestedDelivery: "startNow",
  7916. admittedDelivery: "startNow",
  7917. },
  7918. attachments: [
  7919. {
  7920. fileName: "screenshot.png",
  7921. mime: "image/png",
  7922. bytes: 12345,
  7923. ref: "/tmp/screenshot.png",
  7924. },
  7925. // 无稳定引用(data URL 内联):ref 缺省 → 投影生成行内占位。
  7926. { fileName: "notes.md", mime: "text/markdown", bytes: 42 },
  7927. ],
  7928. },
  7929. { turnId: "turn-1" },
  7930. );
  7931. const { projection } = runAll(log.events);
  7932. const snapshot = projection.getSnapshot();
  7933. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  7934. const userInput = snapshot.rows.window.find((row) => row.kind === "userInput");
  7935. expect(userInput).toBeDefined();
  7936. expect(userInput).toMatchObject({
  7937. sourceCommandId: "command-start-now",
  7938. clientId: "desktop-client",
  7939. });
  7940. const attachments = userInput?.kind === "userInput" ? userInput.attachments : undefined;
  7941. expect(attachments).toHaveLength(2);
  7942. expect(attachments?.[0]).toEqual({
  7943. ref: "/tmp/screenshot.png",
  7944. fileName: "screenshot.png",
  7945. mime: "image/png",
  7946. bytes: 12345,
  7947. });
  7948. expect(attachments?.[1]).toMatchObject({
  7949. fileName: "notes.md",
  7950. mime: "text/markdown",
  7951. bytes: 42,
  7952. });
  7953. expect(attachments?.[1]?.ref).toMatch(/^turn-attachment\//);
  7954. });
  7955. it("无附件的 TurnStarted:row 不带 attachments 键(缺省语义)", () => {
  7956. const log = new EventLog();
  7957. basicTurnEvents(log);
  7958. const { projection } = runAll(log.events);
  7959. const userInput = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput");
  7960. expect(userInput?.kind === "userInput" ? "attachments" in userInput : null).toBe(false);
  7961. });
  7962. });
  7963. // R-19(10 §4.2.3):config 种子——投影初值 = runtime 真值,种子不产 delta / 不 bump
  7964. // revision,事件触碰过的字段不接受种子覆盖("最终值以日志为准")。
  7965. // Bug 背景(2026-07-07 v4 桌面首测):初始 config 写死空 provider/model + mode=build,
  7966. // 导致新会话模型选择器显示空、持久化 mode=yolo 时 UI 停在 build 且点 yolo 静默 no-op。
  7967. describe("config 种子(R-19)", () => {
  7968. const SEED = {
  7969. provider: "prov-a",
  7970. model: "model-1",
  7971. thought: "high",
  7972. thoughtLevels: ["high", "max", "nothink"],
  7973. mode: "yolo",
  7974. };
  7975. it("种子填充空初值:config 就位、revision/seq 不动、schema 合法", () => {
  7976. const projection = new ProductProjection("session-1", "epoch-1");
  7977. projection.seedConfig(SEED);
  7978. const snapshot = projection.getSnapshot();
  7979. expect(snapshot.config).toMatchObject({
  7980. provider: "prov-a",
  7981. model: "model-1",
  7982. thought: "high",
  7983. thoughtLevels: ["high", "max", "nothink"],
  7984. mode: "yolo",
  7985. });
  7986. expect(snapshot.revision).toBe(0);
  7987. expect(snapshot.seq).toBe(0);
  7988. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  7989. });
  7990. it("种子后事件覆盖:ModelSelected / SessionModeChanged 的日志值优先", () => {
  7991. const projection = new ProductProjection("session-1", "epoch-1");
  7992. projection.seedConfig(SEED);
  7993. const log = new EventLog();
  7994. log.push(SessionEventType.ModelSelected, {
  7995. modelSelection: {
  7996. providerId: "prov-b",
  7997. modelId: "model-2",
  7998. options: { reasoningLevel: "low" },
  7999. },
  8000. supportedThoughtLevels: ["low", "high"],
  8001. });
  8002. log.push(SessionEventType.SessionModeChanged, {
  8003. mode: "plan",
  8004. previousMode: "yolo",
  8005. source: "command",
  8006. });
  8007. for (const event of log.events) projection.applyEvent(event);
  8008. expect(projection.getSnapshot().config).toMatchObject({
  8009. provider: "prov-b",
  8010. model: "model-2",
  8011. thought: "low",
  8012. thoughtLevels: ["low", "high"],
  8013. mode: "plan",
  8014. });
  8015. projection.seedConfig({ ...SEED, thoughtLevels: ["disabled"] });
  8016. expect(projection.getSnapshot().config.thoughtLevels).toEqual(["low", "high"]);
  8017. });
  8018. it("事件后种子不覆盖:冷恢复重放序在前时日志值保持权威", () => {
  8019. const projection = new ProductProjection("session-1", "epoch-1");
  8020. const log = new EventLog();
  8021. log.push(SessionEventType.ModelSelected, {
  8022. modelSelection: { providerId: "prov-b", modelId: "model-2" },
  8023. });
  8024. log.push(SessionEventType.SessionModeChanged, {
  8025. mode: "plan",
  8026. previousMode: "build",
  8027. source: "tool",
  8028. });
  8029. for (const event of log.events) projection.applyEvent(event);
  8030. projection.seedConfig(SEED);
  8031. expect(projection.getSnapshot().config).toMatchObject({
  8032. provider: "prov-b",
  8033. model: "model-2",
  8034. thoughtLevels: ["high", "max", "nothink"],
  8035. mode: "plan",
  8036. });
  8037. });
  8038. it("分区独立:只有 mode 被事件触碰时,模型区仍接受种子(反之亦然)", () => {
  8039. const projection = new ProductProjection("session-1", "epoch-1");
  8040. const log = new EventLog();
  8041. log.push(SessionEventType.SessionModeChanged, {
  8042. mode: "plan",
  8043. previousMode: "build",
  8044. source: "command",
  8045. });
  8046. for (const event of log.events) projection.applyEvent(event);
  8047. projection.seedConfig(SEED);
  8048. const config = projection.getSnapshot().config;
  8049. // mode 由日志裁决,模型区来自种子(历史会话恢复:resume 已把上次选型写回 runtime)。
  8050. expect(config.mode).toBe("plan");
  8051. expect(config).toMatchObject({
  8052. provider: "prov-a",
  8053. model: "model-1",
  8054. thought: "high",
  8055. thoughtLevels: ["high", "max", "nothink"],
  8056. });
  8057. });
  8058. it("相同种子幂等,明确留空的恢复结果清除旧模型", () => {
  8059. const projection = new ProductProjection("session-1", "epoch-1");
  8060. projection.seedConfig(SEED);
  8061. const first = projection.getSnapshot();
  8062. projection.seedConfig(SEED);
  8063. expect(projection.getSnapshot()).toBe(first);
  8064. // 恢复结果明确留空,不能继续显示历史消息留下的模型。
  8065. projection.seedConfig({ provider: "", model: "", mode: "" });
  8066. expect(projection.getSnapshot().config).toMatchObject({
  8067. provider: "",
  8068. model: "",
  8069. });
  8070. });
  8071. it("分享上下文导入种子只写只读来源元数据,不生成可见对话行", () => {
  8072. const projection = new ProductProjection("session-1", "epoch-1");
  8073. const before = projection.getSnapshot();
  8074. projection.seedSharedContextImport({ title: "筛选近一年收益前10%的偏股混合基金" });
  8075. const snapshot = projection.getSnapshot();
  8076. expect(snapshot.sharedContextImport).toEqual({
  8077. title: "筛选近一年收益前10%的偏股混合基金",
  8078. });
  8079. expect(snapshot.rows.window).toEqual([]);
  8080. expect(snapshot.revision).toBe(before.revision);
  8081. expect(snapshot.seq).toBe(before.seq);
  8082. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  8083. });
  8084. });
  8085. // ── 16-timeline-authority-plan P2:productTurn 切分 / goalVerify 身份与落位 ──
  8086. describe("P2 productTurn 切分(S1/S3/S5)", () => {
  8087. const drainScenario = (delivery: "queue" | "guide") => {
  8088. const log = new EventLog();
  8089. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  8090. log.push(
  8091. SessionEventType.TurnStarted,
  8092. { turnNumber: 1, input: "问题一" },
  8093. { turnId: "turn-1" },
  8094. );
  8095. log.push(
  8096. SessionEventType.ModelStreaming,
  8097. { kind: "text_start", delta: "", done: false },
  8098. { turnId: "turn-1" },
  8099. );
  8100. log.push(
  8101. SessionEventType.ModelStreaming,
  8102. { kind: "text_delta", delta: "回答一", done: false },
  8103. { turnId: "turn-1" },
  8104. );
  8105. log.push(
  8106. SessionEventType.ModelStreaming,
  8107. { kind: "text_end", delta: "", done: false },
  8108. { turnId: "turn-1" },
  8109. );
  8110. log.push(
  8111. SessionEventType.TurnSteerQueued,
  8112. {
  8113. pendingInputId: "p-q2",
  8114. input: "问题二",
  8115. inputPreview: "问题二",
  8116. inputSize: 9,
  8117. delivery,
  8118. targetTurnId: "turn-1",
  8119. queueLength: 1,
  8120. },
  8121. { turnId: "turn-1" },
  8122. );
  8123. log.push(
  8124. SessionEventType.TurnSteerDrained,
  8125. {
  8126. pendingInputIds: ["p-q2"],
  8127. injectedMessageIds: ["msg-q2"],
  8128. drainedInputs: [
  8129. {
  8130. pendingInputId: "p-q2",
  8131. messageId: "msg-q2",
  8132. text: "问题二",
  8133. delivery,
  8134. intent: {
  8135. sourceCommandId: "command-q2",
  8136. queueItemId: "p-q2",
  8137. clientId: "desktop-continuous",
  8138. kind: delivery === "guide" ? "sendGoalCommand" : "sendText",
  8139. text: "问题二",
  8140. admissionSeq: 2,
  8141. admittedAt: 1_700_000_006_000,
  8142. requestedDelivery: "auto",
  8143. admittedDelivery: delivery,
  8144. fallbackReasonCode: "runtime.turnBusy",
  8145. attachmentRefs: [
  8146. {
  8147. ref: "artifact://q2",
  8148. fileName: "q2.txt",
  8149. mime: "text/plain",
  8150. bytes: 3,
  8151. },
  8152. ],
  8153. provenance: {
  8154. sourceCommandId: "command-q2-original",
  8155. queueItemId: "p-q2-original",
  8156. clientId: "desktop-continuous",
  8157. },
  8158. },
  8159. },
  8160. ],
  8161. targetTurnId: "turn-1",
  8162. },
  8163. { turnId: "turn-1" },
  8164. );
  8165. log.push(
  8166. SessionEventType.ModelStreaming,
  8167. { kind: "text_start", delta: "", done: false },
  8168. { turnId: "turn-1" },
  8169. );
  8170. log.push(
  8171. SessionEventType.ModelStreaming,
  8172. { kind: "text_delta", delta: "回答二", done: false },
  8173. { turnId: "turn-1" },
  8174. );
  8175. log.push(
  8176. SessionEventType.ModelStreaming,
  8177. { kind: "text_end", delta: "", done: false },
  8178. { turnId: "turn-1" },
  8179. );
  8180. log.push(
  8181. SessionEventType.TurnComplete,
  8182. { response: "", tokenCount: 0, toolCallCount: 0, duration: 9000, resultType: "success" },
  8183. { turnId: "turn-1" },
  8184. );
  8185. return runAll(log.events);
  8186. };
  8187. it("QD-node:queue drain 切新 productTurn,两段回复都可见、工时按边界拆分(Case A 根修)", () => {
  8188. const { projection } = drainScenario("queue");
  8189. const snapshot = projection.getSnapshot();
  8190. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  8191. const rows = snapshot.rows.window;
  8192. // 两个 turnHeader:首轮 legacy runtime id 与 promoted user messageId(稳定 productTurn)。
  8193. const headers = rows.filter((row) => row.kind === "turnHeader");
  8194. expect(headers.map((row) => row.turnId)).toEqual(["turn-1", "msg-q2"]);
  8195. // 第一段 header 在 drain 边界收口:activeMs = drain(7s) - start(2s)。
  8196. expect(headers[0]).toMatchObject({ state: "completedSuccess", activeMs: 5000 });
  8197. // 第二段 header 在 TurnComplete 收口:activeMs = complete(11s) - drain(7s),
  8198. // 不再是整段 runtime duration(9000)。
  8199. expect(headers[1]).toMatchObject({ state: "completedSuccess", activeMs: 4000 });
  8200. // 两段 assistant 正文都在,各归自己的 productTurn——A1 不再被折进上一轮 history。
  8201. const assistantRows = rows.filter((row) => row.kind === "assistantText");
  8202. expect(
  8203. assistantRows.map((row) => [row.turnId, row.kind === "assistantText" ? row.text : ""]),
  8204. ).toEqual([
  8205. ["turn-1", "回答一"],
  8206. ["msg-q2", "回答二"],
  8207. ]);
  8208. // drained user 行归新 productTurn,并原子登记 message/entity/edit target。
  8209. const drainedUser = rows.find((row) => row.kind === "userInput" && row.text === "问题二");
  8210. expect(drainedUser?.turnId).toBe("msg-q2");
  8211. expect(projection.getMessageIdForRow(drainedUser!.rowId)).toBe("msg-q2");
  8212. expect(projection.getEntityIdForRow(drainedUser!.rowId)).toBe("msg-q2");
  8213. expect(drainedUser?.actions).toMatchObject({ canEdit: true, editDisposition: "rewind" });
  8214. expect(
  8215. projection.resolveRowActionTarget(
  8216. { rowId: drainedUser!.rowId, entityId: drainedUser!.entityId },
  8217. "editUserQuery",
  8218. ),
  8219. ).toMatchObject({
  8220. ok: true,
  8221. editTarget: {
  8222. entityId: "msg-q2",
  8223. productTurnId: "msg-q2",
  8224. transcriptMessageId: "msg-q2",
  8225. intent: {
  8226. kind: "sendText",
  8227. text: "问题二",
  8228. sourceCommandId: "command-q2",
  8229. queueItemId: "p-q2",
  8230. clientId: "desktop-continuous",
  8231. admissionSeq: 2,
  8232. admittedAt: 1_700_000_006_000,
  8233. requestedDelivery: "auto",
  8234. admittedDelivery: "queue",
  8235. fallbackReasonCode: "runtime.turnBusy",
  8236. attachments: [
  8237. {
  8238. ref: "artifact://q2",
  8239. fileName: "q2.txt",
  8240. mime: "text/plain",
  8241. bytes: 3,
  8242. },
  8243. ],
  8244. provenance: {
  8245. sourceCommandId: "command-q2-original",
  8246. queueItemId: "p-q2-original",
  8247. clientId: "desktop-continuous",
  8248. },
  8249. },
  8250. },
  8251. });
  8252. const coldLog = new EventLog();
  8253. coldLog.push(
  8254. SessionEventType.TurnStarted,
  8255. { turnNumber: 2, input: "问题二", messageId: "msg-q2" },
  8256. { turnId: "hydrate-turn-2" },
  8257. );
  8258. const coldUser = runAll(coldLog.events)
  8259. .projection.getSnapshot()
  8260. .rows.window.find((row) => row.kind === "userInput");
  8261. // 同一 promoted user transcript 在 live drain 与 cold TurnStarted 中使用同一 productTurnId。
  8262. expect(coldUser?.turnId).toBe(drainedUser?.turnId);
  8263. expect(snapshot.queue.items).toEqual([]);
  8264. });
  8265. it("P06:guide steer 内联不切轮,但 accepted guide 开启独立可恢复工时段", () => {
  8266. const { projection } = drainScenario("guide");
  8267. const snapshot = projection.getSnapshot();
  8268. const rows = snapshot.rows.window;
  8269. const headers = rows.filter((row) => row.kind === "turnHeader");
  8270. expect(headers.map((row) => row.turnId)).toEqual(["turn-1"]);
  8271. expect(headers[0]).toMatchObject({
  8272. state: "completedSuccess",
  8273. activeMs: 9000,
  8274. workSegments: [
  8275. {
  8276. segmentId: "turn-1:initial",
  8277. startedAt: 1_700_000_002_000,
  8278. endedAt: 1_700_000_007_000,
  8279. activeMs: 5000,
  8280. },
  8281. {
  8282. segmentId: "msg-q2",
  8283. triggerEntityId: "msg-q2",
  8284. startedAt: 1_700_000_007_000,
  8285. endedAt: 1_700_000_011_000,
  8286. activeMs: 4000,
  8287. },
  8288. ],
  8289. });
  8290. const steerUser = rows.find((row) => row.kind === "userInput" && row.text === "问题二");
  8291. expect(steerUser?.turnId).toBe("turn-1");
  8292. expect(steerUser?.actions).toMatchObject({ canEdit: true, editDisposition: "rewind" });
  8293. expect(
  8294. projection.resolveRowActionTarget(
  8295. { rowId: steerUser!.rowId, entityId: steerUser!.entityId },
  8296. "editUserQuery",
  8297. ),
  8298. ).toMatchObject({
  8299. ok: true,
  8300. editTarget: {
  8301. entityId: "msg-q2",
  8302. productTurnId: "turn-1",
  8303. transcriptMessageId: "msg-q2",
  8304. intent: {
  8305. kind: "sendGoalCommand",
  8306. text: "问题二",
  8307. sourceCommandId: "command-q2",
  8308. queueItemId: "p-q2",
  8309. admittedDelivery: "guide",
  8310. },
  8311. },
  8312. });
  8313. // 内联位置:在 A1 之后、A2 之前。
  8314. const order = rows
  8315. .filter((row) => row.kind === "assistantText" || row.kind === "userInput")
  8316. .map((row) => (row.kind === "assistantText" || row.kind === "userInput" ? row.text : ""));
  8317. expect(order).toEqual(["问题一", "回答一", "问题二", "回答二"]);
  8318. });
  8319. it.each([
  8320. ["一个 drained 事件带两条 guide", true, false],
  8321. ["每条 guide 各一个 drained 事件(冷恢复形态)", false, false],
  8322. ["每条 guide 各一个 drained 事件且逐事件原子发布(live 形态)", false, true],
  8323. ])("M06f:%s时,相邻 guide 共用第一条开启的工作段", (_label, together, atomic) => {
  8324. const log = new EventLog();
  8325. const at = (seconds: number) => ({
  8326. turnId: "turn-1",
  8327. timestampMs: 1_700_000_000_000 + seconds * 1000,
  8328. });
  8329. const text = (delta: string, seconds: number) => {
  8330. log.push(
  8331. SessionEventType.ModelStreaming,
  8332. { kind: "text_start", delta: "", done: false },
  8333. at(seconds),
  8334. );
  8335. log.push(
  8336. SessionEventType.ModelStreaming,
  8337. { kind: "text_delta", delta, done: false },
  8338. at(seconds),
  8339. );
  8340. log.push(
  8341. SessionEventType.ModelStreaming,
  8342. { kind: "text_end", delta: "", done: false },
  8343. at(seconds),
  8344. );
  8345. };
  8346. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 }, at(1));
  8347. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "问题一" }, at(2));
  8348. text("回答一", 3);
  8349. const guides = ["g1", "g2"].map((id) => ({
  8350. pendingInputId: `p-${id}`,
  8351. messageId: `msg-${id}`,
  8352. text: `引导-${id}`,
  8353. delivery: "guide" as const,
  8354. }));
  8355. const drain = (items: typeof guides) =>
  8356. log.push(
  8357. SessionEventType.TurnSteerDrained,
  8358. {
  8359. pendingInputIds: items.map((item) => item.pendingInputId),
  8360. injectedMessageIds: items.map((item) => item.messageId),
  8361. drainedInputs: items,
  8362. targetTurnId: "turn-1",
  8363. },
  8364. at(7),
  8365. );
  8366. if (together) drain(guides);
  8367. else for (const guide of guides) drain([guide]);
  8368. text("回答二", 9);
  8369. log.push(
  8370. SessionEventType.TurnComplete,
  8371. { response: "", tokenCount: 0, toolCallCount: 0, duration: 9000, resultType: "success" },
  8372. at(11),
  8373. );
  8374. const projection = new ProductProjection("session-1", "epoch-1");
  8375. for (const event of log.events) {
  8376. if (atomic) projection.applyEventAtomically(event, () => true);
  8377. else projection.applyEvent(event);
  8378. }
  8379. const rows = projection.getSnapshot().rows.window;
  8380. expect(rows.find((row) => row.kind === "turnHeader")).toMatchObject({
  8381. workSegments: [
  8382. {
  8383. segmentId: "turn-1:initial",
  8384. startedAt: 1_700_000_002_000,
  8385. endedAt: 1_700_000_007_000,
  8386. activeMs: 5000,
  8387. },
  8388. {
  8389. segmentId: "msg-g1",
  8390. triggerEntityId: "msg-g1",
  8391. startedAt: 1_700_000_007_000,
  8392. endedAt: 1_700_000_011_000,
  8393. activeMs: 4000,
  8394. },
  8395. ],
  8396. });
  8397. expect(
  8398. rows
  8399. .filter((row) => row.kind === "userInput" || row.kind === "assistantText")
  8400. .map((row) => (row.kind === "userInput" || row.kind === "assistantText" ? row.text : "")),
  8401. ).toEqual(["问题一", "回答一", "引导-g1", "引导-g2", "回答二"]);
  8402. });
  8403. it("M06f:两次取出之间有一个没有可见行的模型 step 时,后一条 guide 开新工作段", () => {
  8404. const log = new EventLog();
  8405. const at = (seconds: number) => ({
  8406. turnId: "turn-1",
  8407. timestampMs: 1_700_000_000_000 + seconds * 1000,
  8408. });
  8409. const guide = (id: string, seconds: number) =>
  8410. log.push(
  8411. SessionEventType.TurnSteerDrained,
  8412. {
  8413. pendingInputIds: [`p-${id}`],
  8414. injectedMessageIds: [`msg-${id}`],
  8415. drainedInputs: [
  8416. {
  8417. pendingInputId: `p-${id}`,
  8418. messageId: `msg-${id}`,
  8419. text: `引导-${id}`,
  8420. delivery: "guide" as const,
  8421. },
  8422. ],
  8423. targetTurnId: "turn-1",
  8424. },
  8425. at(seconds),
  8426. );
  8427. const stream = (kind: string, delta: string, seconds: number) =>
  8428. log.push(SessionEventType.ModelStreaming, { kind, delta, done: false }, at(seconds));
  8429. const text = (delta: string, seconds: number) => {
  8430. stream("text_start", "", seconds);
  8431. stream("text_delta", delta, seconds);
  8432. stream("text_end", "", seconds);
  8433. };
  8434. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 }, at(1));
  8435. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "问题一" }, at(2));
  8436. text("回答一", 3);
  8437. guide("g1", 5);
  8438. // 这一步只有隐藏内容:没有任何可见行,但它是两次取出之间的模型 step。
  8439. stream("start", "", 6);
  8440. log.push(
  8441. SessionEventType.ModelComplete,
  8442. {
  8443. content: "",
  8444. stopReason: "end_turn",
  8445. querySource: "main_turn",
  8446. toolCallCount: 0,
  8447. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  8448. },
  8449. at(6),
  8450. );
  8451. guide("g2", 7);
  8452. text("回答二", 9);
  8453. log.push(
  8454. SessionEventType.TurnComplete,
  8455. { response: "", tokenCount: 0, toolCallCount: 0, duration: 9000, resultType: "success" },
  8456. at(11),
  8457. );
  8458. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  8459. expect(rows.find((row) => row.kind === "turnHeader")).toMatchObject({
  8460. workSegments: [
  8461. { segmentId: "turn-1:initial", startedAt: 1_700_000_002_000, endedAt: 1_700_000_005_000 },
  8462. {
  8463. segmentId: "msg-g1",
  8464. triggerEntityId: "msg-g1",
  8465. startedAt: 1_700_000_005_000,
  8466. endedAt: 1_700_000_007_000,
  8467. },
  8468. {
  8469. segmentId: "msg-g2",
  8470. triggerEntityId: "msg-g2",
  8471. startedAt: 1_700_000_007_000,
  8472. endedAt: 1_700_000_011_000,
  8473. },
  8474. ],
  8475. });
  8476. });
  8477. it("兼容:旧 runtime 事件(无 drainedInputs/delivery)回退 queue 查表,按 followupMode 兜底切轮", () => {
  8478. const log = new EventLog();
  8479. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  8480. log.push(
  8481. SessionEventType.TurnStarted,
  8482. { turnNumber: 1, input: "问题一" },
  8483. { turnId: "turn-1" },
  8484. );
  8485. log.push(
  8486. SessionEventType.TurnSteerQueued,
  8487. {
  8488. pendingInputId: "p-legacy",
  8489. input: "老事件文本",
  8490. inputPreview: "老事件文本",
  8491. inputSize: 15,
  8492. targetTurnId: "turn-1",
  8493. queueLength: 1,
  8494. },
  8495. { turnId: "turn-1" },
  8496. );
  8497. log.push(
  8498. SessionEventType.TurnSteerDrained,
  8499. {
  8500. pendingInputIds: ["p-legacy"],
  8501. injectedMessageIds: ["msg-legacy"],
  8502. targetTurnId: "turn-1",
  8503. },
  8504. { turnId: "turn-1" },
  8505. );
  8506. const { projection } = runAll(log.events);
  8507. const rows = projection.getSnapshot().rows.window;
  8508. const drained = rows.find((row) => row.kind === "userInput" && row.text === "老事件文本");
  8509. // followupMode 默认 queue → 切轮;旧事件虽无 drainedInputs,injectedMessageIds
  8510. // 仍是 promotion 后的持久 user 身份,因此 product turn 也稳定使用该 messageId。
  8511. expect(drained?.turnId).toBe("msg-legacy");
  8512. expect(projection.getMessageIdForRow(drained!.rowId)).toBe("msg-legacy");
  8513. });
  8514. it("PV4-10 防御:drain 缺持久 messageId 时不暴露无法执行的 edit action", () => {
  8515. const log = new EventLog();
  8516. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  8517. log.push(
  8518. SessionEventType.TurnStarted,
  8519. { turnNumber: 1, input: "问题一" },
  8520. { turnId: "turn-1" },
  8521. );
  8522. log.push(
  8523. SessionEventType.TurnSteerQueued,
  8524. {
  8525. pendingInputId: "p-no-message",
  8526. input: "缺少持久身份",
  8527. inputPreview: "缺少持久身份",
  8528. inputSize: 18,
  8529. targetTurnId: "turn-1",
  8530. queueLength: 1,
  8531. },
  8532. { turnId: "turn-1" },
  8533. );
  8534. log.push(
  8535. SessionEventType.TurnSteerDrained,
  8536. { pendingInputIds: ["p-no-message"], targetTurnId: "turn-1" },
  8537. { turnId: "turn-1" },
  8538. );
  8539. const { projection } = runAll(log.events);
  8540. const drained = projection
  8541. .getSnapshot()
  8542. .rows.window.find((row) => row.kind === "userInput" && row.text === "缺少持久身份");
  8543. expect(drained?.actions?.canEdit).not.toBe(true);
  8544. expect(
  8545. projection.resolveRowActionTarget(
  8546. { rowId: drained!.rowId, entityId: drained!.entityId },
  8547. "editUserQuery",
  8548. ),
  8549. ).toEqual({
  8550. ok: false,
  8551. status: "rejected",
  8552. reasonCode: "guard.actionUnavailable",
  8553. });
  8554. });
  8555. });
  8556. describe("P2 goalVerify 身份与落位(GV-identity / GV-terminal-only / GV-late-anchor)", () => {
  8557. it("同 targetId+iteration 的重试(新 verificationId)复用同一 marker,不长第二个", () => {
  8558. const log = new EventLog();
  8559. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  8560. log.push(SessionEventType.TargetCompletionVerification, {
  8561. targetId: "target-1",
  8562. status: "started",
  8563. verificationId: "attempt-1",
  8564. goalIteration: 1,
  8565. });
  8566. log.push(SessionEventType.TargetCompletionVerification, {
  8567. targetId: "target-1",
  8568. status: "started",
  8569. verificationId: "attempt-2",
  8570. goalIteration: 1,
  8571. });
  8572. log.push(SessionEventType.TargetCompletionVerification, {
  8573. targetId: "target-1",
  8574. status: "completed",
  8575. verificationId: "attempt-2",
  8576. goalIteration: 1,
  8577. verification: { passed: true, reason: "ok" },
  8578. });
  8579. const { projection } = runAll(log.events);
  8580. const markers = projection
  8581. .getSnapshot()
  8582. .rows.window.filter(
  8583. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  8584. );
  8585. expect(markers).toHaveLength(1);
  8586. expect(markers[0]).toMatchObject({ marker: { iteration: 1, outcome: "pass" } });
  8587. });
  8588. it("GV-terminal-only:终态先到(无 started、无 goal 状态)也能创建 boundary", () => {
  8589. const log = new EventLog();
  8590. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  8591. log.push(SessionEventType.TargetCompletionVerification, {
  8592. targetId: "target-1",
  8593. status: "completed",
  8594. verificationId: "only-terminal",
  8595. goalIteration: 3,
  8596. verification: { passed: false, reason: "还差测试" },
  8597. });
  8598. const { projection } = runAll(log.events);
  8599. const marker = projection
  8600. .getSnapshot()
  8601. .rows.window.find((row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify");
  8602. expect(marker).toMatchObject({
  8603. marker: { iteration: 3, outcome: "notSatisfied", detail: "还差测试" },
  8604. });
  8605. });
  8606. it("GV-late-anchor:verify 迟到到下一轮之后,按 anchorTurnId 锚回被验证的轮", () => {
  8607. const log = new EventLog();
  8608. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  8609. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "Q1" }, { turnId: "turn-1" });
  8610. log.push(
  8611. SessionEventType.TurnComplete,
  8612. { response: "", tokenCount: 0, toolCallCount: 0, duration: 100, resultType: "success" },
  8613. { turnId: "turn-1" },
  8614. );
  8615. log.push(SessionEventType.TurnStarted, { turnNumber: 2, input: "Q2" }, { turnId: "turn-2" });
  8616. // 迟到的 verify:事件本身归属 turn-2 期间,但 payload 锚定 turn-1。
  8617. log.push(SessionEventType.TargetCompletionVerification, {
  8618. targetId: "target-1",
  8619. status: "started",
  8620. verificationId: "late-1",
  8621. goalIteration: 1,
  8622. anchorTurnId: "turn-1",
  8623. });
  8624. const { projection } = runAll(log.events);
  8625. const marker = projection
  8626. .getSnapshot()
  8627. .rows.window.find((row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify");
  8628. // UI 按 turnId 分组:锚回 turn-1 而不是落进 turn-2 或 "turn-unknown"。
  8629. expect(marker?.turnId).toBe("turn-1");
  8630. });
  8631. });
  8632. describe("Desktop Hook invocation projection", () => {
  8633. it("keeps the shared Hook event enum aligned with Coding contracts", () => {
  8634. expect(new Set(hookInvocationRowSchema.shape.hookEventName.options)).toEqual(
  8635. new Set(Object.values(HookEventName)),
  8636. );
  8637. });
  8638. const descriptor = {
  8639. clientVisible: true as const,
  8640. sourceKind: "user" as const,
  8641. sourcePath: "/Users/example/.zcode/cli/config.json",
  8642. executionType: "process" as const,
  8643. executionMode: "foreground" as const,
  8644. commandDisplay: "node hooks/check.mjs",
  8645. timeoutMs: 5_000,
  8646. };
  8647. it("HK08/HK10 projects safe Hook summaries into the authoritative real turn", () => {
  8648. const log = new EventLog();
  8649. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1_000 });
  8650. log.push(
  8651. SessionEventType.HookRunStarted,
  8652. {
  8653. descriptor,
  8654. hookEventName: "SessionStart",
  8655. hookIndex: 0,
  8656. hookCount: 1,
  8657. hookInvocationId: "startup-hook",
  8658. hookRunId: "startup-run",
  8659. startedAt: 1_700_000_002_000,
  8660. },
  8661. { turnId: "runtime-turn-before-product-mapping" },
  8662. );
  8663. log.push(
  8664. SessionEventType.HookRunCompleted,
  8665. {
  8666. descriptor,
  8667. durationMs: 10,
  8668. hookEventName: "SessionStart",
  8669. hookIndex: 0,
  8670. hookCount: 1,
  8671. hookInvocationId: "startup-hook",
  8672. hookRunId: "startup-run",
  8673. outcome: "success",
  8674. startedAt: 1_700_000_002_000,
  8675. },
  8676. { turnId: "runtime-turn-before-product-mapping" },
  8677. );
  8678. const beforeTurn = runAll(log.events).projection.getSnapshot();
  8679. expect(beforeTurn.rows.window.some((row) => row.kind === "hookInvocation")).toBe(false);
  8680. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  8681. log.push(
  8682. SessionEventType.HookRunStarted,
  8683. {
  8684. descriptor,
  8685. hookEventName: "PreToolUse",
  8686. hookIndex: 0,
  8687. hookCount: 1,
  8688. hookInvocationId: "tool-hook",
  8689. hookRunId: "tool-run",
  8690. startedAt: 1_700_000_003_000,
  8691. toolCallId: "tool-1",
  8692. toolName: "Write",
  8693. },
  8694. { turnId: "turn-1" },
  8695. );
  8696. log.push(
  8697. SessionEventType.HookRunCompleted,
  8698. {
  8699. descriptor,
  8700. durationMs: 20,
  8701. hookEventName: "PreToolUse",
  8702. hookIndex: 0,
  8703. hookCount: 1,
  8704. hookInvocationId: "tool-hook",
  8705. hookRunId: "tool-run",
  8706. outcome: "success",
  8707. startedAt: 1_700_000_003_000,
  8708. toolCallId: "tool-1",
  8709. toolName: "Write",
  8710. },
  8711. { turnId: "turn-1" },
  8712. );
  8713. const { projection } = runAll(log.events);
  8714. const hookRows = projection
  8715. .getSnapshot()
  8716. .rows.window.filter((row) => row.kind === "hookInvocation");
  8717. expect(hookRows.map((row) => row.turnId)).toEqual(["turn-1", "turn-1"]);
  8718. expect(hookRows[0]).toMatchObject({
  8719. hookEventName: "SessionStart",
  8720. executions: [
  8721. expect.objectContaining({
  8722. didExecute: true,
  8723. displayName: "node · check.mjs",
  8724. sourceKind: "user",
  8725. }),
  8726. ],
  8727. });
  8728. expect(hookRows[1]).toMatchObject({
  8729. hookEventName: "PreToolUse",
  8730. anchorToolCallId: "tool-1",
  8731. executions: [
  8732. expect.objectContaining({
  8733. didExecute: true,
  8734. displayName: "node · check.mjs",
  8735. sourceKind: "user",
  8736. toolName: "Write",
  8737. }),
  8738. ],
  8739. });
  8740. expect(JSON.stringify(hookRows)).not.toMatch(/commandDisplay|sourcePath/u);
  8741. expect(projection.getSnapshot().rows.window.map((row) => row.turnId)).not.toContain(
  8742. "session-hooks:session-1",
  8743. );
  8744. });
  8745. it("HK09 distinguishes admission-only blocked from a Hook that executed and blocked", () => {
  8746. const log = new EventLog();
  8747. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8748. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  8749. log.push(
  8750. SessionEventType.HookRunBlocked,
  8751. {
  8752. descriptor,
  8753. hookEventName: "PreToolUse",
  8754. hookIndex: 0,
  8755. hookCount: 2,
  8756. hookInvocationId: "mixed-hook",
  8757. hookRunId: "admission-blocked",
  8758. outcome: "blocked",
  8759. startedAt: 1_700_000_003_000,
  8760. },
  8761. { turnId: "turn-1" },
  8762. );
  8763. log.push(
  8764. SessionEventType.HookRunStarted,
  8765. {
  8766. descriptor,
  8767. hookEventName: "PreToolUse",
  8768. hookIndex: 1,
  8769. hookCount: 2,
  8770. hookInvocationId: "mixed-hook",
  8771. hookRunId: "executed-block",
  8772. startedAt: 1_700_000_003_010,
  8773. },
  8774. { turnId: "turn-1" },
  8775. );
  8776. log.push(
  8777. SessionEventType.HookRunBlocked,
  8778. {
  8779. descriptor,
  8780. durationMs: 8,
  8781. hookEventName: "PreToolUse",
  8782. hookIndex: 1,
  8783. hookCount: 2,
  8784. hookInvocationId: "mixed-hook",
  8785. hookRunId: "executed-block",
  8786. blockReason: "blocked by workspace policy",
  8787. outcome: "blocked",
  8788. startedAt: 1_700_000_003_010,
  8789. },
  8790. { turnId: "turn-1" },
  8791. );
  8792. const row = runAll(log.events)
  8793. .projection.getSnapshot()
  8794. .rows.window.find((candidate) => candidate.kind === "hookInvocation");
  8795. expect(row).toMatchObject({
  8796. state: "completed",
  8797. executions: [
  8798. expect.objectContaining({ hookRunId: "admission-blocked", didExecute: false }),
  8799. expect.objectContaining({
  8800. hookRunId: "executed-block",
  8801. didExecute: true,
  8802. outcome: "blocked",
  8803. blockReason: "blocked by workspace policy",
  8804. }),
  8805. ],
  8806. });
  8807. });
  8808. it("HK-UP-02 projects an executed UserPromptSubmit block into the chat error", () => {
  8809. const log = new EventLog();
  8810. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1_000 });
  8811. log.push(
  8812. SessionEventType.TurnStarted,
  8813. { turnNumber: 1, input: "blocked prompt" },
  8814. { turnId: "turn-1" },
  8815. );
  8816. log.push(
  8817. SessionEventType.HookRunStarted,
  8818. {
  8819. descriptor,
  8820. hookEventName: "UserPromptSubmit",
  8821. hookIndex: 0,
  8822. hookCount: 1,
  8823. hookInvocationId: "prompt-hook",
  8824. hookRunId: "prompt-run",
  8825. startedAt: 1_700_000_003_000,
  8826. },
  8827. { turnId: "turn-1" },
  8828. );
  8829. log.push(
  8830. SessionEventType.HookRunBlocked,
  8831. {
  8832. descriptor,
  8833. durationMs: 12,
  8834. hookEventName: "UserPromptSubmit",
  8835. hookIndex: 0,
  8836. hookCount: 1,
  8837. hookInvocationId: "prompt-hook",
  8838. hookRunId: "prompt-run",
  8839. blockReason: "hooks_prompt_block",
  8840. errorMessage:
  8841. "python3: can't open file '/workspace/a.py': [Errno 2] No such file or directory",
  8842. stderrPreview:
  8843. "python3: can't open file '/workspace/a.py': [Errno 2] No such file or directory",
  8844. outcome: "blocked",
  8845. startedAt: 1_700_000_003_000,
  8846. },
  8847. { turnId: "turn-1" },
  8848. );
  8849. log.push(
  8850. SessionEventType.TurnComplete,
  8851. {
  8852. response: "HOOK_PROMPT_BLOCK_REASON",
  8853. tokenCount: 0,
  8854. toolCallCount: 0,
  8855. duration: 12,
  8856. resultType: "success",
  8857. },
  8858. { turnId: "turn-1" },
  8859. );
  8860. const { projection } = runAll(log.events);
  8861. const snapshot = projection.getSnapshot();
  8862. expect(snapshot.control.phase).toBe("completedSuccess");
  8863. expect(snapshot.control.lastError).toMatchObject({
  8864. code: "fault.runtime.hookBlocked",
  8865. message:
  8866. "hooks_prompt_block: python3: can't open file '/workspace/a.py': [Errno 2] No such file or directory",
  8867. detail:
  8868. "Hook block reason: hooks_prompt_block\nHook error: python3: can't open file '/workspace/a.py': [Errno 2] No such file or directory",
  8869. recoverable: false,
  8870. source: "runtime",
  8871. traceId: "trace-1",
  8872. attribution: { source: "runtime", reason: "hook_blocked" },
  8873. });
  8874. });
  8875. it.each([
  8876. [SessionEventType.HookRunCompleted, "success"],
  8877. [SessionEventType.HookRunFailed, "failed"],
  8878. ] as const)("HK09 keeps terminal-only %s as not executed", (terminalType, outcome) => {
  8879. const log = new EventLog();
  8880. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8881. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  8882. log.push(
  8883. terminalType,
  8884. {
  8885. descriptor,
  8886. durationMs: 20,
  8887. hookEventName: "PreToolUse",
  8888. hookIndex: 0,
  8889. hookCount: 1,
  8890. hookInvocationId: `terminal-only-${outcome}`,
  8891. hookRunId: `terminal-only-run-${outcome}`,
  8892. outcome,
  8893. startedAt: 1_700_000_003_000,
  8894. },
  8895. { turnId: "turn-1", timestampMs: 1_700_000_003_020 },
  8896. );
  8897. const row = runAll(log.events)
  8898. .projection.getSnapshot()
  8899. .rows.window.find((candidate) => candidate.kind === "hookInvocation");
  8900. expect(row).toMatchObject({
  8901. executions: [expect.objectContaining({ didExecute: false, outcome })],
  8902. });
  8903. });
  8904. it("HK13 updates a late async terminal in place without reopening the completed turn", () => {
  8905. const log = new EventLog();
  8906. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8907. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  8908. log.push(
  8909. SessionEventType.HookRunStarted,
  8910. {
  8911. descriptor: { ...descriptor, executionMode: "background" },
  8912. hookEventName: "UserPromptSubmit",
  8913. hookIndex: 0,
  8914. hookCount: 1,
  8915. hookInvocationId: "async-hook",
  8916. hookRunId: "async-run",
  8917. startedAt: 1_700_000_003_000,
  8918. },
  8919. { turnId: "turn-1", timestampMs: 1_700_000_003_000 },
  8920. );
  8921. log.push(
  8922. SessionEventType.TurnComplete,
  8923. { response: "done", tokenCount: 1, toolCallCount: 0, duration: 10, resultType: "success" },
  8924. { turnId: "turn-1", timestampMs: 1_700_000_003_010 },
  8925. );
  8926. log.push(
  8927. SessionEventType.HookRunCompleted,
  8928. {
  8929. descriptor: { ...descriptor, executionMode: "background" },
  8930. durationMs: 50,
  8931. hookEventName: "UserPromptSubmit",
  8932. hookIndex: 0,
  8933. hookCount: 1,
  8934. hookInvocationId: "async-hook",
  8935. hookRunId: "async-run",
  8936. outcome: "success",
  8937. startedAt: 1_700_000_003_000,
  8938. },
  8939. { turnId: "turn-1", timestampMs: 1_700_000_003_050 },
  8940. );
  8941. const { deltasPerEvent, projection } = runAll(log.events);
  8942. expect(deltasPerEvent[4]).toContainEqual(
  8943. expect.objectContaining({
  8944. op: "row.upserted",
  8945. row: expect.objectContaining({ hookInvocationId: "async-hook", state: "completed" }),
  8946. }),
  8947. );
  8948. expect(projection.getSnapshot().control.phase).toBe("completedSuccess");
  8949. expect(
  8950. projection
  8951. .getSnapshot()
  8952. .rows.window.filter(
  8953. (row) => row.kind === "hookInvocation" && row.hookInvocationId === "async-hook",
  8954. ),
  8955. ).toHaveLength(1);
  8956. });
  8957. it("HK13 closes an attached started-only execution on a real runtime resume", () => {
  8958. const log = new EventLog();
  8959. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8960. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  8961. log.push(
  8962. SessionEventType.HookRunStarted,
  8963. {
  8964. descriptor,
  8965. hookEventName: "PreToolUse",
  8966. hookIndex: 0,
  8967. hookCount: 1,
  8968. hookInvocationId: "started-only-hook",
  8969. hookRunId: "started-only-run",
  8970. startedAt: 1_700_000_002_000,
  8971. },
  8972. { turnId: "turn-1", timestampMs: 1_700_000_002_000 },
  8973. );
  8974. log.push(SessionEventType.SessionResumed, {}, { timestampMs: 1_700_000_003_000 });
  8975. const row = runAll(log.events)
  8976. .projection.getSnapshot()
  8977. .rows.window.find((candidate) => candidate.kind === "hookInvocation");
  8978. expect(row).toMatchObject({
  8979. state: "failed",
  8980. executions: [
  8981. {
  8982. didExecute: true,
  8983. state: "failed",
  8984. outcome: "cancelled",
  8985. durationMs: 1_000,
  8986. },
  8987. ],
  8988. });
  8989. });
  8990. it("HK17 does not flush a pending SessionStart summary onto a model-only compact turn", () => {
  8991. // Bug 根因:Runtime 的 runSessionStartHooks 先于 /compact 输入解析执行,首条输入即
  8992. // /compact 时 SessionStart Hook 真实执行且携带 compact 的 runtime turnId;投影层
  8993. // flush 只看「下一条 TurnStarted」,把摘要挂到了 model-only 维护 turn 上。
  8994. const log = new EventLog();
  8995. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  8996. log.push(
  8997. SessionEventType.HookRunStarted,
  8998. {
  8999. descriptor,
  9000. hookEventName: "SessionStart",
  9001. hookIndex: 0,
  9002. hookCount: 1,
  9003. hookInvocationId: "startup-hook",
  9004. hookRunId: "startup-run",
  9005. startedAt: 1_700_000_002_000,
  9006. },
  9007. { turnId: "turn-1", timestampMs: 1_700_000_002_000 },
  9008. );
  9009. log.push(
  9010. SessionEventType.HookRunCompleted,
  9011. {
  9012. descriptor,
  9013. durationMs: 10,
  9014. hookEventName: "SessionStart",
  9015. hookIndex: 0,
  9016. hookCount: 1,
  9017. hookInvocationId: "startup-hook",
  9018. hookRunId: "startup-run",
  9019. outcome: "success",
  9020. startedAt: 1_700_000_002_000,
  9021. },
  9022. { turnId: "turn-1", timestampMs: 1_700_000_002_010 },
  9023. );
  9024. // compact 维护 turn:inputVisibility=model-only,无 user bubble。
  9025. log.push(
  9026. SessionEventType.TurnStarted,
  9027. { turnNumber: 1, input: "/compact", inputVisibility: "model-only" },
  9028. { turnId: "turn-1", timestampMs: 1_700_000_003_000 },
  9029. );
  9030. log.push(
  9031. SessionEventType.CompactStarted,
  9032. {
  9033. operationId: "op-1",
  9034. messageId: "msg-compact",
  9035. status: "started",
  9036. trigger: "manual",
  9037. display: "separator",
  9038. },
  9039. { turnId: "turn-1", timestampMs: 1_700_000_003_050 },
  9040. );
  9041. log.push(
  9042. SessionEventType.CompactCompleted,
  9043. {
  9044. operationId: "op-1",
  9045. messageId: "msg-compact",
  9046. status: "completed",
  9047. trigger: "manual",
  9048. display: "separator",
  9049. },
  9050. { turnId: "turn-1", timestampMs: 1_700_000_004_000 },
  9051. );
  9052. log.push(
  9053. SessionEventType.TurnComplete,
  9054. {
  9055. response: "compacted",
  9056. tokenCount: 1,
  9057. toolCallCount: 0,
  9058. duration: 1_000,
  9059. resultType: "success",
  9060. },
  9061. { turnId: "turn-1", timestampMs: 1_700_000_004_050 },
  9062. );
  9063. const afterCompact = runAll(log.events).projection.getSnapshot();
  9064. // compact 维护 turn 不承载 SessionStart 摘要:不得出现挂在 turn-1 的 hook row。
  9065. expect(afterCompact.rows.window.filter((row) => row.kind === "hookInvocation")).toHaveLength(0);
  9066. // 下一条真实 user-visible turn 才是合法收口目标。
  9067. log.push(
  9068. SessionEventType.TurnStarted,
  9069. { turnNumber: 2, input: "next real prompt" },
  9070. { turnId: "turn-2", timestampMs: 1_700_000_005_000 },
  9071. );
  9072. const afterRealTurn = runAll(log.events).projection.getSnapshot();
  9073. const hookRows = afterRealTurn.rows.window.filter((row) => row.kind === "hookInvocation");
  9074. expect(hookRows).toHaveLength(1);
  9075. expect(hookRows[0]).toMatchObject({
  9076. hookEventName: "SessionStart",
  9077. turnId: "turn-2",
  9078. executions: [expect.objectContaining({ didExecute: true })],
  9079. });
  9080. });
  9081. it("HK17 keeps a SessionStart summary pending when a compact turn is the last turn", () => {
  9082. // 只有 /compact 且无后续输入:摘要保持 pending,不挂 compact marker,也不制造
  9083. // 可见时间线内容(session-hooks:* synthetic turn 禁止)。
  9084. const log = new EventLog();
  9085. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  9086. log.push(
  9087. SessionEventType.HookRunStarted,
  9088. {
  9089. descriptor,
  9090. hookEventName: "SessionStart",
  9091. hookIndex: 0,
  9092. hookCount: 1,
  9093. hookInvocationId: "startup-hook",
  9094. hookRunId: "startup-run",
  9095. startedAt: 1_700_000_002_000,
  9096. },
  9097. { turnId: "turn-1", timestampMs: 1_700_000_002_000 },
  9098. );
  9099. log.push(
  9100. SessionEventType.HookRunCompleted,
  9101. {
  9102. descriptor,
  9103. durationMs: 10,
  9104. hookEventName: "SessionStart",
  9105. hookIndex: 0,
  9106. hookCount: 1,
  9107. hookInvocationId: "startup-hook",
  9108. hookRunId: "startup-run",
  9109. outcome: "success",
  9110. startedAt: 1_700_000_002_000,
  9111. },
  9112. { turnId: "turn-1", timestampMs: 1_700_000_002_010 },
  9113. );
  9114. log.push(
  9115. SessionEventType.TurnStarted,
  9116. { turnNumber: 1, input: "/compact", inputVisibility: "model-only" },
  9117. { turnId: "turn-1", timestampMs: 1_700_000_003_000 },
  9118. );
  9119. log.push(
  9120. SessionEventType.TurnComplete,
  9121. {
  9122. response: "compacted",
  9123. tokenCount: 1,
  9124. toolCallCount: 0,
  9125. duration: 1_000,
  9126. resultType: "success",
  9127. },
  9128. { turnId: "turn-1", timestampMs: 1_700_000_004_000 },
  9129. );
  9130. const snapshot = runAll(log.events).projection.getSnapshot();
  9131. expect(snapshot.rows.window.filter((row) => row.kind === "hookInvocation")).toHaveLength(0);
  9132. expect(snapshot.rows.window.map((row) => row.turnId)).not.toContain("session-hooks:session-1");
  9133. });
  9134. it("HK17 keeps tool Hooks of a model-only real agent turn attached to that turn", () => {
  9135. // 回归背景(2026-08-28 review):model-only ≠ 维护 turn。background_task 通知轮
  9136. // (runtime-command-queue)、subagent_message 轮、goal continuation 轮都是
  9137. // inputVisibility="model-only" 但会真实跑工具的 agent 轮。HK17 首版把直挂 gate
  9138. // 无差别地按 currentTurnStartedModelOnly 拦截,导致这些轮的 PreToolUse/PostToolUse
  9139. // 被 pending 吞掉、错误 flush 到下一个不相关用户轮。维护 turn 排除只属于
  9140. // SessionStart;工具 Hook 必须按 event.turnId 直挂原轮,与 cold merge 对齐。
  9141. const log = new EventLog();
  9142. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9143. log.push(
  9144. SessionEventType.TurnStarted,
  9145. {
  9146. turnNumber: 1,
  9147. input: "background task completed, continue",
  9148. inputVisibility: "model-only",
  9149. },
  9150. { turnId: "turn-bg", timestampMs: 1_700_000_001_000 },
  9151. );
  9152. log.push(
  9153. SessionEventType.HookRunStarted,
  9154. {
  9155. descriptor,
  9156. hookEventName: "PreToolUse",
  9157. hookIndex: 0,
  9158. hookCount: 1,
  9159. hookInvocationId: "bg-tool-hook",
  9160. hookRunId: "bg-tool-run",
  9161. startedAt: 1_700_000_002_000,
  9162. toolCallId: "tool-bg",
  9163. toolName: "Write",
  9164. },
  9165. { turnId: "turn-bg", timestampMs: 1_700_000_002_000 },
  9166. );
  9167. log.push(
  9168. SessionEventType.HookRunCompleted,
  9169. {
  9170. descriptor,
  9171. durationMs: 15,
  9172. hookEventName: "PreToolUse",
  9173. hookIndex: 0,
  9174. hookCount: 1,
  9175. hookInvocationId: "bg-tool-hook",
  9176. hookRunId: "bg-tool-run",
  9177. outcome: "success",
  9178. startedAt: 1_700_000_002_000,
  9179. toolCallId: "tool-bg",
  9180. toolName: "Write",
  9181. },
  9182. { turnId: "turn-bg", timestampMs: 1_700_000_002_015 },
  9183. );
  9184. log.push(
  9185. SessionEventType.TurnStarted,
  9186. { turnNumber: 2, input: "unrelated user question" },
  9187. { turnId: "turn-user", timestampMs: 1_700_000_003_000 },
  9188. );
  9189. const hookRows = runAll(log.events)
  9190. .projection.getSnapshot()
  9191. .rows.window.filter((row) => row.kind === "hookInvocation");
  9192. expect(hookRows).toHaveLength(1);
  9193. // 工具 Hook 留在 model-only 真实 agent 轮,不被 pending 迁移到用户轮。
  9194. expect(hookRows[0]).toMatchObject({
  9195. hookEventName: "PreToolUse",
  9196. turnId: "turn-bg",
  9197. anchorToolCallId: "tool-bg",
  9198. executions: [expect.objectContaining({ didExecute: true })],
  9199. });
  9200. });
  9201. it.each([
  9202. {
  9203. caseName: "TurnError",
  9204. terminal: (log: EventLog, turnId: string, at: number) =>
  9205. log.push(
  9206. SessionEventType.TurnError,
  9207. { error: { type: "ProviderError", message: "rate limited" }, turnPhase: "model" },
  9208. { turnId, timestampMs: at },
  9209. ),
  9210. },
  9211. {
  9212. caseName: "TurnComplete(cancelled)",
  9213. terminal: (log: EventLog, turnId: string, at: number) =>
  9214. log.push(
  9215. SessionEventType.TurnComplete,
  9216. {
  9217. response: "",
  9218. tokenCount: 0,
  9219. toolCallCount: 0,
  9220. duration: 100,
  9221. resultType: "cancelled",
  9222. },
  9223. { turnId, timestampMs: at },
  9224. ),
  9225. },
  9226. ])(
  9227. "HK17 keeps a pending SessionStart summary off an abnormally terminated model-only turn ($caseName)",
  9228. ({ terminal }) => {
  9229. // SG-01:currentTurnId / currentTurnStartedModelOnly 是 reducer 内部侧表,
  9230. // 异常终态是最容易遗漏的生命周期边界。TurnError 非 controlOnly 路径不清侧表、
  9231. // TurnComplete(cancelled) 清侧表,两条收口路径必须等价:pending SessionStart
  9232. // 不泄漏到异常 turn、不直挂死 turn、只归位下一条真实用户 turn。
  9233. const sessionStartLifecycle = (log: EventLog, invocationId: string, at: number) => {
  9234. log.push(
  9235. SessionEventType.HookRunStarted,
  9236. {
  9237. descriptor,
  9238. hookEventName: "SessionStart",
  9239. hookIndex: 0,
  9240. hookCount: 1,
  9241. hookInvocationId: invocationId,
  9242. hookRunId: `${invocationId}-run`,
  9243. startedAt: at,
  9244. },
  9245. { turnId: "turn-mt", timestampMs: at },
  9246. );
  9247. log.push(
  9248. SessionEventType.HookRunCompleted,
  9249. {
  9250. descriptor,
  9251. durationMs: 5,
  9252. hookEventName: "SessionStart",
  9253. hookIndex: 0,
  9254. hookCount: 1,
  9255. hookInvocationId: invocationId,
  9256. hookRunId: `${invocationId}-run`,
  9257. outcome: "success",
  9258. startedAt: at,
  9259. },
  9260. { turnId: "turn-mt", timestampMs: at + 5 },
  9261. );
  9262. };
  9263. const log = new EventLog();
  9264. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  9265. // model-only goal continuation 轮(executionKind 缺省为 agent,异常走非 controlOnly)。
  9266. log.push(
  9267. SessionEventType.TurnStarted,
  9268. { turnNumber: 1, input: "continue goal", inputVisibility: "model-only" },
  9269. { turnId: "turn-mt", timestampMs: 1_700_000_001_000 },
  9270. );
  9271. sessionStartLifecycle(log, "startup-hook", 1_700_000_002_000);
  9272. terminal(log, "turn-mt", 1_700_000_003_000);
  9273. // 异常收口瞬间:pending 保留,不挂异常 turn,也不泄漏成可见 row。
  9274. const afterTerminal = runAll(log.events).projection.getSnapshot();
  9275. expect(afterTerminal.rows.window.filter((row) => row.kind === "hookInvocation")).toHaveLength(
  9276. 0,
  9277. );
  9278. expect(afterTerminal.rows.window.map((row) => row.turnId)).not.toContain(
  9279. "session-hooks:session-1",
  9280. );
  9281. // 终态后紧接的下一个 SessionStart(resume epoch)同样必须 pending,
  9282. // 不得直挂已终止的死 turn。
  9283. sessionStartLifecycle(log, "resume-hook", 1_700_000_004_000);
  9284. const afterResumeHook = runAll(log.events).projection.getSnapshot();
  9285. expect(
  9286. afterResumeHook.rows.window.filter((row) => row.kind === "hookInvocation"),
  9287. ).toHaveLength(0);
  9288. // 下一条真实用户 turn 收口两条 pending 摘要,且只出现在该轮。
  9289. log.push(
  9290. SessionEventType.TurnStarted,
  9291. { turnNumber: 2, input: "real question" },
  9292. { turnId: "turn-real", timestampMs: 1_700_000_005_000 },
  9293. );
  9294. const finalRows = runAll(log.events)
  9295. .projection.getSnapshot()
  9296. .rows.window.filter((row) => row.kind === "hookInvocation");
  9297. expect(finalRows.map((row) => [row.hookInvocationId, row.turnId])).toEqual([
  9298. ["startup-hook", "turn-real"],
  9299. ["resume-hook", "turn-real"],
  9300. ]);
  9301. },
  9302. );
  9303. it.each([
  9304. [SessionEventType.HookRunCompleted, { durationMs: 20, outcome: "success" }],
  9305. [SessionEventType.HookRunFailed, { durationMs: 20, outcome: "failed" }],
  9306. ] as const)(
  9307. "HK14 ignores late %s after its Hook branch was rewound",
  9308. (terminalType, terminal) => {
  9309. const log = new EventLog();
  9310. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9311. log.push(
  9312. SessionEventType.TurnStarted,
  9313. { turnNumber: 1, input: "run", messageId: "user-1" },
  9314. { turnId: "turn-1" },
  9315. );
  9316. log.push(
  9317. SessionEventType.ModelStreaming,
  9318. { kind: "text_start", delta: "", done: false, assistantMessageId: "assistant-1" },
  9319. { turnId: "turn-1" },
  9320. );
  9321. log.push(
  9322. SessionEventType.HookRunStarted,
  9323. {
  9324. descriptor,
  9325. hookEventName: "PreToolUse",
  9326. hookIndex: 0,
  9327. hookCount: 1,
  9328. hookInvocationId: "rewound-hook",
  9329. hookRunId: "rewound-run",
  9330. startedAt: 1_700_000_003_000,
  9331. },
  9332. { turnId: "turn-1", timestampMs: 1_700_000_003_000 },
  9333. );
  9334. log.push(SessionEventType.RewindTriggered, {
  9335. targetMessageId: "assistant-1",
  9336. scope: "conversation",
  9337. createdMessageId: "rewind-notice",
  9338. });
  9339. log.push(
  9340. terminalType,
  9341. {
  9342. descriptor,
  9343. hookEventName: "PreToolUse",
  9344. hookIndex: 0,
  9345. hookCount: 1,
  9346. hookInvocationId: "rewound-hook",
  9347. hookRunId: "rewound-run",
  9348. startedAt: 1_700_000_003_000,
  9349. ...terminal,
  9350. },
  9351. { turnId: "turn-1", timestampMs: 1_700_000_003_020 },
  9352. );
  9353. const { deltasPerEvent, projection } = runAll(log.events);
  9354. expect(deltasPerEvent[4]).toContainEqual({
  9355. op: "row.removed",
  9356. fromRowId: expect.any(Number),
  9357. });
  9358. expect(
  9359. projection
  9360. .getSnapshot()
  9361. .rows.window.some(
  9362. (row) => row.kind === "hookInvocation" && row.hookInvocationId === "rewound-hook",
  9363. ),
  9364. ).toBe(false);
  9365. expect(deltasPerEvent[5]).not.toContainEqual(
  9366. expect.objectContaining({
  9367. op: "row.appended",
  9368. row: expect.objectContaining({ hookInvocationId: "rewound-hook" }),
  9369. }),
  9370. );
  9371. },
  9372. );
  9373. it("projects workspace Hook review only as Settings-centered pending interaction", () => {
  9374. const log = new EventLog();
  9375. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9376. const request = {
  9377. kind: "workspaceHookReview",
  9378. reviewFlowId: "flow-1",
  9379. generation: 1,
  9380. interactionId: "interaction-1",
  9381. sessionId: "session-1",
  9382. taskId: "session-1",
  9383. runId: "run-1",
  9384. workspaceIdentity: "local:/workspace",
  9385. workspaceLabel: "workspace",
  9386. bundleDigest: "a".repeat(64),
  9387. createdAt: 1_700_000_001_000,
  9388. deadlineAt: 1_700_000_601_000,
  9389. sourceFiles: [
  9390. {
  9391. path: "/workspace/.zcode/config.json",
  9392. displayPath: ".zcode/config.json",
  9393. editable: true,
  9394. },
  9395. ],
  9396. summary: { eventCount: 1, hookCount: 1, pendingCount: 1 },
  9397. items: [
  9398. {
  9399. reviewItemId: "item-0",
  9400. event: "SessionStart",
  9401. matcher: "startup",
  9402. type: "command",
  9403. displayName: "SessionStart · startup",
  9404. displayCommand: "echo project",
  9405. sourcePath: ".zcode/config.json",
  9406. resolvedTimeoutMs: 60_000,
  9407. resolvedMaxOutputBytes: 32_768,
  9408. executionMode: "foreground",
  9409. configuredEnabled: true,
  9410. editable: true,
  9411. trustState: "pending_trust",
  9412. },
  9413. ],
  9414. warningCode: "workspace_hooks_execute_code",
  9415. } as const;
  9416. log.push(SessionEventType.WorkspaceHookReviewRequested, { request });
  9417. const { projection } = runAll(log.events);
  9418. expect(projection.getSnapshot().pendingInteractions).toEqual([
  9419. {
  9420. interactionId: "interaction-1",
  9421. kind: "workspaceHookReview",
  9422. anchorRowId: null,
  9423. createdAt: request.createdAt,
  9424. payload: request,
  9425. },
  9426. ]);
  9427. log.push(SessionEventType.WorkspaceHookReviewSettled, {
  9428. interactionId: "interaction-1",
  9429. state: "resolved",
  9430. });
  9431. projection.applyEvent(log.events.at(-1)!);
  9432. expect(projection.getSnapshot().pendingInteractions).toEqual([]);
  9433. });
  9434. it("superseded review generation removes only the stale interaction", () => {
  9435. const log = new EventLog();
  9436. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9437. const base = {
  9438. kind: "workspaceHookReview",
  9439. reviewFlowId: "flow-1",
  9440. sessionId: "session-1",
  9441. taskId: "session-1",
  9442. runId: "run-1",
  9443. workspaceIdentity: "local:/workspace",
  9444. workspaceLabel: "workspace",
  9445. createdAt: 1_700_000_001_000,
  9446. deadlineAt: 1_700_000_601_000,
  9447. sourceFiles: [],
  9448. summary: { eventCount: 0, hookCount: 0, pendingCount: 0 },
  9449. items: [],
  9450. warningCode: "workspace_hooks_execute_code",
  9451. } as const;
  9452. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  9453. request: {
  9454. ...base,
  9455. generation: 1,
  9456. interactionId: "interaction-1",
  9457. bundleDigest: "a".repeat(64),
  9458. },
  9459. });
  9460. log.push(SessionEventType.WorkspaceHookReviewSuperseded, {
  9461. interactionId: "interaction-1",
  9462. supersededByInteractionId: "interaction-2",
  9463. });
  9464. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  9465. request: {
  9466. ...base,
  9467. generation: 2,
  9468. interactionId: "interaction-2",
  9469. bundleDigest: "b".repeat(64),
  9470. },
  9471. });
  9472. const { projection } = runAll(log.events);
  9473. expect(projection.getSnapshot().pendingInteractions.map((item) => item.interactionId)).toEqual([
  9474. "interaction-2",
  9475. ]);
  9476. });
  9477. it("treats SessionResumed and the next requested review as a new runtime authority", () => {
  9478. const log = new EventLog();
  9479. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9480. const base = {
  9481. kind: "workspaceHookReview",
  9482. sessionId: "session-1",
  9483. taskId: "session-1",
  9484. runId: "run-1",
  9485. workspaceIdentity: "local:/workspace",
  9486. workspaceLabel: "workspace",
  9487. createdAt: 1_700_000_001_000,
  9488. deadlineAt: 1_700_000_601_000,
  9489. sourceFiles: [],
  9490. summary: { eventCount: 0, hookCount: 0, pendingCount: 0 },
  9491. items: [],
  9492. warningCode: "workspace_hooks_execute_code",
  9493. } as const;
  9494. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  9495. request: {
  9496. ...base,
  9497. reviewFlowId: "old-runtime-flow",
  9498. generation: 7,
  9499. interactionId: "old-runtime-interaction",
  9500. bundleDigest: "a".repeat(64),
  9501. },
  9502. });
  9503. log.push(SessionEventType.SessionResumed, {});
  9504. const { projection } = runAll(log.events);
  9505. expect(projection.getSnapshot().pendingInteractions).toEqual([]);
  9506. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  9507. request: {
  9508. ...base,
  9509. reviewFlowId: "new-runtime-flow",
  9510. generation: 1,
  9511. interactionId: "new-runtime-interaction",
  9512. bundleDigest: "b".repeat(64),
  9513. createdAt: 1_700_000_002_000,
  9514. deadlineAt: 1_700_000_602_000,
  9515. },
  9516. });
  9517. projection.applyEvent(log.events.at(-1)!);
  9518. expect(projection.getSnapshot().pendingInteractions.map((item) => item.interactionId)).toEqual([
  9519. "new-runtime-interaction",
  9520. ]);
  9521. });
  9522. it("ignores a different review flow until SessionResumed establishes a new runtime epoch", () => {
  9523. const log = new EventLog();
  9524. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9525. const base = {
  9526. kind: "workspaceHookReview",
  9527. generation: 1,
  9528. sessionId: "session-1",
  9529. taskId: "session-1",
  9530. runId: "run-1",
  9531. workspaceIdentity: "local:/workspace",
  9532. workspaceLabel: "workspace",
  9533. createdAt: 1_700_000_001_000,
  9534. deadlineAt: 1_700_000_601_000,
  9535. sourceFiles: [],
  9536. summary: { eventCount: 0, hookCount: 0, pendingCount: 0 },
  9537. items: [],
  9538. warningCode: "workspace_hooks_execute_code",
  9539. } as const;
  9540. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  9541. request: {
  9542. ...base,
  9543. reviewFlowId: "old-flow",
  9544. interactionId: "old-interaction",
  9545. bundleDigest: "a".repeat(64),
  9546. },
  9547. });
  9548. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  9549. request: {
  9550. ...base,
  9551. reviewFlowId: "new-flow",
  9552. interactionId: "new-interaction",
  9553. bundleDigest: "b".repeat(64),
  9554. createdAt: 1_700_000_002_000,
  9555. deadlineAt: 1_700_000_602_000,
  9556. },
  9557. });
  9558. const { projection } = runAll(log.events);
  9559. expect(projection.getSnapshot().pendingInteractions.map((item) => item.interactionId)).toEqual([
  9560. "old-interaction",
  9561. ]);
  9562. });
  9563. it("ignores equal-generation workspace Hook review requests with a conflicting interaction", () => {
  9564. const log = new EventLog();
  9565. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9566. const base = {
  9567. kind: "workspaceHookReview",
  9568. reviewFlowId: "flow-1",
  9569. generation: 3,
  9570. sessionId: "session-1",
  9571. taskId: "session-1",
  9572. runId: "run-1",
  9573. workspaceIdentity: "local:/workspace",
  9574. workspaceLabel: "workspace",
  9575. createdAt: 1_700_000_001_000,
  9576. deadlineAt: 1_700_000_601_000,
  9577. sourceFiles: [],
  9578. summary: { eventCount: 0, hookCount: 0, pendingCount: 0 },
  9579. items: [],
  9580. warningCode: "workspace_hooks_execute_code",
  9581. } as const;
  9582. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  9583. request: {
  9584. ...base,
  9585. interactionId: "interaction-authority",
  9586. bundleDigest: "a".repeat(64),
  9587. },
  9588. });
  9589. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  9590. request: {
  9591. ...base,
  9592. interactionId: "interaction-conflict",
  9593. bundleDigest: "b".repeat(64),
  9594. },
  9595. });
  9596. const { projection } = runAll(log.events);
  9597. expect(projection.getSnapshot().pendingInteractions.map((item) => item.interactionId)).toEqual([
  9598. "interaction-authority",
  9599. ]);
  9600. });
  9601. it("does not project hidden internal or legacy lifecycle events", () => {
  9602. const log = new EventLog();
  9603. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9604. log.push(SessionEventType.HookRunStarted, {
  9605. descriptor: {
  9606. ...descriptor,
  9607. clientVisible: false,
  9608. sourceKind: "internal",
  9609. },
  9610. hookEventName: "SessionStart",
  9611. hookIndex: 0,
  9612. hookCount: 0,
  9613. hookInvocationId: "mailbox-hook",
  9614. hookRunId: "mailbox-run",
  9615. startedAt: 1_700_000_002_000,
  9616. });
  9617. log.push(SessionEventType.HookRunStarted, {
  9618. hookEventName: "SessionStart",
  9619. hookIndex: 0,
  9620. hookRunId: "legacy-run",
  9621. });
  9622. const { projection } = runAll(log.events);
  9623. expect(projection.getSnapshot().rows.window).not.toContainEqual(
  9624. expect.objectContaining({ kind: "hookInvocation" }),
  9625. );
  9626. });
  9627. });
  9628. describe("软门禁(D2): workspaceHookAdmission snapshot 投影", () => {
  9629. it("WorkspaceHookAdmissionUpdated pendingCount>0 写入 snapshot.workspaceHookAdmission", () => {
  9630. const log = new EventLog();
  9631. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9632. log.push(SessionEventType.WorkspaceHookAdmissionUpdated, {
  9633. pendingCount: 2,
  9634. bundleDigest: "a".repeat(64),
  9635. workspaceIdentity: "local:/workspace",
  9636. });
  9637. const { projection } = runAll(log.events);
  9638. expect(projection.getSnapshot().workspaceHookAdmission).toEqual({
  9639. pendingCount: 2,
  9640. bundleDigest: "a".repeat(64),
  9641. workspaceIdentity: "local:/workspace",
  9642. });
  9643. });
  9644. it("WorkspaceHookAdmissionUpdated pendingCount===0 → 置 null(提示条消失)", () => {
  9645. const log = new EventLog();
  9646. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9647. // 先有 pending
  9648. log.push(SessionEventType.WorkspaceHookAdmissionUpdated, {
  9649. pendingCount: 1,
  9650. bundleDigest: "a".repeat(64),
  9651. });
  9652. // settle 后清零
  9653. log.push(SessionEventType.WorkspaceHookAdmissionUpdated, {
  9654. pendingCount: 0,
  9655. bundleDigest: "a".repeat(64),
  9656. });
  9657. const { projection } = runAll(log.events);
  9658. expect(projection.getSnapshot().workspaceHookAdmission).toBeNull();
  9659. });
  9660. it("SessionResumed epoch 清理 → workspaceHookAdmission 置 null(resume 后 activate 重新上报)", () => {
  9661. const log = new EventLog();
  9662. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9663. log.push(SessionEventType.WorkspaceHookAdmissionUpdated, {
  9664. pendingCount: 3,
  9665. bundleDigest: "a".repeat(64),
  9666. workspaceIdentity: "local:/workspace",
  9667. });
  9668. log.push(SessionEventType.SessionResumed, {});
  9669. const { projection } = runAll(log.events);
  9670. expect(projection.getSnapshot().workspaceHookAdmission).toBeNull();
  9671. });
  9672. it("workspaceIdentity 可选:缺失时 snapshot 字段不含 workspaceIdentity", () => {
  9673. const log = new EventLog();
  9674. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9675. log.push(SessionEventType.WorkspaceHookAdmissionUpdated, {
  9676. pendingCount: 1,
  9677. bundleDigest: "b".repeat(64),
  9678. });
  9679. const { projection } = runAll(log.events);
  9680. expect(projection.getSnapshot().workspaceHookAdmission).toEqual({
  9681. pendingCount: 1,
  9682. bundleDigest: "b".repeat(64),
  9683. });
  9684. expect(projection.getSnapshot().workspaceHookAdmission).not.toHaveProperty("workspaceIdentity");
  9685. });
  9686. });
  9687. // ── CreateWorkflow 运行确认(docs/dynamic-workflow/launch.md)──
  9688. describe("workflow 运行确认的 ask 预览", () => {
  9689. const causalityGraph = {
  9690. steps: [
  9691. {
  9692. id: "ask#1",
  9693. kind: "ask" as const,
  9694. label: "a",
  9695. line: 2,
  9696. column: 11,
  9697. lane: "actor#1",
  9698. },
  9699. ],
  9700. lanes: [{ id: "actor#1", name: "a" }],
  9701. // 第二层是子代理导向:每阶段一张参与者卡 + 交接边(docs/dynamic-workflow/presentation.md)。
  9702. participants: [
  9703. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] },
  9704. ],
  9705. handoffs: [],
  9706. sink: ["ask#1"],
  9707. };
  9708. function permissionRequestedLog(display?: unknown, toolName = "CreateWorkflow"): EventLog {
  9709. const turnId = "turn-1";
  9710. const log = new EventLog();
  9711. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  9712. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run it" }, { turnId });
  9713. log.push(
  9714. SessionEventType.ToolCallScheduled,
  9715. {
  9716. toolCallId: "tc-1",
  9717. toolName,
  9718. input: { script: "return 1;" },
  9719. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  9720. },
  9721. { turnId },
  9722. );
  9723. log.push(
  9724. SessionEventType.PermissionRequested,
  9725. {
  9726. requestId: "req-1",
  9727. toolCallId: "tc-1",
  9728. toolName,
  9729. riskLevel: "low",
  9730. reason: "createWorkflow.runConfirmation: user must confirm running the analyzed script",
  9731. input: { script: "return 1;" },
  9732. // CreateWorkflow 自 2026-09-11(第 7 轮)起声明会话作用域的免确认;Bash 用例只借
  9733. // 这条日志的形状,策略对它无意义(投影不看工具声明,只看事件上的策略)。
  9734. optionsPolicy: "session-always-allow",
  9735. ...(display === undefined ? {} : { display }),
  9736. },
  9737. { turnId },
  9738. );
  9739. return log;
  9740. }
  9741. it("把事件上的 display 投到 pendingInteraction,并按 optionsPolicy 把 always allow 换成会话免确认", () => {
  9742. const log = permissionRequestedLog({
  9743. kind: "create_workflow",
  9744. ok: true,
  9745. errorCount: 0,
  9746. diagnostics: [],
  9747. causalityGraph,
  9748. });
  9749. const snapshot = runAll(log.events).projection.getSnapshot();
  9750. const toolRow = snapshot.rows.window.find((row) => row.kind === "toolCall");
  9751. expect(toolRow).toMatchObject({
  9752. status: "pendingApproval",
  9753. approvalInteractionId: "req-1",
  9754. });
  9755. expect(snapshot.pendingInteractions).toHaveLength(1);
  9756. const payload = snapshot.pendingInteractions[0]?.payload;
  9757. expect(payload).toMatchObject({
  9758. kind: "permission",
  9759. display: { kind: "create_workflow", ok: true, causalityGraph },
  9760. });
  9761. // 产品裁决:项目级 always allow 被 optionsPolicy 裁掉,第 7 轮换成会话作用域的
  9762. // 免确认;第 4 轮在 v4 追加 Refine(拒绝并附修改意见),列表 = Run / Session / Deny / Refine。
  9763. expect(
  9764. payload?.kind === "permission" && payload.options.map((option) => option.optionId),
  9765. ).toEqual(["allowOnce", "allowSession", "deny", "workflowRefine"]);
  9766. const sessionOption =
  9767. payload?.kind === "permission"
  9768. ? payload.options.find((option) => option.optionId === "allowSession")
  9769. : undefined;
  9770. // wire 上的 kind 是闭集:会话选项映为 allowAlways(GUI 按 name 本地化);optionId 原样,
  9771. // broker 靠它精确命中。response 不带 permissionUpdates(strict schema,见 spec 第 7 轮)。
  9772. expect(sessionOption).toMatchObject({
  9773. kind: "allowAlways",
  9774. label: "Always allow in this session",
  9775. response: { decision: "allow" },
  9776. });
  9777. expect(sessionOption?.response).not.toHaveProperty("permissionUpdates");
  9778. expect(conversationSnapshotSchema.safeParse(snapshot).success).toBe(true);
  9779. const refineOption =
  9780. payload?.kind === "permission"
  9781. ? payload.options.find((option) => option.optionId === "workflowRefine")
  9782. : undefined;
  9783. // 静态 response 是普通 deny:不认识该选项的消费面(bot 直出、无 freeText 应答)
  9784. // 退化为拒绝;反馈升级只发生在 interaction-broker 的 freeText 特判。
  9785. expect(refineOption).toMatchObject({
  9786. kind: "custom",
  9787. label: "Refine",
  9788. response: { decision: "deny" },
  9789. });
  9790. });
  9791. it("Refine 选项只属于 CreateWorkflow:其他工具的权限 ask 不投放", () => {
  9792. const snapshot = runAll(
  9793. permissionRequestedLog(undefined, "Bash").events,
  9794. ).projection.getSnapshot();
  9795. const payload = snapshot.pendingInteractions[0]?.payload;
  9796. expect(payload?.kind).toBe("permission");
  9797. expect(
  9798. payload?.kind === "permission" && payload.options.map((option) => option.optionId),
  9799. ).toEqual(["allowOnce", "allowSession", "deny"]);
  9800. });
  9801. it("no-always-allow 策略(SaveWorkflow)仍只留 Run / Deny", () => {
  9802. const turnId = "turn-1";
  9803. const log = new EventLog();
  9804. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  9805. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "save it" }, { turnId });
  9806. log.push(
  9807. SessionEventType.PermissionRequested,
  9808. {
  9809. requestId: "req-1",
  9810. toolCallId: "tc-1",
  9811. toolName: "SaveWorkflow",
  9812. riskLevel: "low",
  9813. reason: "saveWorkflow.confirmation",
  9814. input: { name: "x", script: "return 1;" },
  9815. optionsPolicy: "no-always-allow",
  9816. },
  9817. { turnId },
  9818. );
  9819. const payload = runAll(log.events).projection.getSnapshot().pendingInteractions[0]?.payload;
  9820. expect(
  9821. payload?.kind === "permission" && payload.options.map((option) => option.optionId),
  9822. ).toEqual(["allowOnce", "deny"]);
  9823. });
  9824. it("没有 display 时保持纯文本 ask,pendingApproval 行为不变", () => {
  9825. const snapshot = runAll(permissionRequestedLog().events).projection.getSnapshot();
  9826. const payload = snapshot.pendingInteractions[0]?.payload;
  9827. expect(payload?.kind).toBe("permission");
  9828. expect(payload && "display" in payload).toBe(false);
  9829. expect(snapshot.rows.window.find((row) => row.kind === "toolCall")).toMatchObject({
  9830. status: "pendingApproval",
  9831. });
  9832. });
  9833. it("协议无法承载的 display kind 不进 ask 载荷", () => {
  9834. // file_diff 不在 v4 display 联合里;直接透传会让快照 schema 解析失败。
  9835. const log = permissionRequestedLog({
  9836. kind: "file_diff",
  9837. filePath: "/workspace/a.ts",
  9838. additions: 1,
  9839. deletions: 0,
  9840. structuredPatch: [],
  9841. });
  9842. const snapshot = runAll(log.events).projection.getSnapshot();
  9843. const payload = snapshot.pendingInteractions[0]?.payload;
  9844. expect(payload && "display" in payload).toBe(false);
  9845. expect(conversationSnapshotSchema.safeParse(snapshot).success).toBe(true);
  9846. });
  9847. });
  9848. // ── dwf 实时运行态:引擎事件 → 会话事件 → workflowRuns 状态键 ──
  9849. // 见 docs/dynamic-workflow/presentation.md「The run state the pane draws」「workflowRuns 形状与界」「终态权威 patch」。
  9850. describe("ProductProjection workflowRuns(dwf 进度投影)", () => {
  9851. const RUN_ID = "dwfrun-1";
  9852. function progress(
  9853. log: EventLog,
  9854. eventType: string,
  9855. payload: Record<string, unknown>,
  9856. extra: Record<string, unknown> = {},
  9857. ): SessionEvent {
  9858. return log.push(SessionEventType.DynamicWorkflowRunProgress, {
  9859. runId: RUN_ID,
  9860. toolCallId: "tc-1",
  9861. // sequence 是 journal sequence(appendEvent 从 0 起单调分配)。
  9862. sequence: (progressSequence[RUN_ID] = (progressSequence[RUN_ID] ?? -1) + 1),
  9863. eventType,
  9864. payload,
  9865. ...extra,
  9866. });
  9867. }
  9868. const progressSequence: Record<string, number> = {};
  9869. function startedLog(caps: Record<string, unknown> = { maxConcurrency: 4 }): EventLog {
  9870. progressSequence[RUN_ID] = -1;
  9871. const log = new EventLog();
  9872. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  9873. progress(log, "run-started", { runId: RUN_ID, caps });
  9874. return log;
  9875. }
  9876. function runsOf(log: EventLog) {
  9877. return runAll(log.events).projection.getSnapshot().workflowRuns;
  9878. }
  9879. it("run-started 建条目:状态 running,用量归零,快照过 strict schema", () => {
  9880. const log = startedLog({ maxConcurrency: 2 });
  9881. const snapshot = runAll(log.events).projection.getSnapshot();
  9882. expect(snapshot.workflowRuns).toMatchObject({
  9883. revision: 1,
  9884. runs: [
  9885. {
  9886. runId: RUN_ID,
  9887. toolCallId: "tc-1",
  9888. status: "running",
  9889. usage: { spentTokens: 0, nodesUsed: 0 },
  9890. actors: [],
  9891. nodes: [],
  9892. lastEventSequence: 0,
  9893. },
  9894. ],
  9895. });
  9896. expect(conversationSnapshotSchema.safeParse(snapshot).success).toBe(true);
  9897. });
  9898. it("节点相位按 (siteId, ordinal) upsert,不新增条目", () => {
  9899. const log = startedLog();
  9900. progress(log, "node-queued", {
  9901. instance: { siteId: "ask#1", ordinal: 1 },
  9902. kind: "ask",
  9903. actor: { siteId: "actor#1", ordinal: 1 },
  9904. actorSeq: 1,
  9905. });
  9906. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9907. progress(log, "node-repairing", {
  9908. instance: { siteId: "ask#1", ordinal: 1 },
  9909. attempt: 1,
  9910. violations: [],
  9911. });
  9912. progress(log, "node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" });
  9913. const runs = runsOf(log);
  9914. expect(runs?.runs[0]?.nodes).toEqual([
  9915. {
  9916. siteId: "ask#1",
  9917. ordinal: 1,
  9918. kind: "ask",
  9919. phase: "settled",
  9920. outcome: "ok",
  9921. actorSiteId: "actor#1",
  9922. actorOrdinal: 1,
  9923. },
  9924. ]);
  9925. });
  9926. it("cached 命中只发 node-settled(无 node-queued),kind 因此缺省而条目仍成立", () => {
  9927. const log = startedLog();
  9928. progress(log, "node-settled", {
  9929. instance: { siteId: "world-read#1", ordinal: 1 },
  9930. outcome: "ok",
  9931. cached: true,
  9932. });
  9933. expect(runsOf(log)?.runs[0]?.nodes).toEqual([
  9934. { siteId: "world-read#1", ordinal: 1, phase: "settled", outcome: "ok", cached: true },
  9935. ]);
  9936. });
  9937. it("actor-created 建 actor,其状态由自己的节点派生(三态:waiting / running / completed,决策 39)", () => {
  9938. const log = startedLog();
  9939. progress(
  9940. log,
  9941. "actor-created",
  9942. { actor: { siteId: "actor#1", ordinal: 1 }, name: "planner" },
  9943. { actorSessionId: "sess_dwf-1-actor.1" },
  9944. );
  9945. expect(runsOf(log)?.runs[0]?.actors).toEqual([
  9946. {
  9947. siteId: "actor#1",
  9948. ordinal: 1,
  9949. name: "planner",
  9950. sessionId: "sess_dwf-1-actor.1",
  9951. // 尚无节点且 run 未终态 → waiting("还没派到活"),不是 completed。
  9952. status: "waiting",
  9953. },
  9954. ]);
  9955. progress(log, "node-queued", {
  9956. instance: { siteId: "ask#1", ordinal: 1 },
  9957. kind: "ask",
  9958. actor: { siteId: "actor#1", ordinal: 1 },
  9959. });
  9960. // dispatched 只是会话就绪、请求尚未准入(docs/dynamic-workflow/concurrency.md「Protocol state」):仍是 waiting。
  9961. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9962. expect(runsOf(log)?.runs[0]?.actors[0]?.status).toBe("waiting");
  9963. // 模型请求真的发出去了 → running。
  9964. progress(log, "node-executing", { instance: { siteId: "ask#1", ordinal: 1 } });
  9965. expect(runsOf(log)?.runs[0]?.actors[0]?.status).toBe("running");
  9966. progress(log, "node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" });
  9967. expect(runsOf(log)?.runs[0]?.actors[0]?.status).toBe("completed");
  9968. });
  9969. it("用量:spentTokens 直接取 usage-updated 载荷,nodesUsed 按实例首次派发计数", () => {
  9970. // docs/dynamic-workflow/authoring.md:事件自带已花总量(不再是剩余量 + 派生字段),
  9971. // 步数由派发事件计数(不再从上限反算——没有上限了)。同一实例重复派发不重复计数。
  9972. const log = startedLog({ maxConcurrency: 4 });
  9973. progress(log, "usage-updated", { spentTokens: 1_234 });
  9974. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9975. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9976. progress(log, "node-dispatched", { instance: { siteId: "ask#2", ordinal: 1 } });
  9977. expect(runsOf(log)?.runs[0]?.usage).toEqual({
  9978. spentTokens: 1_234,
  9979. nodesUsed: 2,
  9980. });
  9981. });
  9982. /**
  9983. * 终态事件产**一条** `workflowRun.updated`,把这条 run 的结算事实(status / error)一次落地。
  9984. *
  9985. * 这里刻意不再断言「终态 patch 是整键替换、丢光中间态也能收口」:改成键级增量之后,丢失的
  9986. * 中间 op 不再被下一条事件顺带补回来——那份自愈让位给了帧的 seq 连续性判定与 snapshot 重同步
  9987. * (客户端 fromSeq 对不上就整份重取)。终态事实照旧在这一条 op 里,一条也没少。
  9988. */
  9989. it("run-settled 产一条该 run 的键级增量:结算事实一次落地", () => {
  9990. const log = startedLog();
  9991. progress(log, "node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" });
  9992. const settled = progress(log, "run-settled", {
  9993. status: "errored",
  9994. error: { code: "ReportCapExceeded", message: "报告条数超过上限" },
  9995. });
  9996. const { projection, deltasPerEvent } = runAll(log.events);
  9997. const terminalDeltas = deltasPerEvent[log.events.indexOf(settled)]!;
  9998. expect(terminalDeltas).toHaveLength(1);
  9999. const updated = terminalDeltas[0]!;
  10000. expect(updated.op).toBe("workflowRun.updated");
  10001. const op = updated as {
  10002. op: "workflowRun.updated";
  10003. runId: string;
  10004. revision: number;
  10005. run?: { status?: string; error?: string };
  10006. nodes?: unknown[];
  10007. };
  10008. expect(op.runId).toBe(RUN_ID);
  10009. expect(op.run).toMatchObject({ status: "errored", error: "报告条数超过上限" });
  10010. // 节点这一步没动,所以这条增量里一条节点都不带——线上的字节与**改动量**成正比。
  10011. expect(op.nodes).toBeUndefined();
  10012. expect(op.revision).toBe(projection.getSnapshot().workflowRuns?.revision);
  10013. const run = projection.getSnapshot().workflowRuns?.runs[0];
  10014. expect(run?.status).toBe("errored");
  10015. expect(run?.nodes).toHaveLength(1);
  10016. });
  10017. it("resume:同 runId 再收 run-started 时清掉上一世的 error(进程内 cancel→resume)", () => {
  10018. // run-started 分支原样展开旧条目:cancel → resume 不经重启时,run 以 running 重现
  10019. // 却还挂着上一世的结算错误——一个正在跑的 run 同时展示失败文案。
  10020. const log = startedLog();
  10021. progress(log, "run-settled", {
  10022. status: "stopped",
  10023. stopReason: "interrupted",
  10024. error: { code: "Interrupted", message: "owning process exited" },
  10025. });
  10026. progress(log, "run-started", { runId: RUN_ID, caps: { maxConcurrency: 4 } });
  10027. const runs = runsOf(log)?.runs ?? [];
  10028. expect(runs).toHaveLength(1);
  10029. expect(runs[0]).toMatchObject({ runId: RUN_ID, status: "running" });
  10030. expect(runs[0]?.error).toBeUndefined();
  10031. expect(runs[0]?.resultPreview).toBeUndefined();
  10032. });
  10033. it("revision 单调,lastEventSequence 随 journal sequence 抬升", () => {
  10034. const log = startedLog();
  10035. progress(log, "node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" });
  10036. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  10037. const { snapshots } = runAll(log.events);
  10038. const revisions = snapshots
  10039. .map((snapshot) => snapshot.workflowRuns?.revision)
  10040. .filter((revision): revision is number => revision !== undefined);
  10041. expect(revisions).toEqual([1, 2, 3]);
  10042. expect(snapshots.at(-1)?.workflowRuns?.runs[0]?.lastEventSequence).toBe(2);
  10043. });
  10044. it("四个数组的界:nodes 超上限置 truncated 且不再增长,被拒实例进计数器", () => {
  10045. const rejected = 5;
  10046. const log = startedLog();
  10047. for (let ordinal = 1; ordinal <= WORKFLOW_RUNS_LIMITS.maxNodes + rejected; ordinal += 1) {
  10048. progress(log, "node-queued", { instance: { siteId: "ask#1", ordinal }, kind: "ask" });
  10049. }
  10050. const run = runsOf(log)?.runs[0];
  10051. expect(run?.nodes).toHaveLength(WORKFLOW_RUNS_LIMITS.maxNodes);
  10052. expect(run?.truncated).toBe(true);
  10053. // `truncated` 只说得出「有东西没进来」;到底少了几步要靠计数器,否则读面上的步数
  10054. // 会比真实步数小,而且小多少没人说得清。
  10055. expect(run?.usage.nodesUnlisted).toBe(rejected);
  10056. expect(run?.usage.nodesUnlistedSettled).toBeUndefined();
  10057. // 读面唯一允许的步数读法 = 表内 + 表外。
  10058. expect(workflowRunStepCounts(run!)).toEqual({
  10059. total: WORKFLOW_RUNS_LIMITS.maxNodes + rejected,
  10060. settled: 0,
  10061. });
  10062. // 已在表内的实例仍可继续更新相位(超界只拒绝**新**实例)。
  10063. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  10064. expect(runsOf(log)?.runs[0]?.nodes[0]?.phase).toBe("dispatched");
  10065. // 表外实例的结算同样要数得出来:它一条节点行都没有,只能落在第二个计数器上。
  10066. progress(log, "node-settled", {
  10067. instance: { siteId: "ask#1", ordinal: WORKFLOW_RUNS_LIMITS.maxNodes + 1 },
  10068. outcome: "ok",
  10069. });
  10070. const settledRun = runsOf(log)!.runs[0]!;
  10071. expect(settledRun.usage.nodesUnlistedSettled).toBe(1);
  10072. expect(workflowRunStepCounts(settledRun)).toEqual({
  10073. total: WORKFLOW_RUNS_LIMITS.maxNodes + rejected,
  10074. settled: 1,
  10075. });
  10076. });
  10077. /**
  10078. * 一条引擎事件 → **一条**该 run 的键级增量,且只带动过的那条节点。
  10079. *
  10080. * 这一条是整次改造的验收点:旧编码在这里会重发整张表(此处 16 条节点),线上的字节因此与
  10081. * 状态大小成正比而不是与改动量成正比——O(N) 字节/事件、O(N²)/run,节点上界与宽 fan-out
  10082. * 撞界丢实例都是这笔账的下游。
  10083. */
  10084. it("一条事件只发动过的那条节点,别的 run 一个字节都不带", () => {
  10085. const log = startedLog();
  10086. for (let ordinal = 1; ordinal <= 16; ordinal += 1) {
  10087. progress(log, "node-queued", { instance: { siteId: "ask#1", ordinal }, kind: "ask" });
  10088. }
  10089. // 第二条 run:它这一步没变化,所以不该出现在增量里。
  10090. log.push(SessionEventType.DynamicWorkflowRunProgress, {
  10091. runId: "dwfrun-other",
  10092. sequence: 0,
  10093. eventType: "run-started",
  10094. payload: { runId: "dwfrun-other", caps: { maxConcurrency: 1 } },
  10095. });
  10096. const dispatched = progress(log, "node-dispatched", {
  10097. instance: { siteId: "ask#1", ordinal: 7 },
  10098. });
  10099. const { deltasPerEvent, projection } = runAll(log.events);
  10100. const deltas = deltasPerEvent[log.events.indexOf(dispatched)]!;
  10101. expect(deltas).toHaveLength(1);
  10102. const op = deltas[0] as {
  10103. op: string;
  10104. runId: string;
  10105. nodes?: { siteId: string; ordinal: number; phase: string; kind?: string }[];
  10106. run?: Record<string, unknown>;
  10107. actors?: unknown[];
  10108. };
  10109. expect(op.op).toBe("workflowRun.updated");
  10110. expect(op.runId).toBe(RUN_ID);
  10111. expect(op.nodes).toEqual([{ siteId: "ask#1", ordinal: 7, kind: "ask", phase: "dispatched" }]);
  10112. expect(op.actors).toBeUndefined();
  10113. // header 只带真的动过的键(水位与派发计数),不含 nodes/actors 之外的整表。
  10114. expect(Object.keys(op.run ?? {}).toSorted()).toEqual(["lastEventSequence", "usage"]);
  10115. // 增量应用回去之后,权威状态仍是归约本身的产物(契约:逐字节一致)。
  10116. const authoritative = projection.getSnapshot().workflowRuns!;
  10117. expect(authoritative.runs.map((run) => run.runId)).toEqual([RUN_ID, "dwfrun-other"]);
  10118. expect(authoritative.runs[0]!.nodes).toHaveLength(16);
  10119. expect(authoritative.runs[0]!.nodes[6]).toEqual({
  10120. siteId: "ask#1",
  10121. ordinal: 7,
  10122. kind: "ask",
  10123. phase: "dispatched",
  10124. });
  10125. });
  10126. it("run 被条数界淘汰时发 workflowRun.removed(只有生产者淘汰,而且必须说出来)", () => {
  10127. const log = new EventLog();
  10128. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  10129. for (let index = 0; index <= WORKFLOW_RUNS_LIMITS.maxRuns; index += 1) {
  10130. log.push(SessionEventType.DynamicWorkflowRunProgress, {
  10131. runId: `dwfrun-${index}`,
  10132. sequence: 0,
  10133. eventType: "run-started",
  10134. payload: { runId: `dwfrun-${index}`, caps: { maxConcurrency: 1 } },
  10135. });
  10136. }
  10137. const { deltasPerEvent } = runAll(log.events);
  10138. // 第 9 条 run 出生的那一条事件同时淘汰了第 1 条:淘汰先发,出生随后。
  10139. const evicting = deltasPerEvent.at(-1)!;
  10140. expect(evicting.map((delta) => delta.op)).toEqual([
  10141. "workflowRun.removed",
  10142. "workflowRun.updated",
  10143. ]);
  10144. expect((evicting[0] as { runId: string }).runId).toBe("dwfrun-0");
  10145. expect((evicting[1] as { runId: string }).runId).toBe(`dwfrun-${WORKFLOW_RUNS_LIMITS.maxRuns}`);
  10146. });
  10147. it("runs ≤ 8 且按最旧淘汰", () => {
  10148. const log = new EventLog();
  10149. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  10150. for (let index = 0; index < WORKFLOW_RUNS_LIMITS.maxRuns + 3; index += 1) {
  10151. log.push(SessionEventType.DynamicWorkflowRunProgress, {
  10152. runId: `dwfrun-${index}`,
  10153. sequence: 0,
  10154. eventType: "run-started",
  10155. payload: { runId: `dwfrun-${index}`, caps: { maxConcurrency: 1 } },
  10156. });
  10157. }
  10158. const runs = runAll(log.events).projection.getSnapshot().workflowRuns?.runs ?? [];
  10159. expect(runs.map((run) => run.runId)).toEqual([
  10160. "dwfrun-3",
  10161. "dwfrun-4",
  10162. "dwfrun-5",
  10163. "dwfrun-6",
  10164. "dwfrun-7",
  10165. "dwfrun-8",
  10166. "dwfrun-9",
  10167. "dwfrun-10",
  10168. ]);
  10169. });
  10170. it("log 与 usage 事件不进图:它们没有 site id,只进事件日志", () => {
  10171. const log = startedLog();
  10172. progress(log, "log", { message: "开始" });
  10173. const run = runsOf(log)?.runs[0];
  10174. expect(run?.nodes).toEqual([]);
  10175. expect(run?.actors).toEqual([]);
  10176. // 但它仍抬升 lastEventSequence——事件日志需要知道有新内容可取。
  10177. expect(run?.lastEventSequence).toBe(1);
  10178. });
  10179. // R-10:两个 profile 的终态必须逐字节一致,所以 workflowRuns 的增量一条都不能被 profile 过滤
  10180. // 掉(`profiles.ts` 只滤 row.delta)。桌面 continuous 与手机 replayable 收到的是同一串 op。
  10181. it("键级增量不受 delivery profile 门控(记录在案的偏离)", () => {
  10182. const log = startedLog();
  10183. const dispatched = progress(log, "node-dispatched", {
  10184. instance: { siteId: "ask#1", ordinal: 1 },
  10185. });
  10186. const { deltasPerEvent } = runAll(log.events);
  10187. const deltas = deltasPerEvent[log.events.indexOf(dispatched)]!;
  10188. expect(deltas.some((delta) => delta.op === "workflowRun.updated")).toBe(true);
  10189. for (const profile of Object.values(DELIVERY_PROFILES) as DeliveryProfile[]) {
  10190. expect(filterConversationDeltasForProfile(deltas, profile)).toEqual(deltas);
  10191. }
  10192. });
  10193. it("同一 run 的重复事件幂等:内容不变不产 delta", () => {
  10194. const log = startedLog();
  10195. progress(log, "node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" });
  10196. const { projection } = runAll(log.events);
  10197. const before = projection.getSnapshot().workflowRuns?.revision;
  10198. // 同一条事件重放(同 sequence、同内容)。
  10199. const replay = log.events.at(-1)!;
  10200. expect(projection.applyEvent(replay)).toEqual([]);
  10201. expect(projection.getSnapshot().workflowRuns?.revision).toBe(before);
  10202. });
  10203. // ── report 事件 → reports[](docs/dynamic-workflow/presentation.md「The run pane」)──
  10204. // 数据面是详情页 Results 区的全部输入;Results 区本身在 packages/ui 的 jsdom 用例里钉。
  10205. it("report 事件按顺序追加进 reports[]:string 原样,object 走 pretty JSON", () => {
  10206. const log = startedLog();
  10207. progress(log, "report", {
  10208. instance: { siteId: "report#1", ordinal: 1 },
  10209. item: "3 stale imports",
  10210. });
  10211. progress(log, "report", {
  10212. instance: { siteId: "report#2", ordinal: 1 },
  10213. item: { file: "a.ts", severity: "warn" },
  10214. });
  10215. const snapshot = runAll(log.events).projection.getSnapshot();
  10216. expect(snapshot.workflowRuns?.runs[0]?.reports).toEqual([
  10217. { siteId: "report#1", ordinal: 1, preview: "3 stale imports" },
  10218. {
  10219. siteId: "report#2",
  10220. ordinal: 1,
  10221. preview: '{\n "file": "a.ts",\n "severity": "warn"\n}',
  10222. },
  10223. ]);
  10224. expect(conversationSnapshotSchema.safeParse(snapshot).success).toBe(true);
  10225. });
  10226. it("零条 report 时 reports 键整个缺席(Results 区据此整区不渲染)", () => {
  10227. const log = startedLog();
  10228. progress(log, "node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" });
  10229. expect(runsOf(log)?.runs[0]).not.toHaveProperty("reports");
  10230. });
  10231. /**
  10232. * 这一条是 report 与 node 分类的凭证:report 有 site 身份、进 journal、有自己的 RunEvent,
  10233. * 但它**不是 step**。混进 nodes[] 的代价是可观测的——紧凑卡与任务岛的 `settled/observed`
  10234. * 步数读的就是 nodes,一个报得勤的工作流会显得步数虚高,状态叠加也会多亮一格。
  10235. */
  10236. it("report 不进 nodes[]/actors,也不动 nodesUsed;但抬升 lastEventSequence", () => {
  10237. const log = startedLog({ maxConcurrency: 4 });
  10238. progress(log, "node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" });
  10239. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  10240. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: "a finding" });
  10241. const run = runsOf(log)?.runs[0];
  10242. expect(run?.nodes.map((node) => node.siteId)).toEqual(["ask#1"]);
  10243. expect(run?.actors).toEqual([]);
  10244. expect(run?.usage.nodesUsed).toBe(1);
  10245. expect(run?.reports).toHaveLength(1);
  10246. // 事件日志要知道有新内容可取,所以水位照常抬升。
  10247. expect(run?.lastEventSequence).toBe(3);
  10248. });
  10249. it("失败结算之后 reports 原样留着:捞回半途产物正是 report 存在的理由", () => {
  10250. const log = startedLog();
  10251. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: "finding 1" });
  10252. progress(log, "run-settled", {
  10253. status: "errored",
  10254. error: { code: "DriverError", message: "boom" },
  10255. });
  10256. const run = runsOf(log)?.runs[0];
  10257. expect(run?.status).toBe("errored");
  10258. expect(run?.reports).toEqual([{ siteId: "report#1", ordinal: 1, preview: "finding 1" }]);
  10259. });
  10260. it("同一 report 事件重放(同 sequence 同内容)不产 delta、不重复条目", () => {
  10261. const log = startedLog();
  10262. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: "once" });
  10263. const { projection } = runAll(log.events);
  10264. const before = projection.getSnapshot().workflowRuns?.revision;
  10265. expect(projection.applyEvent(log.events.at(-1)!)).toEqual([]);
  10266. expect(projection.getSnapshot().workflowRuns?.revision).toBe(before);
  10267. expect(projection.getSnapshot().workflowRuns?.runs[0]?.reports).toHaveLength(1);
  10268. });
  10269. /**
  10270. * 去重键是实例(siteId × ordinal),不是事件 sequence——脚本 replay 时每个 report 调用都会
  10271. * 重跑。所以一条**新 sequence** 却带已见实例的事件只抬水位,绝不把同一条产物列两次。
  10272. */
  10273. it("新 sequence 带已见实例键:水位抬升,条目不重复", () => {
  10274. const log = startedLog();
  10275. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: "once" });
  10276. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: "once" });
  10277. const run = runsOf(log)?.runs[0];
  10278. expect(run?.reports).toEqual([{ siteId: "report#1", ordinal: 1, preview: "once" }]);
  10279. expect(run?.lastEventSequence).toBe(2);
  10280. });
  10281. it("reports 触到 64 条上限:拒绝新条目并置 truncated,已有条目照常更新", () => {
  10282. const log = startedLog();
  10283. for (let ordinal = 1; ordinal <= WORKFLOW_RUNS_LIMITS.maxReports + 3; ordinal += 1) {
  10284. progress(log, "report", {
  10285. instance: { siteId: "report#1", ordinal },
  10286. item: `finding ${ordinal}`,
  10287. });
  10288. }
  10289. const run = runsOf(log)?.runs[0];
  10290. expect(run?.reports).toHaveLength(WORKFLOW_RUNS_LIMITS.maxReports);
  10291. expect(run?.truncated).toBe(true);
  10292. // 先到的条目不被后来的挤掉(淘汰会让读者以为早期发现丢了;界的语义是拒新)。
  10293. expect(run?.reports?.[0]?.preview).toBe("finding 1");
  10294. // 触界之后其余键照常更新:结算与水位都不受影响。
  10295. progress(log, "run-settled", { status: "completed" });
  10296. const settled = runsOf(log)?.runs[0];
  10297. expect(settled?.status).toBe("completed");
  10298. expect(settled?.reports).toHaveLength(WORKFLOW_RUNS_LIMITS.maxReports);
  10299. });
  10300. it("单条预览超界即截断(带省略号),仍过 strict schema", () => {
  10301. const log = startedLog();
  10302. // 载荷有界化已经把单个字符串削到 2048,所以真正会超界的是「键多的对象展开成 pretty JSON」。
  10303. const wide: Record<string, string> = {};
  10304. for (let index = 0; index < 64; index += 1) wide[`key${index}`] = "x".repeat(64);
  10305. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: wide });
  10306. const snapshot = runAll(log.events).projection.getSnapshot();
  10307. const preview = snapshot.workflowRuns?.runs[0]?.reports?.[0]?.preview ?? "";
  10308. expect(preview.length).toBe(WORKFLOW_RUNS_LIMITS.maxReportPreviewLength);
  10309. expect(preview.endsWith("…")).toBe(true);
  10310. expect(conversationSnapshotSchema.safeParse(snapshot).success).toBe(true);
  10311. });
  10312. it("instance 缺失的 report 事件被忽略(不造无身份条目),但仍抬水位", () => {
  10313. const log = startedLog();
  10314. progress(log, "report", { item: "orphan" });
  10315. const run = runsOf(log)?.runs[0];
  10316. expect(run).not.toHaveProperty("reports");
  10317. expect(run?.lastEventSequence).toBe(1);
  10318. });
  10319. });
  10320. // 中枢直接启动已保存工作流(docs/dynamic-workflow/launch.md):controlOnly 启动轮的活投影。
  10321. // TurnStarted(workflow_launch) → turnHeader/userInput 双行 origin=workflowLaunch + 同一份元数据,
  10322. // 无助手行;TurnComplete 收口后 header 变 completed(controlOnly 不下发 running/工时)。
  10323. describe("workflow-direct-launch 启动轮投影", () => {
  10324. const workflowLaunch = {
  10325. runId: "dwfrun-9",
  10326. toolCallId: "launch-abc",
  10327. name: "deep-research",
  10328. scope: "global" as const,
  10329. path: "/home/u/.zcode/workflows/deep-research.ts",
  10330. args: { topic: "adaptive concurrency" },
  10331. description: "Deep-dive a topic",
  10332. };
  10333. function launchEvents(): SessionEvent[] {
  10334. const log = new EventLog();
  10335. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  10336. log.push(
  10337. SessionEventType.TurnStarted,
  10338. {
  10339. turnNumber: 1,
  10340. input: 'Started the saved workflow "deep-research" (global) as run dwfrun-9.',
  10341. messageId: "message-launch-1",
  10342. executionKind: "controlOnly",
  10343. inputSource: "workflow_launch",
  10344. workflowLaunch,
  10345. },
  10346. { turnId: "turn-launch" },
  10347. );
  10348. log.push(
  10349. SessionEventType.TurnComplete,
  10350. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  10351. { turnId: "turn-launch" },
  10352. );
  10353. return log.events;
  10354. }
  10355. it("双行 origin=workflowLaunch 且都带启动元数据,无助手行", () => {
  10356. const snapshot = runAll(launchEvents()).projection.getSnapshot();
  10357. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  10358. const rows = snapshot.rows.window;
  10359. expect(rows.map((row) => row.kind)).toEqual(["turnHeader", "userInput"]);
  10360. const header = rows.find((row) => row.kind === "turnHeader");
  10361. expect(header).toMatchObject({
  10362. origin: "workflowLaunch",
  10363. executionKind: "controlOnly",
  10364. state: "completedSuccess",
  10365. workflowLaunch,
  10366. });
  10367. const userInput = rows.find((row) => row.kind === "userInput");
  10368. expect(userInput).toMatchObject({
  10369. origin: "workflowLaunch",
  10370. text: 'Started the saved workflow "deep-research" (global) as run dwfrun-9.',
  10371. workflowLaunch,
  10372. });
  10373. // controlOnly:不残留 running / activeWorks(旧 UI 会把 0ms 误显示成「已工作 1 秒」)。
  10374. expect(snapshot.control.activeWorks).toEqual([]);
  10375. });
  10376. it("启动轮收口让会话离开 draft:phase 成终态,sessions-index 摘要不再被当 draft 丢弃", () => {
  10377. // 2026-09-14 实机:只有一条 controlOnly 启动轮的会话活投影恒为 draft,task-index syncer 丢弃 draft
  10378. // 摘要,侧栏要等重启(store 种子给出终态 phase)才出现。冷热必须同形。
  10379. const events = launchEvents();
  10380. const { projection } = runAll(events.slice(0, 2));
  10381. expect(projection.getSnapshot().control.phase).toBe("draft");
  10382. projection.applyEvent(events[2]!);
  10383. const control = projection.getSnapshot().control;
  10384. expect(control.phase).toBe("completedSuccess");
  10385. expect(control.sessionEnded).toBe(true);
  10386. expect(control.canStop).toBe(false);
  10387. expect(control.activeWorks).toEqual([]);
  10388. });
  10389. it("非 draft 会话上的 controlOnly 轮照旧不碰 session control", () => {
  10390. const log = new EventLog();
  10391. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  10392. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  10393. log.push(
  10394. SessionEventType.TurnComplete,
  10395. { response: "", tokenCount: 0, toolCallCount: 0, duration: 5, resultType: "cancelled" },
  10396. { turnId: "turn-1" },
  10397. );
  10398. log.push(
  10399. SessionEventType.TurnStarted,
  10400. { turnNumber: 2, input: "/goal x", executionKind: "controlOnly" },
  10401. { turnId: "turn-2" },
  10402. );
  10403. log.push(
  10404. SessionEventType.TurnComplete,
  10405. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  10406. { turnId: "turn-2" },
  10407. );
  10408. const snapshot = runAll(log.events).projection.getSnapshot();
  10409. // 上一轮的中断终态保留,控制轮的 success 不改写它。
  10410. expect(snapshot.control.phase).toBe("completedInterrupted");
  10411. });
  10412. });
  10413. // docs/dynamic-workflow/transcript-and-notifications.md:TurnStarted 上的 epilogueStart 原样落到
  10414. // userInput 行;缺席时行上没有这个键(老转录逐字不变)。
  10415. describe("userInput 行的 epilogueStart(热路径)", () => {
  10416. it("透传 TurnStarted.epilogueStart;缺席不写键", () => {
  10417. const log = new EventLog();
  10418. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  10419. log.push(
  10420. SessionEventType.TurnStarted,
  10421. { turnNumber: 1, input: "Summarize\n\n---\nStandard", epilogueStart: 9 },
  10422. { turnId: "turn-1" },
  10423. );
  10424. log.push(SessionEventType.TurnStarted, { turnNumber: 2, input: "plain" }, { turnId: "turn-2" });
  10425. const { projection } = runAll(log.events);
  10426. const rows = projection.getSnapshot().rows.window.filter((row) => row.kind === "userInput");
  10427. expect(rows[0]).toMatchObject({ text: "Summarize\n\n---\nStandard", epilogueStart: 9 });
  10428. expect(rows[1]).not.toHaveProperty("epilogueStart");
  10429. });
  10430. });