product-projection.test.ts 362 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602
  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("preserves topic originals and attachment ownership when replaying accepted turn events", () => {
  582. const source = {
  583. provider: "feishu",
  584. botId: "bot",
  585. chatId: "group",
  586. threadId: "topic",
  587. senderId: "b",
  588. senderName: "Bob",
  589. messageId: "second",
  590. messages: [
  591. {
  592. messageId: "first",
  593. senderId: "a",
  594. senderName: "Alice",
  595. text: "First",
  596. attachmentIndexes: [0],
  597. conversationQuotes: [{ text: "Root", senderName: "Root author" }],
  598. },
  599. {
  600. messageId: "second",
  601. senderId: "b",
  602. senderName: "Bob",
  603. text: "Second",
  604. attachmentIndexes: [1],
  605. },
  606. ],
  607. };
  608. const log = new EventLog();
  609. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  610. log.push(
  611. SessionEventType.TurnStarted,
  612. {
  613. turnNumber: 1,
  614. input: "combined",
  615. messageId: "accepted",
  616. inputId: "command",
  617. intent: {
  618. sourceCommandId: "command",
  619. kind: "sendText",
  620. text: "combined",
  621. admissionSeq: 1,
  622. admittedAt: 10,
  623. requestedDelivery: "startNow",
  624. admittedDelivery: "startNow",
  625. botGroupSource: source,
  626. attachmentRefs: [
  627. { ref: "artifact://first", fileName: "first.txt", mime: "text/plain", bytes: 1 },
  628. { ref: "artifact://second", fileName: "second.txt", mime: "text/plain", bytes: 1 },
  629. ],
  630. },
  631. },
  632. { turnId: "topic-turn" },
  633. );
  634. const restored = log.events.map((event) => ({
  635. ...event,
  636. payload: JSON.parse(JSON.stringify(event.payload)),
  637. }));
  638. const snapshot = conversationSnapshotSchema.parse(runAll(restored).projection.getSnapshot());
  639. expect(snapshot.rows.window.find((row) => row.kind === "userInput")).toMatchObject({
  640. botGroupSource: source,
  641. attachments: [{ ref: "artifact://first" }, { ref: "artifact://second" }],
  642. });
  643. });
  644. it("TEL06:edit/rerun user row 保留 canonical root sourceCommandId", () => {
  645. const log = new EventLog();
  646. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  647. log.push(
  648. SessionEventType.TurnStarted,
  649. {
  650. turnNumber: 1,
  651. input: "retry prompt",
  652. messageId: "user-retry",
  653. inputId: "command-edit",
  654. foregroundExecutionId: "foreground-edit",
  655. intent: {
  656. sourceCommandId: "command-edit",
  657. queueItemId: "queue-edit",
  658. clientId: "desktop",
  659. kind: "sendText",
  660. text: "retry prompt",
  661. admissionSeq: 2,
  662. admittedAt: 1_700_000_000_000,
  663. requestedDelivery: "startNow",
  664. admittedDelivery: "startNow",
  665. provenance: { sourceCommandId: "command-original" },
  666. },
  667. },
  668. { turnId: "turn-retry" },
  669. );
  670. const { projection } = runAll(log.events);
  671. expect(conversationSnapshotSchema.parse(projection.getSnapshot()).control.activeWorks).toEqual([
  672. expect.objectContaining({
  673. foregroundExecutionId: "foreground-edit",
  674. sourceCommandId: "command-edit",
  675. }),
  676. ]);
  677. expect(
  678. projection.getSnapshot().rows.window.find((row) => row.kind === "userInput"),
  679. ).toMatchObject({
  680. sourceCommandId: "command-edit",
  681. rootSourceCommandId: "command-original",
  682. productTurnId: "user-retry",
  683. });
  684. });
  685. it("PV4-08:只给 completedSuccess 轮尾 assistant 下发 canFork,后续 turn running 时仍稳定", () => {
  686. const log = new EventLog();
  687. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  688. log.push(
  689. SessionEventType.TurnStarted,
  690. { turnNumber: 1, input: "first", messageId: "user-1" },
  691. { turnId: "turn-1" },
  692. );
  693. log.push(
  694. SessionEventType.ModelStreaming,
  695. { kind: "text_start", delta: "", done: false, assistantMessageId: "assistant-1" },
  696. { turnId: "turn-1" },
  697. );
  698. log.push(
  699. SessionEventType.ModelStreaming,
  700. { kind: "text_end", delta: "", done: false },
  701. { turnId: "turn-1" },
  702. );
  703. log.push(
  704. SessionEventType.TurnComplete,
  705. { response: "done", tokenCount: 1, toolCallCount: 0, duration: 1, resultType: "success" },
  706. { turnId: "turn-1" },
  707. );
  708. log.push(
  709. SessionEventType.TurnStarted,
  710. { turnNumber: 2, input: "second", messageId: "user-2" },
  711. { turnId: "turn-2" },
  712. );
  713. const { projection } = runAll(log.events);
  714. const firstAssistant = projection
  715. .getSnapshot()
  716. .rows.window.find((row) => row.kind === "assistantText" && row.turnId === "user-1");
  717. expect(firstAssistant?.actions).toEqual({ canFork: true });
  718. expect(projection.resolveStableForkCandidate(firstAssistant!.rowId)).toEqual({
  719. ok: true,
  720. candidate: {
  721. boundaryMessageId: "assistant-1",
  722. productTurnId: "user-1",
  723. startMessageId: "user-1",
  724. transcriptTurnId: "turn-1",
  725. },
  726. });
  727. expect(projection.getSnapshot().control.phase).toBe("running");
  728. });
  729. it("PV4-08:成功轮固化 fork 能力时不复制并反转完整 rows 窗口", () => {
  730. const log = new EventLog();
  731. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  732. log.push(
  733. SessionEventType.TurnStarted,
  734. { turnNumber: 1, input: "first", messageId: "user-1" },
  735. { turnId: "turn-1" },
  736. );
  737. log.push(
  738. SessionEventType.ModelStreaming,
  739. { kind: "text_start", delta: "", done: false, assistantMessageId: "assistant-1" },
  740. { turnId: "turn-1" },
  741. );
  742. log.push(
  743. SessionEventType.ModelStreaming,
  744. { kind: "text_end", delta: "", done: false },
  745. { turnId: "turn-1" },
  746. );
  747. const { projection } = runAll(log.events);
  748. const reverse = vi.spyOn(Array.prototype, "reverse").mockImplementation(() => {
  749. throw new Error("TurnComplete must not reverse the full rows window");
  750. });
  751. try {
  752. projection.applyEvent(
  753. log.push(
  754. SessionEventType.TurnComplete,
  755. {
  756. response: "done",
  757. tokenCount: 1,
  758. toolCallCount: 0,
  759. duration: 1,
  760. resultType: "success",
  761. },
  762. { turnId: "turn-1" },
  763. ),
  764. );
  765. } finally {
  766. reverse.mockRestore();
  767. }
  768. const assistant = projection
  769. .getSnapshot()
  770. .rows.window.find((row) => row.kind === "assistantText");
  771. expect(assistant?.actions?.canFork).toBe(true);
  772. });
  773. it("PV4-08:中间 assistant 段和 interrupted turn 都不可 fork", () => {
  774. const log = new EventLog();
  775. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  776. log.push(
  777. SessionEventType.TurnStarted,
  778. { turnNumber: 1, input: "first", messageId: "user-1" },
  779. { turnId: "turn-1" },
  780. );
  781. log.push(
  782. SessionEventType.ModelStreaming,
  783. { kind: "text_start", delta: "", done: false, assistantMessageId: "assistant-1a" },
  784. { turnId: "turn-1" },
  785. );
  786. log.push(
  787. SessionEventType.ModelStreaming,
  788. { kind: "text_end", delta: "", done: false },
  789. { turnId: "turn-1" },
  790. );
  791. log.push(
  792. SessionEventType.ModelStreaming,
  793. { kind: "text_start", delta: "", done: false, assistantMessageId: "assistant-1b" },
  794. { turnId: "turn-1" },
  795. );
  796. log.push(
  797. SessionEventType.TurnComplete,
  798. {
  799. response: "partial",
  800. tokenCount: 1,
  801. toolCallCount: 0,
  802. duration: 1,
  803. resultType: "cancelled",
  804. },
  805. { turnId: "turn-1" },
  806. );
  807. const { projection } = runAll(log.events);
  808. const assistants = projection
  809. .getSnapshot()
  810. .rows.window.filter((row) => row.kind === "assistantText");
  811. expect(assistants.every((row) => row.actions?.canFork !== true)).toBe(true);
  812. expect(projection.resolveStableForkCandidate(assistants[0]!.rowId)).toEqual({
  813. ok: false,
  814. reasonCode: "guard.forkTargetNotStable",
  815. });
  816. expect(projection.resolveStableForkCandidate(assistants[1]!.rowId)).toEqual({
  817. ok: false,
  818. reasonCode: "guard.forkTargetNotStable",
  819. });
  820. });
  821. it("OTC08:同一 turn 的 output-limit Continue 只投影一条累计 assistantText", () => {
  822. const log = new EventLog();
  823. const turnId = "turn-output-continue";
  824. const appendAssistantResponse = (
  825. assistantMessageId: string,
  826. partId: string,
  827. text: string,
  828. stopReason: "length" | "end_turn",
  829. ) => {
  830. log.push(
  831. SessionEventType.ModelStreaming,
  832. {
  833. kind: "text_start",
  834. delta: "",
  835. done: false,
  836. assistantMessageId,
  837. partId,
  838. },
  839. { turnId },
  840. );
  841. log.push(
  842. SessionEventType.ModelStreaming,
  843. { kind: "text_delta", delta: text, done: false, assistantMessageId, partId },
  844. { turnId },
  845. );
  846. log.push(
  847. SessionEventType.ModelStreaming,
  848. { kind: "text_end", delta: "", done: false, assistantMessageId, partId },
  849. { turnId },
  850. );
  851. log.push(
  852. SessionEventType.ModelComplete,
  853. {
  854. content: text,
  855. stopReason,
  856. querySource: "main_turn",
  857. toolCallCount: 0,
  858. usage: {
  859. inputTokens: 1,
  860. outputTokens: 1,
  861. cacheReadTokens: 0,
  862. cacheWriteTokens: 0,
  863. },
  864. },
  865. { turnId },
  866. );
  867. };
  868. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  869. log.push(
  870. SessionEventType.TurnStarted,
  871. { turnNumber: 1, input: "写一段长回复", messageId: "user-output-continue" },
  872. { turnId },
  873. );
  874. appendAssistantResponse("assistant-p1", "part-p1", "即使底层已经", "length");
  875. appendAssistantResponse("assistant-p2", "part-p2", "发起新的请求并停在", "length");
  876. appendAssistantResponse("assistant-p3", "part-p3", "一个尚未完成的位置。", "end_turn");
  877. log.push(
  878. SessionEventType.TurnComplete,
  879. {
  880. response: "一个尚未完成的位置。",
  881. tokenCount: 3,
  882. toolCallCount: 0,
  883. duration: 3_000,
  884. resultType: "success",
  885. },
  886. { turnId },
  887. );
  888. const { projection, deltasPerEvent } = runAll(log.events);
  889. const assistantRows = projection
  890. .getSnapshot()
  891. .rows.window.filter((row) => row.kind === "assistantText");
  892. expect(assistantRows).toHaveLength(1);
  893. expect(assistantRows[0]).toMatchObject({
  894. text: "即使底层已经发起新的请求并停在一个尚未完成的位置。",
  895. state: "complete",
  896. assistantResponseId: "assistant-p3",
  897. entityId: "assistant-p3",
  898. actions: { canFork: true },
  899. });
  900. expect(
  901. deltasPerEvent
  902. .flat()
  903. .filter((delta) => delta.op === "row.appended" && delta.row.kind === "assistantText"),
  904. ).toHaveLength(1);
  905. expect(projection.getMessageIdForRow(assistantRows[0]!.rowId)).toBe("assistant-p3");
  906. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  907. expect(projection.getMessageIdsForTurnRow(header!.rowId)).toEqual(
  908. expect.arrayContaining([
  909. "user-output-continue",
  910. "assistant-p1",
  911. "assistant-p2",
  912. "assistant-p3",
  913. ]),
  914. );
  915. });
  916. it("OTC08:异步 session-title ModelComplete 不清除主 turn 的 Continue 资格", () => {
  917. const log = new EventLog();
  918. const turnId = "turn-output-continue-with-title-sidecar";
  919. const appendAssistantResponse = (
  920. assistantMessageId: string,
  921. text: string,
  922. stopReason: "length" | "end_turn",
  923. ) => {
  924. log.push(
  925. SessionEventType.ModelStreaming,
  926. { kind: "text_start", delta: "", done: false, assistantMessageId },
  927. { turnId },
  928. );
  929. log.push(
  930. SessionEventType.ModelStreaming,
  931. { kind: "text_delta", delta: text, done: false, assistantMessageId },
  932. { turnId },
  933. );
  934. log.push(
  935. SessionEventType.ModelStreaming,
  936. { kind: "text_end", delta: "", done: false, assistantMessageId },
  937. { turnId },
  938. );
  939. log.push(
  940. SessionEventType.ModelComplete,
  941. {
  942. content: text,
  943. querySource: "main_turn",
  944. stopReason,
  945. toolCallCount: 0,
  946. usage: {},
  947. },
  948. { turnId },
  949. );
  950. };
  951. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  952. log.push(
  953. SessionEventType.TurnStarted,
  954. { turnNumber: 1, input: "写一段长回复", messageId: "user-output-title-sidecar" },
  955. { turnId },
  956. );
  957. appendAssistantResponse("assistant-title-p1", "主 turn 第一段", "length");
  958. log.push(
  959. SessionEventType.ModelComplete,
  960. {
  961. content: "标题",
  962. querySource: "session_title",
  963. stopReason: "end_turn",
  964. toolCallCount: 0,
  965. usage: {},
  966. },
  967. { turnId },
  968. );
  969. appendAssistantResponse("assistant-title-p2", "继续拼接完成。", "end_turn");
  970. const { projection } = runAll(log.events);
  971. const assistantRows = projection
  972. .getSnapshot()
  973. .rows.window.filter((row) => row.kind === "assistantText");
  974. expect(assistantRows).toHaveLength(1);
  975. expect(assistantRows[0]).toMatchObject({
  976. text: "主 turn 第一段继续拼接完成。",
  977. assistantResponseId: "assistant-title-p2",
  978. state: "complete",
  979. });
  980. });
  981. it.each([
  982. { label: "含工具边界", stopReason: "length", toolCallCount: 1 },
  983. { label: "缺少明确 zero-tool 事实", stopReason: "length", toolCallCount: undefined },
  984. { label: "不是 output-limit", stopReason: "end_turn", toolCallCount: 0 },
  985. ] as const)("OTC08:$label 时不复用 assistantText row", ({ stopReason, toolCallCount }) => {
  986. const log = new EventLog();
  987. const turnId = `turn-output-boundary-${stopReason}-${String(toolCallCount)}`;
  988. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  989. log.push(
  990. SessionEventType.TurnStarted,
  991. { turnNumber: 1, input: "执行工具", messageId: "user-output-tool-boundary" },
  992. { turnId },
  993. );
  994. log.push(
  995. SessionEventType.ModelStreaming,
  996. {
  997. kind: "text_start",
  998. delta: "",
  999. done: false,
  1000. assistantMessageId: "assistant-before-tool",
  1001. },
  1002. { turnId },
  1003. );
  1004. log.push(
  1005. SessionEventType.ModelStreaming,
  1006. { kind: "text_delta", delta: "先执行工具。", done: false },
  1007. { turnId },
  1008. );
  1009. log.push(
  1010. SessionEventType.ModelStreaming,
  1011. { kind: "text_end", delta: "", done: false },
  1012. { turnId },
  1013. );
  1014. log.push(
  1015. SessionEventType.ModelComplete,
  1016. {
  1017. content: "先执行工具。",
  1018. stopReason,
  1019. querySource: "main_turn",
  1020. ...(toolCallCount === undefined ? {} : { toolCallCount }),
  1021. usage: {},
  1022. },
  1023. { turnId },
  1024. );
  1025. log.push(
  1026. SessionEventType.ModelStreaming,
  1027. {
  1028. kind: "text_start",
  1029. delta: "",
  1030. done: false,
  1031. assistantMessageId: "assistant-after-tool",
  1032. },
  1033. { turnId },
  1034. );
  1035. const { projection } = runAll(log.events);
  1036. expect(
  1037. projection.getSnapshot().rows.window.filter((row) => row.kind === "assistantText"),
  1038. ).toHaveLength(2);
  1039. });
  1040. it("A:完整成功 turn —— rows 结构、phase、usage、schema 合法", () => {
  1041. const log = new EventLog();
  1042. basicTurnEvents(log);
  1043. const { projection } = runAll(log.events);
  1044. const snapshot = projection.getSnapshot();
  1045. // schema 合法性(M1 数据模型被 reducer 锤炼的第一道闸)。
  1046. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  1047. const kinds = snapshot.rows.window.map((row) => row.kind);
  1048. expect(kinds).toEqual(["turnHeader", "userInput", "assistantText"]);
  1049. const [header, userInput, assistant] = snapshot.rows.window;
  1050. expect(header).toMatchObject({
  1051. kind: "turnHeader",
  1052. origin: "userInput",
  1053. state: "completedSuccess",
  1054. activeMs: 5000,
  1055. });
  1056. expect(userInput).toMatchObject({
  1057. kind: "userInput",
  1058. text: "写一个 hello world",
  1059. origin: "realUser",
  1060. });
  1061. expect(assistant).toMatchObject({
  1062. kind: "assistantText",
  1063. text: "Hello world",
  1064. state: "complete",
  1065. });
  1066. expect(snapshot.control.phase).toBe("completedSuccess");
  1067. expect(snapshot.control.sessionEnded).toBe(true);
  1068. expect(snapshot.control.canStop).toBe(false);
  1069. expect(snapshot.inputRouting.mode).toBe("startNow");
  1070. expect(snapshot.usage.contextWindow).toEqual({
  1071. usedTokens: 150,
  1072. maxTokens: 200_000,
  1073. autoCompactThresholdTokens: null,
  1074. });
  1075. expect(snapshot.usage.cumulative.inputTokens).toBe(120);
  1076. expect(snapshot.seq).toBe(log.events.length);
  1077. });
  1078. it("A:主轮次 usage 保留 cache 命中率和 context breakdown", () => {
  1079. const log = new EventLog();
  1080. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  1081. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  1082. log.push(
  1083. SessionEventType.ModelComplete,
  1084. {
  1085. content: "done",
  1086. stopReason: "end_turn",
  1087. querySource: "main_turn",
  1088. contextWindow: 200_000,
  1089. usage: {
  1090. inputTokens: 100,
  1091. outputTokens: 20,
  1092. cacheReadTokens: 80,
  1093. cacheWriteTokens: 10,
  1094. },
  1095. cacheHit: {
  1096. inputTokens: 100,
  1097. cacheReadTokens: 80,
  1098. cacheWriteTokens: 10,
  1099. latestHitRate: 0.8,
  1100. hitRate: 0.8,
  1101. hitRateRequestCount: 1,
  1102. totalInputTokens: 100,
  1103. totalCacheReadTokens: 80,
  1104. totalCacheWriteTokens: 10,
  1105. },
  1106. contextUsageBreakdown: [
  1107. { source: "messages", chars: 900 },
  1108. { source: "system_tool_schemas", chars: 100 },
  1109. ],
  1110. },
  1111. { turnId: "turn-1" },
  1112. );
  1113. const { projection } = runAll(log.events);
  1114. const contextWindow = projection.getSnapshot().usage.contextWindow;
  1115. expect(contextWindow?.usedTokens).toBe(120);
  1116. expect(contextWindow?.maxTokens).toBe(200_000);
  1117. expect(contextWindow?.cache).toMatchObject({ hitRate: 0.8, totalCacheReadTokens: 80 });
  1118. expect(contextWindow?.breakdown).toEqual([
  1119. { source: "messages", chars: 900 },
  1120. { source: "system_tool_schemas", chars: 100 },
  1121. ]);
  1122. });
  1123. it("A:sidecar usage 不覆盖输入栏 context cache 和 breakdown", () => {
  1124. const log = new EventLog();
  1125. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  1126. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  1127. log.push(
  1128. SessionEventType.ModelComplete,
  1129. {
  1130. content: "title",
  1131. stopReason: "end_turn",
  1132. querySource: "session_title",
  1133. contextWindow: 200_000,
  1134. usage: {
  1135. inputTokens: 100,
  1136. outputTokens: 20,
  1137. cacheReadTokens: 80,
  1138. cacheWriteTokens: 10,
  1139. },
  1140. cacheHit: {
  1141. inputTokens: 100,
  1142. cacheReadTokens: 80,
  1143. cacheWriteTokens: 10,
  1144. latestHitRate: 0.8,
  1145. hitRate: 0.8,
  1146. hitRateRequestCount: 1,
  1147. totalInputTokens: 100,
  1148. totalCacheReadTokens: 80,
  1149. totalCacheWriteTokens: 10,
  1150. },
  1151. contextUsageBreakdown: [{ source: "messages", chars: 900 }],
  1152. },
  1153. { turnId: "turn-1" },
  1154. );
  1155. const { projection } = runAll(log.events);
  1156. expect(projection.getSnapshot().usage.contextWindow).toBeNull();
  1157. });
  1158. it("A:running 期 inputRouting=enqueue,完成后 startNow", () => {
  1159. const log = new EventLog();
  1160. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1161. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  1162. const { projection } = runAll(log.events);
  1163. expect(projection.getSnapshot().inputRouting.mode).toBe("enqueue");
  1164. // 回归原因:busy 期间 compact 已改为进入 typed FIFO,旧黄金断言仍按直接执行
  1165. // 门禁判为不可用;这里同时补齐标题承诺的完成态路由收口。
  1166. expect(projection.getSnapshot().availability.compact.allowed).toBe(true);
  1167. projection.applyEvent(
  1168. log.push(
  1169. SessionEventType.TurnComplete,
  1170. {
  1171. response: "done",
  1172. tokenCount: 1,
  1173. toolCallCount: 0,
  1174. duration: 100,
  1175. resultType: "success",
  1176. },
  1177. { turnId: "turn-1" },
  1178. ),
  1179. );
  1180. expect(projection.getSnapshot().inputRouting.mode).toBe("startNow");
  1181. });
  1182. it("A:model-only 输入(goal continuation 等)不产生 userInput row", () => {
  1183. const log = new EventLog();
  1184. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1185. log.push(
  1186. SessionEventType.TurnStarted,
  1187. {
  1188. turnNumber: 1,
  1189. input: "continue the goal",
  1190. inputSource: "goal-continuation",
  1191. inputVisibility: "model-only",
  1192. },
  1193. { turnId: "turn-1" },
  1194. );
  1195. const { projection } = runAll(log.events);
  1196. const kinds = projection.getSnapshot().rows.window.map((row) => row.kind);
  1197. expect(kinds).toEqual(["turnHeader"]);
  1198. expect(projection.getSnapshot().rows.window[0]).toMatchObject({
  1199. origin: "goalContinuation",
  1200. });
  1201. });
  1202. it("BG27/BG28:background model-only turn 把结构化标题投影到 turnHeader", () => {
  1203. const log = new EventLog();
  1204. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1205. log.push(
  1206. SessionEventType.TurnStarted,
  1207. {
  1208. turnNumber: 1,
  1209. input: "background result",
  1210. inputSource: "background_task",
  1211. inputVisibility: "model-only",
  1212. originMeta: {
  1213. backgroundSource: "subagent",
  1214. title: "Review the projection chain",
  1215. workId: "agent-review",
  1216. },
  1217. } as never,
  1218. { turnId: "turn-background" },
  1219. );
  1220. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  1221. expect(rows).toHaveLength(1);
  1222. expect(rows[0]).toMatchObject({
  1223. kind: "turnHeader",
  1224. origin: "backgroundResult",
  1225. originMeta: {
  1226. backgroundSource: "subagent",
  1227. title: "Review the projection chain",
  1228. workId: "agent-review",
  1229. },
  1230. });
  1231. });
  1232. it("workflow 终态通知:manifest 载荷随 originMeta 投影到 turnHeader(BG27 姊妹)", () => {
  1233. const log = new EventLog();
  1234. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1235. const workflowNotification = {
  1236. kind: "terminal" as const,
  1237. status: "completed" as const,
  1238. summary: "nightly audit",
  1239. result: "final artifact",
  1240. resultForm: "prose" as const,
  1241. reports: { count: 2, shown: 1, preview: ["第一步"] },
  1242. durationMs: 5_000,
  1243. };
  1244. log.push(
  1245. SessionEventType.TurnStarted,
  1246. {
  1247. turnNumber: 1,
  1248. input: "workflow result",
  1249. inputSource: "background_task",
  1250. inputVisibility: "model-only",
  1251. originMeta: {
  1252. backgroundSource: "workflow",
  1253. title: "nightly audit",
  1254. workId: "dwfrun-proj",
  1255. workflowNotification,
  1256. },
  1257. } as never,
  1258. { turnId: "turn-workflow" },
  1259. );
  1260. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  1261. expect(rows).toHaveLength(1);
  1262. // originMeta 被投影层整体拷贝——manifest 载荷免费搭车,不被逐字段重构剥掉。
  1263. expect(rows[0]).toMatchObject({
  1264. kind: "turnHeader",
  1265. origin: "backgroundResult",
  1266. originMeta: {
  1267. backgroundSource: "workflow",
  1268. title: "nightly audit",
  1269. workId: "dwfrun-proj",
  1270. workflowNotification,
  1271. },
  1272. });
  1273. });
  1274. it("BG26:background Agent 失败通知按 tool-use-id 覆盖 launch ACK 终态", () => {
  1275. const turnId = "turn-agent-launch";
  1276. const toolCallId = "tool-agent-rate-limit";
  1277. const error = "Requests are too frequent. Request id: bg26";
  1278. const result = `Agent general-purpose task \"分析世界杯\" failed. ${error}`;
  1279. const notification = [
  1280. "<task-notification>",
  1281. `<tool-use-id>${toolCallId}</tool-use-id>`,
  1282. "<status>failed</status>",
  1283. `<result>${result}</result>`,
  1284. `<error>${error}</error>`,
  1285. "</task-notification>",
  1286. ].join("\n");
  1287. const log = new EventLog();
  1288. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1289. log.push(
  1290. SessionEventType.TurnStarted,
  1291. { turnNumber: 1, input: "launch agent", messageId: "user-agent-launch" },
  1292. { turnId },
  1293. );
  1294. log.push(
  1295. SessionEventType.ToolCallScheduled,
  1296. {
  1297. toolCallId,
  1298. toolName: "Agent",
  1299. input: {
  1300. description: "分析世界杯",
  1301. run_in_background: true,
  1302. subagent_type: "general-purpose",
  1303. },
  1304. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1305. },
  1306. { turnId },
  1307. );
  1308. log.push(
  1309. SessionEventType.ToolCallStarted,
  1310. { toolCallId, toolName: "Agent", startedAt: new Date(1_700_000_003_000) },
  1311. { turnId },
  1312. );
  1313. log.push(
  1314. SessionEventType.ToolCallResult,
  1315. {
  1316. toolCallId,
  1317. result: { success: true, content: "Async agent launched successfully." },
  1318. duration: 1,
  1319. },
  1320. { turnId },
  1321. );
  1322. log.push(
  1323. SessionEventType.TurnComplete,
  1324. { response: "", tokenCount: 0, toolCallCount: 1, duration: 1, resultType: "success" },
  1325. { turnId },
  1326. );
  1327. log.push(
  1328. SessionEventType.TurnStarted,
  1329. {
  1330. turnNumber: 2,
  1331. input: notification,
  1332. inputSource: "background_task",
  1333. inputVisibility: "model-only",
  1334. messageId: "user-agent-notification",
  1335. },
  1336. { turnId: "turn-agent-notification" },
  1337. );
  1338. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  1339. expect(rows.filter((row) => row.kind === "userInput")).toHaveLength(1);
  1340. expect(
  1341. rows.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  1342. ).toMatchObject({
  1343. error: {
  1344. code: "fault.runtime.backgroundTaskFailed",
  1345. message: error,
  1346. },
  1347. output: { text: result },
  1348. status: "error",
  1349. });
  1350. });
  1351. it("BG26:不带 <error> 的失败通知按 originMeta.subagentResult 取失败原因,不解析 summary", () => {
  1352. const turnId = "turn-agent-launch";
  1353. const toolCallId = "tool-agent-rate-limit";
  1354. const error = "Requests are too frequent. Request id: bg26";
  1355. // 失败通知不带 <error>;失败原文由 originMeta.subagentResult 结构化下发,
  1356. // hover 只显示 provider 原文。
  1357. const summary = `Agent "分析世界杯" failed: ${error}`;
  1358. const notification = [
  1359. "<task-notification>",
  1360. `<tool-use-id>${toolCallId}</tool-use-id>`,
  1361. "<status>failed</status>",
  1362. `<summary>${summary}</summary>`,
  1363. "</task-notification>",
  1364. ].join("\n");
  1365. const toolRowFor = (originMeta?: Record<string, unknown>) => {
  1366. const log = new EventLog();
  1367. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1368. log.push(
  1369. SessionEventType.TurnStarted,
  1370. { turnNumber: 1, input: "launch agent", messageId: "user-agent-launch" },
  1371. { turnId },
  1372. );
  1373. log.push(
  1374. SessionEventType.ToolCallScheduled,
  1375. {
  1376. toolCallId,
  1377. toolName: "Agent",
  1378. input: {
  1379. description: "分析世界杯",
  1380. run_in_background: true,
  1381. subagent_type: "general-purpose",
  1382. },
  1383. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1384. },
  1385. { turnId },
  1386. );
  1387. log.push(
  1388. SessionEventType.ToolCallStarted,
  1389. { toolCallId, toolName: "Agent", startedAt: new Date(1_700_000_003_000) },
  1390. { turnId },
  1391. );
  1392. log.push(
  1393. SessionEventType.ToolCallResult,
  1394. {
  1395. toolCallId,
  1396. result: { success: true, content: "Async agent launched successfully." },
  1397. duration: 1,
  1398. },
  1399. { turnId },
  1400. );
  1401. log.push(
  1402. SessionEventType.TurnComplete,
  1403. { response: "", tokenCount: 0, toolCallCount: 1, duration: 1, resultType: "success" },
  1404. { turnId },
  1405. );
  1406. log.push(
  1407. SessionEventType.TurnStarted,
  1408. {
  1409. turnNumber: 2,
  1410. input: notification,
  1411. inputSource: "background_task",
  1412. inputVisibility: "model-only",
  1413. messageId: "user-agent-notification",
  1414. ...(originMeta ? { originMeta } : {}),
  1415. },
  1416. { turnId: "turn-agent-notification" },
  1417. );
  1418. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  1419. expect(rows.filter((row) => row.kind === "userInput")).toHaveLength(1);
  1420. return rows.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId);
  1421. };
  1422. expect(
  1423. toolRowFor({
  1424. backgroundSource: "subagent",
  1425. workId: "agent-bg26",
  1426. title: "分析世界杯",
  1427. subagentResult: { status: "failed", error },
  1428. }),
  1429. ).toMatchObject({
  1430. error: { code: "fault.runtime.backgroundTaskFailed", message: error },
  1431. output: { text: summary },
  1432. status: "error",
  1433. });
  1434. // 产品数据不依赖模型可见文案:没有结构化结果(合并轮)时不从 summary 猜原因,
  1435. // 失败详情退回整句 summary。
  1436. expect(toolRowFor()).toMatchObject({
  1437. error: { code: "fault.runtime.backgroundTaskFailed", message: summary },
  1438. status: "error",
  1439. });
  1440. });
  1441. it("BG26:合并通知按块投影,失败任务不读下一条通知的结果", () => {
  1442. const turnId = "turn-agent-launch";
  1443. const failedSummary = 'Agent "A" failed: Permission denied';
  1444. const notification = (toolCallId: string, lines: string[]) =>
  1445. [
  1446. "<task-notification>",
  1447. `<tool-use-id>${toolCallId}</tool-use-id>`,
  1448. ...lines,
  1449. "</task-notification>",
  1450. ].join("\n");
  1451. const log = new EventLog();
  1452. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1453. log.push(
  1454. SessionEventType.TurnStarted,
  1455. { turnNumber: 1, input: "launch agents", messageId: "user-agent-launch" },
  1456. { turnId },
  1457. );
  1458. for (const toolCallId of ["tool-agent-a", "tool-agent-b"]) {
  1459. log.push(
  1460. SessionEventType.ToolCallScheduled,
  1461. {
  1462. toolCallId,
  1463. toolName: "Agent",
  1464. input: {
  1465. description: toolCallId,
  1466. run_in_background: true,
  1467. subagent_type: "general-purpose",
  1468. },
  1469. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1470. },
  1471. { turnId },
  1472. );
  1473. log.push(
  1474. SessionEventType.ToolCallResult,
  1475. {
  1476. toolCallId,
  1477. result: { success: true, content: "Async agent launched successfully." },
  1478. duration: 1,
  1479. },
  1480. { turnId },
  1481. );
  1482. }
  1483. log.push(
  1484. SessionEventType.TurnComplete,
  1485. { response: "", tokenCount: 0, toolCallCount: 2, duration: 1, resultType: "success" },
  1486. { turnId },
  1487. );
  1488. // 合并轮的 originMeta 只有基字段,没有逐任务的结构化结果。
  1489. log.push(
  1490. SessionEventType.TurnStarted,
  1491. {
  1492. turnNumber: 2,
  1493. input: [
  1494. notification("tool-agent-a", [
  1495. "<status>failed</status>",
  1496. `<summary>${failedSummary}</summary>`,
  1497. ]),
  1498. notification("tool-agent-b", [
  1499. "<status>completed</status>",
  1500. '<summary>Agent "B" finished</summary>',
  1501. "<result>Tests passed</result>",
  1502. ]),
  1503. ].join("\n\n"),
  1504. inputSource: "background_task",
  1505. inputVisibility: "model-only",
  1506. messageId: "user-agent-notification",
  1507. originMeta: { backgroundSource: "subagent", workId: "agent-a", title: "A · B" },
  1508. },
  1509. { turnId: "turn-agent-notification" },
  1510. );
  1511. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  1512. const toolRow = (toolCallId: string) =>
  1513. rows.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId);
  1514. expect(toolRow("tool-agent-a")).toMatchObject({
  1515. error: { code: "fault.runtime.backgroundTaskFailed", message: failedSummary },
  1516. output: { text: failedSummary },
  1517. status: "error",
  1518. });
  1519. expect(toolRow("tool-agent-b")).toMatchObject({
  1520. output: { text: "Tests passed" },
  1521. status: "success",
  1522. });
  1523. });
  1524. // ── B 组:stop / 迟到终态 ──
  1525. it("B:cancelled turn —— streaming 行收口为 interrupted,phase=completedInterrupted", () => {
  1526. const log = new EventLog();
  1527. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1528. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  1529. log.push(
  1530. SessionEventType.ModelStreaming,
  1531. { kind: "text_start", delta: "", done: false },
  1532. { turnId: "turn-1" },
  1533. );
  1534. log.push(
  1535. SessionEventType.ModelStreaming,
  1536. { kind: "text_delta", delta: "partial", done: false },
  1537. { turnId: "turn-1" },
  1538. );
  1539. log.push(
  1540. SessionEventType.TurnComplete,
  1541. { response: "", tokenCount: 0, toolCallCount: 0, duration: 1000, resultType: "cancelled" },
  1542. { turnId: "turn-1" },
  1543. );
  1544. const { projection } = runAll(log.events);
  1545. const snapshot = projection.getSnapshot();
  1546. expect(snapshot.control.phase).toBe("completedInterrupted");
  1547. const assistant = snapshot.rows.window.find((row) => row.kind === "assistantText");
  1548. expect(assistant).toMatchObject({ text: "partial", state: "interrupted" });
  1549. const header = snapshot.rows.window.find((row) => row.kind === "turnHeader");
  1550. expect(header).toMatchObject({ state: "completedInterrupted" });
  1551. });
  1552. it("B/结构性2:stop 后迟到的流式/工具终态被拒收,投影逐字节不变", () => {
  1553. const log = new EventLog();
  1554. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1555. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  1556. log.push(
  1557. SessionEventType.TurnComplete,
  1558. { response: "", tokenCount: 0, toolCallCount: 0, duration: 100, resultType: "cancelled" },
  1559. { turnId: "turn-1" },
  1560. );
  1561. const { projection } = runAll(log.events);
  1562. const before = structuredClone(projection.getSnapshot());
  1563. const late = new EventLog();
  1564. late.push(
  1565. SessionEventType.ModelStreaming,
  1566. { kind: "text_delta", delta: "ghost", done: false },
  1567. { turnId: "turn-1" },
  1568. );
  1569. late.push(
  1570. SessionEventType.ToolCallResult,
  1571. { toolCallId: "tc-1", result: { success: true, content: "ghost" }, duration: 1 },
  1572. { turnId: "turn-1" },
  1573. );
  1574. for (const event of late.events) {
  1575. expect(projection.applyEvent(event)).toEqual([]);
  1576. }
  1577. expect({ ...projection.getSnapshot(), seq: before.seq }).toEqual(before);
  1578. });
  1579. // ── O/Q 组:tool call 状态机与权限交互 ──
  1580. it("CUA:PID 工具按事件顺序固化最近一次成功 list_apps 快照", () => {
  1581. const turnId = "turn-cua-app-snapshot";
  1582. const log = new EventLog();
  1583. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1584. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "操作应用" }, { turnId });
  1585. const listApps = (id: string, name: string, success = true) => {
  1586. log.push(
  1587. SessionEventType.ToolCallScheduled,
  1588. {
  1589. toolCallId: id,
  1590. toolName: "mcp__computer-use__list_apps",
  1591. input: {},
  1592. schedule: { parallelGroups: [[id]], executionOrder: [id] },
  1593. },
  1594. { turnId },
  1595. );
  1596. log.push(
  1597. SessionEventType.ToolCallResult,
  1598. {
  1599. toolCallId: id,
  1600. result: {
  1601. success,
  1602. content: success
  1603. ? JSON.stringify([{ pid: 42, name, bundle_id: `com.example.${name}` }])
  1604. : "failed",
  1605. ...(!success ? { error: { type: "toolFailed", message: "failed" } } : {}),
  1606. },
  1607. duration: 1,
  1608. },
  1609. { turnId },
  1610. );
  1611. };
  1612. const scheduleKey = (
  1613. id: string,
  1614. toolName = "mcp__computer-use__key",
  1615. appRef: unknown = { pid: 42 },
  1616. ) =>
  1617. log.push(
  1618. SessionEventType.ToolCallScheduled,
  1619. {
  1620. toolCallId: id,
  1621. toolName,
  1622. input: { app_ref: appRef, key: "TAB" },
  1623. schedule: { parallelGroups: [[id]], executionOrder: [id] },
  1624. },
  1625. { turnId },
  1626. );
  1627. listApps("list-1", "One");
  1628. scheduleKey("key-1");
  1629. listApps("list-failed", "Ignored", false);
  1630. scheduleKey("key-after-failure");
  1631. listApps("list-2", "Two");
  1632. scheduleKey("key-2");
  1633. scheduleKey("bundle-only", "mcp__computer-use__get_app_state", {
  1634. bundle_id: "com.example.Two",
  1635. });
  1636. scheduleKey("serialized-pid", "mcp__computer-use__get_app_state", '{"pid":42}');
  1637. scheduleKey("lookalike", "mcp__other__computer-use__key");
  1638. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  1639. const appOf = (id: string) => {
  1640. const row = rows.find(
  1641. (candidate) => candidate.kind === "toolCall" && candidate.toolCallId === id,
  1642. );
  1643. return row?.kind === "toolCall" ? row.cuaApp : undefined;
  1644. };
  1645. expect(appOf("key-1")).toEqual({ pid: 42, name: "One", bundleId: "com.example.One" });
  1646. expect(appOf("key-after-failure")).toEqual({
  1647. pid: 42,
  1648. name: "One",
  1649. bundleId: "com.example.One",
  1650. });
  1651. expect(appOf("key-2")).toEqual({ pid: 42, name: "Two", bundleId: "com.example.Two" });
  1652. expect(appOf("bundle-only")).toEqual({
  1653. pid: 42,
  1654. name: "Two",
  1655. bundleId: "com.example.Two",
  1656. });
  1657. expect(appOf("serialized-pid")).toEqual({
  1658. pid: 42,
  1659. name: "Two",
  1660. bundleId: "com.example.Two",
  1661. });
  1662. expect(appOf("lookalike")).toBeUndefined();
  1663. });
  1664. it("CUA:原子实时投影提交后保留 list_apps 快照", () => {
  1665. const turnId = "turn-cua-atomic-snapshot";
  1666. const log = new EventLog();
  1667. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1668. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "操作飞书" }, { turnId });
  1669. log.push(
  1670. SessionEventType.ToolCallScheduled,
  1671. {
  1672. toolCallId: "list-apps",
  1673. toolName: "mcp__computer-use__list_apps",
  1674. input: {},
  1675. schedule: { parallelGroups: [["list-apps"]], executionOrder: ["list-apps"] },
  1676. },
  1677. { turnId },
  1678. );
  1679. log.push(
  1680. SessionEventType.ToolCallResult,
  1681. {
  1682. toolCallId: "list-apps",
  1683. result: {
  1684. success: true,
  1685. content: JSON.stringify([{ pid: 691, name: "Feishu", bundle_id: "com.electron.lark" }]),
  1686. },
  1687. duration: 1,
  1688. },
  1689. { turnId },
  1690. );
  1691. log.push(
  1692. SessionEventType.ToolCallScheduled,
  1693. {
  1694. toolCallId: "get-app-state",
  1695. toolName: "mcp__computer-use__get_app_state",
  1696. input: { app_ref: '{"pid":691}', title: "查看飞书当前界面" },
  1697. schedule: {
  1698. parallelGroups: [["get-app-state"]],
  1699. executionOrder: ["get-app-state"],
  1700. },
  1701. },
  1702. { turnId },
  1703. );
  1704. const projection = new ProductProjection("session-1", "epoch-1");
  1705. for (const event of log.events) {
  1706. expect(projection.applyEventAtomically(event, () => true)).not.toBeNull();
  1707. }
  1708. const row = projection
  1709. .getSnapshot()
  1710. .rows.window.find(
  1711. (candidate) => candidate.kind === "toolCall" && candidate.toolCallId === "get-app-state",
  1712. );
  1713. expect(row?.kind === "toolCall" ? row.cuaApp : undefined).toEqual({
  1714. pid: 691,
  1715. name: "Feishu",
  1716. bundleId: "com.electron.lark",
  1717. });
  1718. });
  1719. it("BTA01:保留 turn-end Node REPL 图片 display 到 live tool row", () => {
  1720. const turnId = "turn-browser-shot";
  1721. const toolCallId = "tool-browser-shot";
  1722. const log = new EventLog();
  1723. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1724. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "打开页面" }, { turnId });
  1725. log.push(
  1726. SessionEventType.ToolCallScheduled,
  1727. {
  1728. toolCallId,
  1729. toolName: "mcp__node_repl__js",
  1730. input: { source: "browser_turn_end" },
  1731. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1732. },
  1733. { turnId },
  1734. );
  1735. log.push(
  1736. SessionEventType.ToolCallResult,
  1737. {
  1738. toolCallId,
  1739. result: {
  1740. success: true,
  1741. content: "",
  1742. display: {
  1743. kind: "node_repl_images",
  1744. source: "browser_turn_end",
  1745. images: [{ base64: "AAAA", mimeType: "image/png" }],
  1746. },
  1747. },
  1748. duration: 0,
  1749. },
  1750. { turnId },
  1751. );
  1752. const snapshot = runAll(log.events).projection.getSnapshot();
  1753. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  1754. expect(
  1755. snapshot.rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  1756. ).toMatchObject({
  1757. status: "success",
  1758. display: { kind: "node_repl_images", source: "browser_turn_end" },
  1759. });
  1760. });
  1761. it("CUA:保留实时工具结果的截图 display 到 output", () => {
  1762. const turnId = "turn-cua-screenshot";
  1763. const toolCallId = "tool-cua-screenshot";
  1764. const log = new EventLog();
  1765. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1766. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "截图" }, { turnId });
  1767. log.push(
  1768. SessionEventType.ToolCallScheduled,
  1769. {
  1770. toolCallId,
  1771. toolName: "mcp__computer-use__computer-use",
  1772. input: { action: "screenshot" },
  1773. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1774. },
  1775. { turnId },
  1776. );
  1777. log.push(
  1778. SessionEventType.ToolCallResult,
  1779. {
  1780. toolCallId,
  1781. result: {
  1782. success: true,
  1783. content: "[Attached image/jpeg: MCP image]",
  1784. display: {
  1785. kind: "cua",
  1786. schemaVersion: 1,
  1787. toolName: "computer-use",
  1788. status: "success",
  1789. input: '{"action":"screenshot"}',
  1790. media: [{ mimeType: "image/jpeg", data: "AAAA" }],
  1791. },
  1792. },
  1793. duration: 10,
  1794. },
  1795. { turnId },
  1796. );
  1797. expect(
  1798. runAll(log.events)
  1799. .projection.getSnapshot()
  1800. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  1801. ).toMatchObject({
  1802. status: "success",
  1803. output: {
  1804. text: "[Attached image/jpeg: MCP image]",
  1805. display: {
  1806. kind: "cua",
  1807. media: [{ mimeType: "image/jpeg", data: "AAAA" }],
  1808. },
  1809. },
  1810. });
  1811. });
  1812. it.each([
  1813. {
  1814. toolName: "TaskOutput",
  1815. display: {
  1816. kind: "task_output",
  1817. retrievalStatus: "not_ready",
  1818. taskStatus: "running",
  1819. output: "partial output",
  1820. } as const,
  1821. },
  1822. {
  1823. toolName: "RespondToCoordinator",
  1824. display: {
  1825. kind: "respond_to_coordinator",
  1826. status: "success",
  1827. } as const,
  1828. },
  1829. {
  1830. toolName: "CreateWorkflow",
  1831. display: {
  1832. kind: "create_workflow",
  1833. ok: true,
  1834. errorCount: 0,
  1835. diagnostics: [],
  1836. causalityGraph: {
  1837. steps: [
  1838. {
  1839. id: "ask#1",
  1840. kind: "ask",
  1841. label: "scout",
  1842. line: 3,
  1843. column: 20,
  1844. lane: "actor#1",
  1845. },
  1846. ],
  1847. lanes: [{ id: "actor#1", name: "scout", line: 3, column: 11 }],
  1848. // 第二层是子代理导向:每阶段一张参与者卡 + 交接边(docs/dynamic-workflow/presentation.md)。
  1849. participants: [
  1850. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] },
  1851. ],
  1852. handoffs: [],
  1853. sink: ["ask#1"],
  1854. },
  1855. } as const,
  1856. },
  1857. // 观察类工作流工具的五个 display kind(spec:docs/dynamic-workflow/launch.md「Run introspection tools」
  1858. // 「工具卡 display」、同文件「The model catalog」)——whitelist 不放行就整块被剥,UI 只能退回文本投影。
  1859. {
  1860. toolName: "GetWorkflowRun",
  1861. display: {
  1862. kind: "get_workflow_run",
  1863. runId: "wf_demo",
  1864. label: "demo",
  1865. status: "running",
  1866. usage: {
  1867. spentTokens: 1_000,
  1868. nodesObserved: 3,
  1869. nodesRunning: 1,
  1870. nodesCompleted: 2,
  1871. nodesFailed: 0,
  1872. },
  1873. actors: [{ siteId: "agent#1", ordinal: 1, name: "scout" }],
  1874. logTail: [{ sequence: 1, message: "started" }],
  1875. } as const,
  1876. },
  1877. {
  1878. toolName: "ListWorkflowRuns",
  1879. display: {
  1880. kind: "list_workflow_runs",
  1881. runs: [
  1882. {
  1883. runId: "wf_demo",
  1884. label: "demo",
  1885. labelSource: "name",
  1886. status: "completed",
  1887. ownedByThisSession: true,
  1888. createdAt: 1,
  1889. updatedAt: 2,
  1890. spentTokens: 42,
  1891. },
  1892. ],
  1893. } as const,
  1894. },
  1895. {
  1896. toolName: "EvalWorkflowSnippet",
  1897. display: {
  1898. kind: "eval_workflow_snippet",
  1899. ok: true,
  1900. diagnostics: [],
  1901. logs: ["glob matched 3 files"],
  1902. response: "3",
  1903. durationMs: 120,
  1904. } as const,
  1905. },
  1906. {
  1907. toolName: "ResumeWorkflowRun",
  1908. display: {
  1909. kind: "resume_workflow_run",
  1910. runId: "wf_demo",
  1911. } as const,
  1912. },
  1913. // 模型目录卡(spec:docs/dynamic-workflow/launch.md「The model catalog」):白名单漏了它,
  1914. // UI 只能退回那段以 providerId 开头的 `<models>` 文本。
  1915. {
  1916. toolName: "ListModels",
  1917. display: {
  1918. kind: "list_models",
  1919. current: "account:bigmodel-team-coding-plan/GLM-5.3-Flash",
  1920. models: [
  1921. {
  1922. id: "account:bigmodel-team-coding-plan/GLM-5.3-Flash",
  1923. providerId: "account:bigmodel-team-coding-plan",
  1924. modelId: "GLM-5.3-Flash",
  1925. providerLabel: "BigModel",
  1926. reasoningLevels: ["low", "medium", "high"],
  1927. defaultReasoningLevel: "high",
  1928. contextWindow: 128_000,
  1929. },
  1930. ],
  1931. } as const,
  1932. },
  1933. {
  1934. toolName: "ListSavedWorkflows",
  1935. display: {
  1936. kind: "saved_workflow_list",
  1937. workflows: [
  1938. {
  1939. name: "nightly-sync",
  1940. scope: "project",
  1941. path: ".zcode/workflows/nightly-sync.dwf.ts",
  1942. argNames: ["question"],
  1943. },
  1944. ],
  1945. } as const,
  1946. },
  1947. ])("保留 $toolName display 到 live tool row", ({ toolName, display }) => {
  1948. const turnId = `turn-${toolName}`;
  1949. const toolCallId = `tool-${toolName}`;
  1950. const log = new EventLog();
  1951. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1952. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run tool" }, { turnId });
  1953. log.push(
  1954. SessionEventType.ToolCallScheduled,
  1955. {
  1956. toolCallId,
  1957. toolName,
  1958. input: {},
  1959. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1960. },
  1961. { turnId },
  1962. );
  1963. log.push(
  1964. SessionEventType.ToolCallResult,
  1965. {
  1966. toolCallId,
  1967. result: {
  1968. success: true,
  1969. content: "provider content remains independent",
  1970. display,
  1971. },
  1972. duration: 0,
  1973. },
  1974. { turnId },
  1975. );
  1976. expect(
  1977. runAll(log.events)
  1978. .projection.getSnapshot()
  1979. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  1980. ).toMatchObject({
  1981. status: "success",
  1982. display,
  1983. output: { text: "provider content remains independent" },
  1984. });
  1985. });
  1986. it("不把未声明支持的 display kind 顺带开放到 V4 row", () => {
  1987. const turnId = "turn-file-diff-display";
  1988. const toolCallId = "tool-file-diff-display";
  1989. const log = new EventLog();
  1990. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1991. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "edit file" }, { turnId });
  1992. log.push(
  1993. SessionEventType.ToolCallScheduled,
  1994. {
  1995. toolCallId,
  1996. toolName: "Edit",
  1997. input: {},
  1998. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1999. },
  2000. { turnId },
  2001. );
  2002. log.push(
  2003. SessionEventType.ToolCallResult,
  2004. {
  2005. toolCallId,
  2006. result: {
  2007. success: true,
  2008. content: "updated",
  2009. display: {
  2010. kind: "file_diff",
  2011. filePath: "/workspace/app.ts",
  2012. additions: 1,
  2013. deletions: 0,
  2014. structuredPatch: [],
  2015. truncated: false,
  2016. },
  2017. },
  2018. duration: 0,
  2019. },
  2020. { turnId },
  2021. );
  2022. const row = runAll(log.events)
  2023. .projection.getSnapshot()
  2024. .rows.window.find((candidate) => candidate.kind === "toolCall");
  2025. expect(row).not.toHaveProperty("display");
  2026. });
  2027. it("不把 mirrored RespondToCoordinator 物化到父会话", () => {
  2028. const turnId = "turn-mirrored-response";
  2029. const toolCallId = "tool_subagent_agent-1_response";
  2030. const mirrored = {
  2031. agentId: "agent-1",
  2032. agentType: "general-purpose",
  2033. childSessionId: "session-child-1",
  2034. childToolCallId: "response",
  2035. parentToolCallId: "parent-agent-call",
  2036. source: "subagent",
  2037. };
  2038. const log = new EventLog();
  2039. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2040. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run child" }, { turnId });
  2041. log.push(
  2042. SessionEventType.ToolCallScheduled,
  2043. {
  2044. ...mirrored,
  2045. toolCallId,
  2046. toolName: "RespondToCoordinator",
  2047. input: { summary: "reply", message: "details" },
  2048. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  2049. },
  2050. { turnId },
  2051. );
  2052. log.push(
  2053. SessionEventType.ToolCallResult,
  2054. {
  2055. ...mirrored,
  2056. toolCallId,
  2057. result: {
  2058. success: true,
  2059. content: "Response response-1 was queued for the coordinator.",
  2060. display: { kind: "respond_to_coordinator", status: "success" },
  2061. },
  2062. duration: 0,
  2063. },
  2064. { turnId },
  2065. );
  2066. expect(
  2067. runAll(log.events)
  2068. .projection.getSnapshot()
  2069. .rows.window.filter((row) => row.kind === "toolCall"),
  2070. ).toEqual([]);
  2071. });
  2072. it("MCP discovery 展示元数据进入 live tool row,不依赖合成工具名解析", () => {
  2073. const turnId = "turn-mcp-presentation";
  2074. const toolCallId = "tool-mcp-presentation";
  2075. const log = new EventLog();
  2076. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2077. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "查询 issue" }, { turnId });
  2078. log.push(
  2079. SessionEventType.ToolCallScheduled,
  2080. {
  2081. toolCallId,
  2082. toolName: "custom-provider-visible-name",
  2083. input: { query: "is:open" },
  2084. display: {
  2085. kind: "mcp_tool",
  2086. serverName: "company-github-prod",
  2087. toolName: "issue_query_v2",
  2088. description: "Query issues visible to the current user.",
  2089. },
  2090. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  2091. },
  2092. { turnId },
  2093. );
  2094. const pendingRow = runAll(log.events.slice(0, 3))
  2095. .projection.getSnapshot()
  2096. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId);
  2097. expect(pendingRow).toMatchObject({
  2098. status: "inputStreaming",
  2099. display: { kind: "mcp_tool", toolName: "issue_query_v2" },
  2100. });
  2101. log.push(
  2102. SessionEventType.ToolCallResult,
  2103. {
  2104. toolCallId,
  2105. result: {
  2106. success: true,
  2107. content: "12 issues",
  2108. display: {
  2109. kind: "mcp_tool",
  2110. serverName: "company-github-prod",
  2111. toolName: "issue_query_v2",
  2112. description: "Query issues visible to the current user.",
  2113. },
  2114. },
  2115. duration: 12,
  2116. },
  2117. { turnId },
  2118. );
  2119. expect(
  2120. runAll(log.events)
  2121. .projection.getSnapshot()
  2122. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  2123. ).toMatchObject({
  2124. toolName: "custom-provider-visible-name",
  2125. status: "success",
  2126. display: {
  2127. kind: "mcp_tool",
  2128. serverName: "company-github-prod",
  2129. toolName: "issue_query_v2",
  2130. },
  2131. });
  2132. });
  2133. it("MCP display 在 running、failed 与 stopped 生命周期更新中保持不变", () => {
  2134. const display = {
  2135. kind: "mcp_tool" as const,
  2136. serverName: "firebase",
  2137. toolName: "get_environment",
  2138. };
  2139. const createLog = () => {
  2140. const log = new EventLog();
  2141. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2142. log.push(
  2143. SessionEventType.TurnStarted,
  2144. { turnNumber: 1, input: "inspect" },
  2145. { turnId: "turn-mcp-lifecycle" },
  2146. );
  2147. log.push(
  2148. SessionEventType.ToolCallScheduled,
  2149. {
  2150. toolCallId: "mcp-lifecycle",
  2151. toolName: "opaque-name",
  2152. input: {},
  2153. display,
  2154. schedule: { parallelGroups: [["mcp-lifecycle"]], executionOrder: ["mcp-lifecycle"] },
  2155. },
  2156. { turnId: "turn-mcp-lifecycle" },
  2157. );
  2158. log.push(
  2159. SessionEventType.ToolCallStarted,
  2160. { toolCallId: "mcp-lifecycle", toolName: "opaque-name", startedAt: new Date() },
  2161. { turnId: "turn-mcp-lifecycle" },
  2162. );
  2163. return log;
  2164. };
  2165. const failedLog = createLog();
  2166. failedLog.push(
  2167. SessionEventType.ToolCallError,
  2168. { toolCallId: "mcp-lifecycle", error: { type: "tool_failed", message: "boom" } },
  2169. { turnId: "turn-mcp-lifecycle" },
  2170. );
  2171. const failedRow = runAll(failedLog.events).projection.getSnapshot().rows.window.at(-1);
  2172. expect(failedRow).toMatchObject({ status: "error", display });
  2173. const stoppedLog = createLog();
  2174. stoppedLog.push(
  2175. SessionEventType.TurnComplete,
  2176. { response: "", tokenCount: 0, toolCallCount: 1, duration: 1, resultType: "cancelled" },
  2177. { turnId: "turn-mcp-lifecycle" },
  2178. );
  2179. const stoppedRow = runAll(stoppedLog.events).projection.getSnapshot().rows.window.at(-1);
  2180. expect(stoppedRow).toMatchObject({ status: "cancelled", display });
  2181. });
  2182. it("工具主动取消错误直接投影为 cancelled,不等待 turn complete 纠正", () => {
  2183. const turnId = "turn-tool-cancelled";
  2184. const log = new EventLog();
  2185. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2186. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run long bash" }, { turnId });
  2187. log.push(
  2188. SessionEventType.ToolCallScheduled,
  2189. {
  2190. toolCallId: "bash-cancelled",
  2191. toolName: "Bash",
  2192. input: { command: "sleep 60" },
  2193. schedule: { parallelGroups: [["bash-cancelled"]], executionOrder: ["bash-cancelled"] },
  2194. },
  2195. { turnId },
  2196. );
  2197. log.push(
  2198. SessionEventType.ToolCallStarted,
  2199. { toolCallId: "bash-cancelled", toolName: "Bash", startedAt: new Date() },
  2200. { turnId },
  2201. );
  2202. log.push(
  2203. SessionEventType.ToolCallError,
  2204. {
  2205. toolCallId: "bash-cancelled",
  2206. error: {
  2207. code: "TOOL_CANCELLED",
  2208. type: "tool_cancelled",
  2209. message: "Bash was cancelled and the child process was asked to stop",
  2210. },
  2211. },
  2212. { turnId },
  2213. );
  2214. const row = runAll(log.events).projection.getSnapshot().rows.window.at(-1);
  2215. expect(row).toMatchObject({ kind: "toolCall", status: "cancelled" });
  2216. });
  2217. it("O/Q:tool 输入流式 → 权限等待 → 放行执行 → 成功终态", () => {
  2218. const turnId = "turn-1";
  2219. const log = new EventLog();
  2220. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2221. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run ls" }, { turnId });
  2222. log.push(
  2223. SessionEventType.ModelStreaming,
  2224. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-1", toolName: "bash" },
  2225. { turnId },
  2226. );
  2227. log.push(
  2228. SessionEventType.ModelStreaming,
  2229. { kind: "tool_input_delta", delta: '{"command":"ls"}', done: false, toolCallId: "tc-1" },
  2230. { turnId },
  2231. );
  2232. log.push(
  2233. SessionEventType.ToolCallScheduled,
  2234. {
  2235. toolCallId: "tc-1",
  2236. toolName: "bash",
  2237. input: { command: "ls" },
  2238. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  2239. },
  2240. { turnId },
  2241. );
  2242. log.push(
  2243. SessionEventType.PermissionRequested,
  2244. {
  2245. requestId: "req-1",
  2246. toolCallId: "tc-1",
  2247. toolName: "bash",
  2248. riskLevel: "medium",
  2249. reason: "Run shell command",
  2250. input: { command: "ls" },
  2251. suggestedPermissionUpdates: [
  2252. {
  2253. behavior: "allow",
  2254. rules: [{ ruleContent: "pnpm run lint:*", toolName: "Bash" }],
  2255. type: "addRules",
  2256. },
  2257. ],
  2258. },
  2259. { turnId },
  2260. );
  2261. const { projection } = runAll(log.events);
  2262. const pending = projection.getSnapshot();
  2263. const toolRow = pending.rows.window.find((row) => row.kind === "toolCall");
  2264. expect(toolRow).toMatchObject({
  2265. status: "pendingApproval",
  2266. inputText: '{"command":"ls"}',
  2267. approvalInteractionId: "req-1",
  2268. });
  2269. expect(pending.pendingInteractions).toHaveLength(1);
  2270. expect(pending.pendingInteractions[0]).toMatchObject({
  2271. kind: "permission",
  2272. anchorRowId: toolRow?.rowId,
  2273. });
  2274. expect(pending.pendingInteractions[0]?.payload).toMatchObject({
  2275. freeText: true,
  2276. options: [
  2277. { optionId: "allowOnce", response: { decision: "allow" } },
  2278. {
  2279. optionId: "allowAlways",
  2280. response: {
  2281. decision: "allow",
  2282. permissionUpdates: [
  2283. {
  2284. behavior: "allow",
  2285. rules: [{ ruleContent: "pnpm run lint:*", toolName: "Bash" }],
  2286. type: "addRules",
  2287. },
  2288. ],
  2289. },
  2290. },
  2291. { optionId: "deny", response: { decision: "deny" } },
  2292. ],
  2293. });
  2294. const resume = new EventLog();
  2295. // EventLog seq 从 1 重新计数不影响断言主体(seq 水位单独断言于 A 组)。
  2296. resume.push(
  2297. SessionEventType.PermissionResolved,
  2298. { requestId: "req-1", toolCallId: "tc-1", decision: "allow" },
  2299. { turnId },
  2300. );
  2301. resume.push(
  2302. SessionEventType.ToolCallStarted,
  2303. { toolCallId: "tc-1", toolName: "bash", startedAt: new Date() },
  2304. { turnId },
  2305. );
  2306. resume.push(
  2307. SessionEventType.ToolCallResult,
  2308. { toolCallId: "tc-1", result: { success: true, content: "file-a\nfile-b" }, duration: 42 },
  2309. { turnId },
  2310. );
  2311. for (const event of resume.events) projection.applyEvent(event);
  2312. const done = projection.getSnapshot();
  2313. expect(done.pendingInteractions).toHaveLength(0);
  2314. const doneRow = done.rows.window.find((row) => row.kind === "toolCall");
  2315. expect(doneRow).toMatchObject({
  2316. status: "success",
  2317. output: { text: "file-a\nfile-b" },
  2318. });
  2319. expect(
  2320. doneRow && "approvalInteractionId" in doneRow && doneRow.approvalInteractionId,
  2321. ).toBeFalsy();
  2322. });
  2323. it.each([
  2324. { label: "空字符串", streamName: "" },
  2325. { label: "纯空白", streamName: " \t " },
  2326. ])("O/ETN:$label 工具名只参与恢复,不物化可见工具行", ({ streamName }) => {
  2327. const turnId = "turn-empty-tool-name";
  2328. const toolCallId = "call-empty-tool-name";
  2329. const log = new EventLog();
  2330. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2331. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "continue" }, { turnId });
  2332. log.push(
  2333. SessionEventType.ModelStreaming,
  2334. {
  2335. kind: "tool_input_start",
  2336. delta: "",
  2337. done: false,
  2338. toolCallId,
  2339. toolName: streamName,
  2340. },
  2341. { turnId },
  2342. );
  2343. log.push(
  2344. SessionEventType.ModelStreaming,
  2345. {
  2346. kind: "tool_input_delta",
  2347. delta: '{"value":1}',
  2348. done: false,
  2349. toolCallId,
  2350. },
  2351. { turnId },
  2352. );
  2353. log.push(
  2354. SessionEventType.ModelStreaming,
  2355. {
  2356. kind: "tool_call",
  2357. delta: "",
  2358. done: true,
  2359. input: { value: 1 },
  2360. toolCallId,
  2361. toolName: streamName,
  2362. },
  2363. { turnId },
  2364. );
  2365. log.push(
  2366. SessionEventType.ToolCallError,
  2367. {
  2368. toolCallId,
  2369. error: {
  2370. type: "fault.runtime.toolFailed",
  2371. message: "Model returned an invalid tool call: tool name is empty.",
  2372. },
  2373. },
  2374. { turnId },
  2375. );
  2376. log.push(
  2377. SessionEventType.ModelStreaming,
  2378. { kind: "text_start", delta: "", done: false },
  2379. { turnId },
  2380. );
  2381. log.push(
  2382. SessionEventType.ModelStreaming,
  2383. { kind: "text_delta", delta: "continued", done: false },
  2384. { turnId },
  2385. );
  2386. log.push(
  2387. SessionEventType.ModelStreaming,
  2388. { kind: "text_end", delta: "", done: false },
  2389. { turnId },
  2390. );
  2391. log.push(
  2392. SessionEventType.TurnComplete,
  2393. {
  2394. response: "continued",
  2395. tokenCount: 1,
  2396. toolCallCount: 1,
  2397. duration: 10,
  2398. resultType: "success",
  2399. },
  2400. { turnId },
  2401. );
  2402. const { deltasPerEvent, projection, snapshots } = runAll(log.events);
  2403. expect(projection.getSnapshot().rows.window.filter((row) => row.kind === "toolCall")).toEqual(
  2404. [],
  2405. );
  2406. expect(
  2407. projection.getSnapshot().rows.window.find((row) => row.kind === "assistantText"),
  2408. ).toMatchObject({ text: "continued", state: "complete" });
  2409. expect(
  2410. deltasPerEvent
  2411. .flat()
  2412. .some(
  2413. (delta) =>
  2414. (delta.op === "row.appended" || delta.op === "row.upserted") &&
  2415. delta.row.kind === "toolCall",
  2416. ),
  2417. ).toBe(false);
  2418. const direct = applyConversationDeltas(snapshots[0]!, deltasPerEvent.flat());
  2419. for (const profile of [DELIVERY_PROFILES.continuous, DELIVERY_PROFILES.replayable]) {
  2420. const delivered = coalesceConversationDeltas(
  2421. filterConversationDeltasForProfile(deltasPerEvent.flat(), profile),
  2422. );
  2423. expect(applyConversationDeltas(snapshots[0]!, delivered)).toEqual(direct);
  2424. }
  2425. });
  2426. it("O/ETN:合法 empty_tool_name 工具保留 live 与 replayable 可见生命周期", () => {
  2427. const turnId = "turn-legitimate-empty-tool-name";
  2428. const toolCallId = "call-legitimate-empty-tool-name";
  2429. const log = new EventLog();
  2430. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2431. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run tool" }, { turnId });
  2432. log.push(
  2433. SessionEventType.ModelStreaming,
  2434. {
  2435. kind: "tool_input_start",
  2436. delta: "",
  2437. done: false,
  2438. toolCallId,
  2439. toolName: "empty_tool_name",
  2440. },
  2441. { turnId },
  2442. );
  2443. log.push(
  2444. SessionEventType.ModelStreaming,
  2445. {
  2446. kind: "tool_input_delta",
  2447. delta: '{"value":1}',
  2448. done: false,
  2449. toolCallId,
  2450. },
  2451. { turnId },
  2452. );
  2453. log.push(
  2454. SessionEventType.ModelStreaming,
  2455. {
  2456. kind: "tool_call",
  2457. delta: "",
  2458. done: true,
  2459. input: { value: 1 },
  2460. toolCallId,
  2461. toolName: "empty_tool_name",
  2462. },
  2463. { turnId },
  2464. );
  2465. log.push(
  2466. SessionEventType.ToolCallScheduled,
  2467. {
  2468. toolCallId,
  2469. toolName: "empty_tool_name",
  2470. input: { value: 1 },
  2471. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  2472. },
  2473. { turnId },
  2474. );
  2475. log.push(
  2476. SessionEventType.ToolCallResult,
  2477. {
  2478. toolCallId,
  2479. result: { success: true, content: "ok" },
  2480. duration: 1,
  2481. },
  2482. { turnId },
  2483. );
  2484. const { deltasPerEvent, projection, snapshots } = runAll(log.events);
  2485. expect(
  2486. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  2487. ).toMatchObject({
  2488. input: { value: 1 },
  2489. status: "success",
  2490. toolCallId,
  2491. toolName: "empty_tool_name",
  2492. });
  2493. const direct = applyConversationDeltas(snapshots[0]!, deltasPerEvent.flat());
  2494. for (const profile of [DELIVERY_PROFILES.continuous, DELIVERY_PROFILES.replayable]) {
  2495. const delivered = coalesceConversationDeltas(
  2496. filterConversationDeltasForProfile(deltasPerEvent.flat(), profile),
  2497. );
  2498. expect(applyConversationDeltas(snapshots[0]!, delivered)).toEqual(direct);
  2499. }
  2500. });
  2501. it("O/ETN:普通非空 unknown tool 仍保留 terminal error 工具行", () => {
  2502. const turnId = "turn-unknown-tool";
  2503. const toolCallId = "call-unknown-tool";
  2504. const log = new EventLog();
  2505. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2506. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "continue" }, { turnId });
  2507. log.push(
  2508. SessionEventType.ToolCallScheduled,
  2509. {
  2510. toolCallId,
  2511. toolName: "DefinitelyMissingTool",
  2512. input: {},
  2513. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  2514. },
  2515. { turnId },
  2516. );
  2517. log.push(
  2518. SessionEventType.ToolCallError,
  2519. {
  2520. toolCallId,
  2521. error: { type: "fault.runtime.toolNotFound", message: "Tool not found" },
  2522. },
  2523. { turnId },
  2524. );
  2525. expect(
  2526. runAll(log.events)
  2527. .projection.getSnapshot()
  2528. .rows.window.find((row) => row.kind === "toolCall"),
  2529. ).toMatchObject({
  2530. toolCallId,
  2531. toolName: "DefinitelyMissingTool",
  2532. status: "error",
  2533. });
  2534. });
  2535. it.each(["Write", "Edit"])(
  2536. "STIP06:%s 首包立即,后续 inputText 按事件时间戳每秒合并一次",
  2537. (toolName) => {
  2538. const turnId = "turn-file-tool";
  2539. const base = 1_700_000_010_000;
  2540. const log = new EventLog();
  2541. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2542. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "modify file" }, { turnId });
  2543. log.push(
  2544. SessionEventType.ModelStreaming,
  2545. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-file", toolName },
  2546. { timestampMs: base, turnId },
  2547. );
  2548. log.push(
  2549. SessionEventType.ModelStreaming,
  2550. {
  2551. kind: "tool_input_delta",
  2552. delta: '{"file_path":"src/app.ts",',
  2553. done: false,
  2554. toolCallId: "tc-file",
  2555. },
  2556. { timestampMs: base + 100, turnId },
  2557. );
  2558. log.push(
  2559. SessionEventType.ModelStreaming,
  2560. { kind: "tool_input_delta", delta: '"content":"a', done: false, toolCallId: "tc-file" },
  2561. { timestampMs: base + 400, turnId },
  2562. );
  2563. log.push(
  2564. SessionEventType.ModelStreaming,
  2565. { kind: "tool_input_delta", delta: 'b"}', done: false, toolCallId: "tc-file" },
  2566. { timestampMs: base + 1_100, turnId },
  2567. );
  2568. const { deltasPerEvent, projection } = runAll(log.events);
  2569. expect(inputTextAppends(deltasPerEvent[3] ?? [])).toEqual(['{"file_path":"src/app.ts",']);
  2570. expect(inputTextAppends(deltasPerEvent[4] ?? [])).toEqual([]);
  2571. expect(inputTextAppends(deltasPerEvent[5] ?? [])).toEqual(['"content":"ab"}']);
  2572. expect(
  2573. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  2574. ).toMatchObject({ inputText: '{"file_path":"src/app.ts","content":"ab"}' });
  2575. const estimateProjection = new ProductProjection("session-1", "epoch-1");
  2576. const appendEstimates = log.events.map((event) => {
  2577. const estimate = estimateProjection.establishedStreamingAppend(event);
  2578. estimateProjection.applyEvent(event);
  2579. return estimate;
  2580. });
  2581. expect(appendEstimates.slice(3)).toEqual([
  2582. '{"file_path":"src/app.ts",',
  2583. "",
  2584. '"content":"ab"}',
  2585. ]);
  2586. },
  2587. );
  2588. it("STIP07:Write input end 立即冲刷窗口内尚未发布的 suffix", () => {
  2589. const turnId = "turn-write-end";
  2590. const base = 1_700_000_020_000;
  2591. const log = new EventLog();
  2592. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2593. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "write" }, { turnId });
  2594. log.push(
  2595. SessionEventType.ModelStreaming,
  2596. {
  2597. kind: "tool_input_start",
  2598. delta: "",
  2599. done: false,
  2600. toolCallId: "tc-write",
  2601. toolName: "Write",
  2602. },
  2603. { timestampMs: base, turnId },
  2604. );
  2605. log.push(
  2606. SessionEventType.ModelStreaming,
  2607. { kind: "tool_input_delta", delta: '{"content":"a', done: false, toolCallId: "tc-write" },
  2608. { timestampMs: base + 100, turnId },
  2609. );
  2610. log.push(
  2611. SessionEventType.ModelStreaming,
  2612. { kind: "tool_input_delta", delta: 'b"}', done: false, toolCallId: "tc-write" },
  2613. { timestampMs: base + 200, turnId },
  2614. );
  2615. log.push(
  2616. SessionEventType.ModelStreaming,
  2617. { kind: "tool_input_end", delta: "", done: true, toolCallId: "tc-write" },
  2618. { timestampMs: base + 300, turnId },
  2619. );
  2620. const { deltasPerEvent, projection } = runAll(log.events);
  2621. expect(inputTextAppends(deltasPerEvent[4] ?? [])).toEqual([]);
  2622. expect(inputTextAppends(deltasPerEvent[5] ?? [])).toEqual(['b"}']);
  2623. expect(
  2624. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  2625. ).toMatchObject({ inputText: '{"content":"ab"}' });
  2626. });
  2627. it("STIP07:Write 被取消时把窗口内 suffix 收进 cancelled row", () => {
  2628. const turnId = "turn-write-cancel";
  2629. const base = 1_700_000_030_000;
  2630. const log = new EventLog();
  2631. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2632. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "write" }, { turnId });
  2633. log.push(
  2634. SessionEventType.ModelStreaming,
  2635. {
  2636. kind: "tool_input_start",
  2637. delta: "",
  2638. done: false,
  2639. toolCallId: "tc-write",
  2640. toolName: "Write",
  2641. },
  2642. { timestampMs: base, turnId },
  2643. );
  2644. log.push(
  2645. SessionEventType.ModelStreaming,
  2646. { kind: "tool_input_delta", delta: '{"content":"a', done: false, toolCallId: "tc-write" },
  2647. { timestampMs: base + 100, turnId },
  2648. );
  2649. log.push(
  2650. SessionEventType.ModelStreaming,
  2651. { kind: "tool_input_delta", delta: 'b"}', done: false, toolCallId: "tc-write" },
  2652. { timestampMs: base + 200, turnId },
  2653. );
  2654. log.push(
  2655. SessionEventType.TurnComplete,
  2656. { response: "", tokenCount: 0, toolCallCount: 0, duration: 300, resultType: "cancelled" },
  2657. { timestampMs: base + 300, turnId },
  2658. );
  2659. const { deltasPerEvent, projection } = runAll(log.events);
  2660. expect(inputTextAppends(deltasPerEvent[4] ?? [])).toEqual([]);
  2661. expect(
  2662. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  2663. ).toMatchObject({ status: "cancelled", inputText: '{"content":"ab"}' });
  2664. });
  2665. it("STIP08:非 Write/Edit 工具保留逐投影增量", () => {
  2666. const turnId = "turn-bash";
  2667. const base = 1_700_000_040_000;
  2668. const log = new EventLog();
  2669. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2670. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId });
  2671. log.push(
  2672. SessionEventType.ModelStreaming,
  2673. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-bash", toolName: "Bash" },
  2674. { timestampMs: base, turnId },
  2675. );
  2676. log.push(
  2677. SessionEventType.ModelStreaming,
  2678. { kind: "tool_input_delta", delta: '{"command":"p', done: false, toolCallId: "tc-bash" },
  2679. { timestampMs: base + 100, turnId },
  2680. );
  2681. log.push(
  2682. SessionEventType.ModelStreaming,
  2683. { kind: "tool_input_delta", delta: 'wd"}', done: false, toolCallId: "tc-bash" },
  2684. { timestampMs: base + 200, turnId },
  2685. );
  2686. const { deltasPerEvent } = runAll(log.events);
  2687. expect(inputTextAppends(deltasPerEvent[3] ?? [])).toEqual(['{"command":"p']);
  2688. expect(inputTextAppends(deltasPerEvent[4] ?? [])).toEqual(['wd"}']);
  2689. });
  2690. it("Q:AskUserQuestion 权限等待态 → structured userInput pendingInteraction", () => {
  2691. const turnId = "turn-ask";
  2692. const log = new EventLog();
  2693. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2694. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "帮我做个番茄钟" }, { turnId });
  2695. log.push(
  2696. SessionEventType.ToolCallScheduled,
  2697. {
  2698. toolCallId: "ask-1",
  2699. toolName: "AskUserQuestion",
  2700. input: {
  2701. questions: [
  2702. {
  2703. question: "你想把这个番茄时钟作为什么形式存在?",
  2704. header: "形式",
  2705. options: [
  2706. { label: "独立新页面", description: "新增页面", preview: "新增页面预览" },
  2707. { label: "独立小工具视图", description: "嵌入现有界面" },
  2708. ],
  2709. },
  2710. ],
  2711. },
  2712. schedule: { parallelGroups: [["ask-1"]], executionOrder: ["ask-1"] },
  2713. },
  2714. { turnId },
  2715. );
  2716. log.push(
  2717. SessionEventType.PermissionRequested,
  2718. {
  2719. requestId: "ask-request-1",
  2720. toolCallId: "ask-1",
  2721. toolName: "AskUserQuestion",
  2722. riskLevel: "low",
  2723. reason: "AskUserQuestion pauses execution to collect answers from the user",
  2724. origin: {
  2725. kind: "subagent",
  2726. agentId: "agent-ask",
  2727. agentType: "general-purpose",
  2728. childSessionId: "sess-child-ask",
  2729. description: "Ask from child",
  2730. parentSessionId: "session-1",
  2731. parentToolCallId: "call-parent-agent",
  2732. parentTurnId: turnId,
  2733. },
  2734. input: {
  2735. questions: [
  2736. {
  2737. question: "你想把这个番茄时钟作为什么形式存在?",
  2738. header: "形式",
  2739. options: [
  2740. { label: "独立新页面", description: "新增页面", preview: "新增页面预览" },
  2741. { label: "独立小工具视图", description: "嵌入现有界面" },
  2742. ],
  2743. },
  2744. ],
  2745. },
  2746. },
  2747. { turnId },
  2748. );
  2749. const { projection } = runAll(log.events);
  2750. const snapshot = projection.getSnapshot();
  2751. const toolRow = snapshot.rows.window.find((row) => row.kind === "toolCall");
  2752. expect(toolRow).toMatchObject({
  2753. status: "pendingApproval",
  2754. approvalInteractionId: "ask-request-1",
  2755. });
  2756. expect(snapshot.pendingInteractions).toHaveLength(1);
  2757. expect(snapshot.pendingInteractions[0]).toMatchObject({
  2758. interactionId: "ask-request-1",
  2759. kind: "userInput",
  2760. anchorRowId: toolRow?.rowId,
  2761. payload: {
  2762. kind: "userInput",
  2763. toolName: "AskUserQuestion",
  2764. toolCallId: "ask-1",
  2765. origin: {
  2766. kind: "subagent",
  2767. agentId: "agent-ask",
  2768. childSessionId: "sess-child-ask",
  2769. parentSessionId: "session-1",
  2770. parentToolCallId: "call-parent-agent",
  2771. },
  2772. prompt: "AskUserQuestion pauses execution to collect answers from the user",
  2773. freeText: true,
  2774. schema: { toolName: "AskUserQuestion" },
  2775. questions: [
  2776. {
  2777. question: "你想把这个番茄时钟作为什么形式存在?",
  2778. header: "形式",
  2779. options: [
  2780. {
  2781. value: "独立新页面",
  2782. label: "独立新页面",
  2783. description: "新增页面",
  2784. preview: "新增页面预览",
  2785. },
  2786. { value: "独立小工具视图", label: "独立小工具视图", description: "嵌入现有界面" },
  2787. ],
  2788. },
  2789. ],
  2790. },
  2791. });
  2792. const autoResolutionLog = new EventLog();
  2793. const hiddenGrace = {
  2794. state: "hiddenGrace" as const,
  2795. startedAt: 1_700_000_000_000,
  2796. visibleAt: 1_700_000_060_000,
  2797. deadlineAt: 1_700_000_300_000,
  2798. };
  2799. projection.applyEvent(
  2800. autoResolutionLog.push(
  2801. SessionEventType.UserInputAutoResolutionUpdated,
  2802. {
  2803. interactionId: "ask-request-1",
  2804. toolCallId: "ask-1",
  2805. autoResolution: hiddenGrace,
  2806. },
  2807. { turnId },
  2808. ),
  2809. );
  2810. expect(projection.getSnapshot().pendingInteractions[0]?.autoResolution).toEqual(hiddenGrace);
  2811. const visibleCountdown = { ...hiddenGrace, state: "visibleCountdown" as const };
  2812. projection.applyEvent(
  2813. autoResolutionLog.push(
  2814. SessionEventType.UserInputAutoResolutionUpdated,
  2815. {
  2816. interactionId: "ask-request-1",
  2817. toolCallId: "ask-1",
  2818. autoResolution: visibleCountdown,
  2819. },
  2820. { turnId },
  2821. ),
  2822. );
  2823. expect(projection.getSnapshot().pendingInteractions[0]?.autoResolution).toEqual(
  2824. visibleCountdown,
  2825. );
  2826. const snoozed = {
  2827. state: "snoozed" as const,
  2828. startedAt: hiddenGrace.startedAt,
  2829. snoozedAt: 1_700_000_299_000,
  2830. };
  2831. projection.applyEvent(
  2832. autoResolutionLog.push(
  2833. SessionEventType.UserInputAutoResolutionUpdated,
  2834. {
  2835. interactionId: "ask-request-1",
  2836. toolCallId: "ask-1",
  2837. autoResolution: snoozed,
  2838. },
  2839. { turnId },
  2840. ),
  2841. );
  2842. expect(projection.getSnapshot().pendingInteractions[0]?.autoResolution).toEqual(snoozed);
  2843. const resume = new EventLog();
  2844. projection.applyEvent(
  2845. resume.push(
  2846. SessionEventType.PermissionResolved,
  2847. { requestId: "ask-request-1", toolCallId: "ask-1", decision: "allow" },
  2848. { turnId },
  2849. ),
  2850. );
  2851. expect(projection.getSnapshot().pendingInteractions).toHaveLength(0);
  2852. });
  2853. it("Q:ExitPlanMode 权限等待态 → plan approval elicitation pendingInteraction", () => {
  2854. const turnId = "turn-plan";
  2855. const log = new EventLog();
  2856. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2857. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "进入计划模式" }, { turnId });
  2858. log.push(
  2859. SessionEventType.ToolCallScheduled,
  2860. {
  2861. toolCallId: "exit-plan-1",
  2862. toolName: "ExitPlanMode",
  2863. input: { plan: "1. 增加协议\n2. 补 UI" },
  2864. schedule: { parallelGroups: [["exit-plan-1"]], executionOrder: ["exit-plan-1"] },
  2865. },
  2866. { turnId },
  2867. );
  2868. log.push(
  2869. SessionEventType.PermissionRequested,
  2870. {
  2871. requestId: "plan-request-1",
  2872. toolCallId: "exit-plan-1",
  2873. toolName: "ExitPlanMode",
  2874. riskLevel: "low",
  2875. reason: "ExitPlanMode requires user approval before implementation",
  2876. input: { plan: "1. 增加协议\n2. 补 UI" },
  2877. },
  2878. { turnId },
  2879. );
  2880. const { projection } = runAll(log.events);
  2881. expect(projection.getSnapshot().pendingInteractions[0]).toMatchObject({
  2882. kind: "userInput",
  2883. payload: {
  2884. kind: "userInput",
  2885. toolName: "ExitPlanMode",
  2886. toolCallId: "exit-plan-1",
  2887. schema: { interaction: "plan_approval", toolName: "ExitPlanMode" },
  2888. questions: [
  2889. {
  2890. header: "Plan",
  2891. question: "ExitPlanMode requires user approval before implementation",
  2892. options: [
  2893. {
  2894. value: "approve",
  2895. label: "Approve",
  2896. description: "Exit plan mode and start implementation.",
  2897. },
  2898. ],
  2899. },
  2900. ],
  2901. },
  2902. });
  2903. });
  2904. it("Q:权限拒绝 → toolCall cancelled,交互清除", () => {
  2905. const turnId = "turn-1";
  2906. const log = new EventLog();
  2907. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2908. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "rm -rf" }, { turnId });
  2909. log.push(
  2910. SessionEventType.ToolCallScheduled,
  2911. {
  2912. toolCallId: "tc-1",
  2913. toolName: "bash",
  2914. input: { command: "rm -rf /" },
  2915. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  2916. },
  2917. { turnId },
  2918. );
  2919. log.push(
  2920. SessionEventType.PermissionRequested,
  2921. {
  2922. requestId: "req-1",
  2923. toolCallId: "tc-1",
  2924. toolName: "bash",
  2925. riskLevel: "high",
  2926. reason: "Destructive",
  2927. input: {},
  2928. },
  2929. { turnId },
  2930. );
  2931. log.push(
  2932. SessionEventType.PermissionResolved,
  2933. { requestId: "req-1", toolCallId: "tc-1", decision: "deny" },
  2934. { turnId },
  2935. );
  2936. const { projection } = runAll(log.events);
  2937. const snapshot = projection.getSnapshot();
  2938. expect(snapshot.pendingInteractions).toHaveLength(0);
  2939. expect(snapshot.rows.window.find((row) => row.kind === "toolCall")).toMatchObject({
  2940. status: "cancelled",
  2941. });
  2942. });
  2943. it("O:SubagentSpawned/Stopped → subagent row success 并保留 child session 下钻信息", () => {
  2944. const turnId = "turn-1";
  2945. const log = new EventLog();
  2946. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2947. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "派子代理" }, { turnId });
  2948. log.push(
  2949. SessionEventType.SubagentSpawned,
  2950. {
  2951. agentId: "agent-1",
  2952. agentType: "Explore",
  2953. childSessionId: "sess_child_1",
  2954. description: "探索项目结构",
  2955. parentToolCallId: "call-agent-1",
  2956. prompt: "请探索项目",
  2957. status: "running",
  2958. },
  2959. { turnId },
  2960. );
  2961. log.push(
  2962. SessionEventType.SubagentStopped,
  2963. {
  2964. agentId: "agent-1",
  2965. agentType: "Explore",
  2966. childSessionId: "sess_child_1",
  2967. status: "completed",
  2968. summaryText: "项目结构已经梳理完成",
  2969. },
  2970. { turnId },
  2971. );
  2972. const { projection } = runAll(log.events);
  2973. expect(
  2974. projection.getSnapshot().rows.window.find((row) => row.kind === "subagent"),
  2975. ).toMatchObject({
  2976. childSessionId: "sess_child_1",
  2977. parentToolCallId: "call-agent-1",
  2978. status: "success",
  2979. subagentType: "Explore",
  2980. summaryText: "项目结构已经梳理完成",
  2981. });
  2982. expect(projection.getSnapshot().subagents).toMatchObject({
  2983. childSessionIds: ["sess_child_1"],
  2984. running: [],
  2985. endedTotal: 1,
  2986. });
  2987. });
  2988. it("SAT12:SendMessage resumed spawn 在同一次投影中恢复原 row 和 cancellable work", () => {
  2989. const turnId = "turn-send-message-resume";
  2990. const log = new EventLog();
  2991. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2992. log.push(
  2993. SessionEventType.TurnStarted,
  2994. { turnNumber: 1, input: "先运行前台 Agent" },
  2995. { turnId },
  2996. );
  2997. log.push(
  2998. SessionEventType.SubagentSpawned,
  2999. {
  3000. agentId: "agent-resume",
  3001. agentType: "general-purpose",
  3002. childSessionId: "sess-child-resume",
  3003. description: "前台任务",
  3004. parentToolCallId: "call-agent",
  3005. status: "running",
  3006. },
  3007. { turnId },
  3008. );
  3009. log.push(
  3010. SessionEventType.SubagentStopped,
  3011. {
  3012. agentId: "agent-resume",
  3013. agentType: "general-purpose",
  3014. childSessionId: "sess-child-resume",
  3015. parentToolCallId: "call-agent",
  3016. status: "completed",
  3017. },
  3018. { turnId },
  3019. );
  3020. const projection = new ProductProjection("session-1", "epoch-1");
  3021. for (const item of log.events) projection.applyEvent(item);
  3022. const resumedEvent = log.push(
  3023. SessionEventType.SubagentSpawned,
  3024. {
  3025. agentId: "agent-resume",
  3026. agentType: "general-purpose",
  3027. background: true,
  3028. childSessionId: "sess-child-resume",
  3029. description: "恢复到后台",
  3030. parentToolCallId: "call-send-message",
  3031. resumed: true,
  3032. status: "running",
  3033. },
  3034. { turnId },
  3035. );
  3036. const deltas = projection.applyEvent(resumedEvent);
  3037. const snapshot = projection.getSnapshot();
  3038. expect(
  3039. snapshot.rows.window.filter(
  3040. (row) => row.kind === "subagent" && row.entityId === "agent-resume",
  3041. ),
  3042. ).toHaveLength(1);
  3043. expect(snapshot.rows.window.find((row) => row.kind === "subagent")).toMatchObject({
  3044. childSessionId: "sess-child-resume",
  3045. parentToolCallId: "call-agent",
  3046. status: "running",
  3047. });
  3048. expect(snapshot.backgroundWorks).toEqual([
  3049. expect.objectContaining({
  3050. workId: "agent-resume",
  3051. kind: "subagent",
  3052. childSessionId: "sess-child-resume",
  3053. cancellable: true,
  3054. status: "running",
  3055. title: "恢复到后台",
  3056. }),
  3057. ]);
  3058. expect(snapshot.subagents).toMatchObject({
  3059. childSessionIds: ["sess-child-resume"],
  3060. running: [expect.objectContaining({ childSessionId: "sess-child-resume" })],
  3061. endedTotal: 0,
  3062. });
  3063. expect(
  3064. deltas.some(
  3065. (delta) => delta.op === "state.updated" && delta.patch.backgroundWorks?.length === 1,
  3066. ),
  3067. ).toBe(true);
  3068. expect(
  3069. deltas.some(
  3070. (delta) => delta.op === "state.updated" && delta.patch.subagents?.running.length === 1,
  3071. ),
  3072. ).toBe(true);
  3073. projection.applyEvent(
  3074. log.push(
  3075. SessionEventType.BackgroundTaskCompleted,
  3076. {
  3077. taskId: "agent-resume",
  3078. toolName: "Agent",
  3079. taskKind: "subagent",
  3080. childSessionId: "sess-child-resume",
  3081. status: "cancelled",
  3082. cancellable: false,
  3083. },
  3084. { turnId },
  3085. ),
  3086. );
  3087. projection.applyEvent(
  3088. log.push(
  3089. SessionEventType.SubagentStopped,
  3090. {
  3091. agentId: "agent-resume",
  3092. agentType: "general-purpose",
  3093. background: true,
  3094. childSessionId: "sess-child-resume",
  3095. parentToolCallId: "call-send-message",
  3096. status: "cancelled",
  3097. },
  3098. { turnId },
  3099. ),
  3100. );
  3101. const terminalSnapshot = projection.getSnapshot();
  3102. expect(terminalSnapshot.rows.window.find((row) => row.kind === "subagent")).toMatchObject({
  3103. parentToolCallId: "call-agent",
  3104. status: "cancelled",
  3105. });
  3106. expect(terminalSnapshot.backgroundWorks).toEqual([
  3107. expect.objectContaining({ workId: "agent-resume", status: "cancelled" }),
  3108. ]);
  3109. });
  3110. it("SAT24:7 个毫秒级并行 spawn 在每次 row 提交中原子发布完整 running 投影", () => {
  3111. const turnId = "turn-parallel-subagents";
  3112. const log = new EventLog();
  3113. log.push(SessionEventType.SessionCreated, {
  3114. mode: "default",
  3115. contextWindow: 1000,
  3116. });
  3117. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "并行派生" }, { turnId });
  3118. for (let index = 1; index <= 7; index += 1) {
  3119. log.push(
  3120. SessionEventType.SubagentSpawned,
  3121. {
  3122. agentId: `agent-${index}`,
  3123. agentType: "Explore",
  3124. childSessionId: `sess_child_${index}`,
  3125. description: `并行子智能体 ${index}`,
  3126. parentToolCallId: `call-agent-${index}`,
  3127. status: "running",
  3128. },
  3129. { turnId, timestampMs: 1_700_000_000_000 + index },
  3130. );
  3131. }
  3132. const projection = new ProductProjection("session-1", "epoch-1");
  3133. for (const event of log.events) {
  3134. const deltas = projection.applyEvent(event);
  3135. if (event.type !== SessionEventType.SubagentSpawned) continue;
  3136. const expectedCount = Number((event.payload as { agentId: string }).agentId.split("-")[1]);
  3137. const subagentPatch = deltas.find(
  3138. (delta) => delta.op === "state.updated" && delta.patch.subagents,
  3139. );
  3140. expect(deltas.some((delta) => delta.op === "row.appended")).toBe(true);
  3141. expect(subagentPatch).toMatchObject({
  3142. op: "state.updated",
  3143. patch: {
  3144. subagents: {
  3145. childSessionIds: expect.arrayContaining([`sess_child_${expectedCount}`]),
  3146. endedTotal: 0,
  3147. },
  3148. },
  3149. });
  3150. expect(projection.getSnapshot().subagents?.running).toHaveLength(expectedCount);
  3151. }
  3152. expect(projection.getSnapshot().subagents).toMatchObject({
  3153. childSessionIds: Array.from({ length: 7 }, (_, index) => `sess_child_${index + 1}`),
  3154. endedTotal: 0,
  3155. });
  3156. });
  3157. it("SAT22:cold seed 持续排除未持久化 ghost,直到新的合法 spawn", () => {
  3158. const turnId = "turn-cold-subagent-seed";
  3159. const log = new EventLog();
  3160. log.push(SessionEventType.SessionCreated, {
  3161. mode: "default",
  3162. contextWindow: 1000,
  3163. });
  3164. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "历史派生" }, { turnId });
  3165. log.push(
  3166. SessionEventType.SubagentSpawned,
  3167. {
  3168. agentId: "agent-reliable",
  3169. agentType: "Explore",
  3170. childSessionId: "sess-reliable",
  3171. description: "可靠 child",
  3172. status: "running",
  3173. },
  3174. { turnId },
  3175. );
  3176. log.push(
  3177. SessionEventType.SubagentSpawned,
  3178. {
  3179. agentId: "agent-ghost",
  3180. agentType: "Explore",
  3181. childSessionId: "sess-ghost",
  3182. description: "旧版本 ghost",
  3183. status: "running",
  3184. },
  3185. { turnId },
  3186. );
  3187. const projection = new ProductProjection("session-1", "epoch-1");
  3188. for (const event of log.events) projection.applyEvent(event);
  3189. projection.seedSubagents({
  3190. revision: 10,
  3191. childSessionIds: ["sess-reliable"],
  3192. running: [
  3193. {
  3194. agentId: "agent-reliable",
  3195. childSessionId: "sess-reliable",
  3196. status: "running",
  3197. subagentType: "Explore",
  3198. title: "可靠 child",
  3199. },
  3200. ],
  3201. });
  3202. expect(projection.getSnapshot().subagents).toMatchObject({
  3203. revision: 10,
  3204. childSessionIds: ["sess-reliable"],
  3205. running: [{ childSessionId: "sess-reliable" }],
  3206. endedTotal: 0,
  3207. });
  3208. projection.applyEvent(
  3209. log.push(SessionEventType.ModelSelected, {
  3210. modelSelection: {
  3211. providerId: "test-provider",
  3212. modelId: "test-model",
  3213. },
  3214. }),
  3215. );
  3216. expect(projection.getSnapshot().subagents?.childSessionIds).toEqual(["sess-reliable"]);
  3217. projection.applyEvent(
  3218. log.push(
  3219. SessionEventType.SubagentSpawned,
  3220. {
  3221. agentId: "agent-ghost",
  3222. agentType: "Explore",
  3223. childSessionId: "sess-ghost",
  3224. description: "已持久化后恢复",
  3225. resumed: true,
  3226. status: "running",
  3227. },
  3228. { turnId },
  3229. ),
  3230. );
  3231. expect(projection.getSnapshot().subagents?.childSessionIds).toEqual([
  3232. "sess-reliable",
  3233. "sess-ghost",
  3234. ]);
  3235. expect(projection.getSnapshot().subagents?.running).toHaveLength(2);
  3236. });
  3237. it("SAT22:非空 cold manifest 即使旧查询 revision 为 0 也会建立有效版本", () => {
  3238. const projection = new ProductProjection("session-1", "epoch-1");
  3239. projection.seedSubagents({
  3240. revision: 0,
  3241. childSessionIds: ["sess-reliable"],
  3242. running: [],
  3243. });
  3244. expect(projection.getSnapshot().subagents).toMatchObject({
  3245. revision: 1,
  3246. childSessionIds: ["sess-reliable"],
  3247. endedTotal: 1,
  3248. });
  3249. });
  3250. // ── M 组:turn steer 队列 ──
  3251. it("M:steer 入队/注入 —— queue.items 生命周期", () => {
  3252. const turnId = "turn-1";
  3253. const log = new EventLog();
  3254. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3255. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  3256. log.push(
  3257. SessionEventType.TurnSteerQueued,
  3258. {
  3259. pendingInputId: "pi-1",
  3260. inputId: "command-original",
  3261. input: "顺便加个测试",
  3262. inputPreview: "顺便加个测试",
  3263. inputSize: 6,
  3264. targetTurnId: turnId,
  3265. queueLength: 1,
  3266. delivery: "guide",
  3267. intent: {
  3268. sourceCommandId: "command-original",
  3269. queueItemId: "pi-1",
  3270. clientId: "mobile-client",
  3271. kind: "sendText",
  3272. admissionSeq: 12,
  3273. admittedAt: 1234,
  3274. requestedDelivery: "guide",
  3275. admittedDelivery: "guide",
  3276. highspeed: {
  3277. schemaVersion: 1,
  3278. cardId: "hsc-queue",
  3279. taskId: "session-1",
  3280. provider: "builtin:bigmodel-coding-plan",
  3281. model: "GLM-5.3",
  3282. issuedAt: 1_700_000_000_000,
  3283. expiresAt: 1_700_000_900_000,
  3284. },
  3285. attachmentRefs: [
  3286. { ref: "artifact://one", fileName: "one.txt", mime: "text/plain", bytes: 3 },
  3287. ],
  3288. },
  3289. },
  3290. { turnId },
  3291. );
  3292. const { projection } = runAll(log.events);
  3293. expect(projection.getSnapshot().queue.items).toHaveLength(1);
  3294. expect(projection.getSnapshot().queue.items[0]).toMatchObject({
  3295. queueItemId: "pi-1",
  3296. kind: "sendText",
  3297. text: "顺便加个测试",
  3298. sourceCommandId: "command-original",
  3299. clientId: "mobile-client",
  3300. attachments: [{ ref: "artifact://one", fileName: "one.txt", mime: "text/plain", bytes: 3 }],
  3301. delivery: { requested: "guide", admitted: "guide" },
  3302. order: { admissionSeq: 12, queuePosition: 0 },
  3303. steer: { state: "steering" },
  3304. dispatch: { state: "queued" },
  3305. highspeed: { cardId: "hsc-queue", expiresAt: 1_700_000_900_000 },
  3306. admittedAt: 1234,
  3307. });
  3308. const drain = new EventLog();
  3309. drain.push(
  3310. SessionEventType.TurnSteerDrained,
  3311. {
  3312. pendingInputIds: ["pi-1"],
  3313. targetTurnId: turnId,
  3314. injectedMessageIds: ["message-drained"],
  3315. drainedInputs: [
  3316. {
  3317. pendingInputId: "pi-1",
  3318. messageId: "message-drained",
  3319. text: "顺便加个测试",
  3320. delivery: "guide",
  3321. intent: {
  3322. sourceCommandId: "command-original",
  3323. queueItemId: "pi-1",
  3324. clientId: "mobile-client",
  3325. kind: "sendText",
  3326. admissionSeq: 12,
  3327. admittedAt: 1234,
  3328. requestedDelivery: "guide",
  3329. admittedDelivery: "guide",
  3330. attachmentRefs: [
  3331. {
  3332. ref: "artifact://one",
  3333. fileName: "one.txt",
  3334. mime: "text/plain",
  3335. bytes: 3,
  3336. },
  3337. ],
  3338. },
  3339. },
  3340. ],
  3341. },
  3342. { turnId },
  3343. );
  3344. for (const event of drain.events) projection.applyEvent(event);
  3345. expect(projection.getSnapshot().queue.items).toHaveLength(0);
  3346. expect(projection.getSnapshot().rows.window.at(-1)).toMatchObject({
  3347. kind: "userInput",
  3348. text: "顺便加个测试",
  3349. guided: true,
  3350. sourceCommandId: "command-original",
  3351. clientId: "mobile-client",
  3352. attachments: [{ ref: "artifact://one", fileName: "one.txt", mime: "text/plain", bytes: 3 }],
  3353. });
  3354. });
  3355. it("M:goal command 入队 —— queue item 保留 sendGoalCommand kind", () => {
  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-goal",
  3364. commandKind: "sendGoalCommand",
  3365. input: "/goal 新目标",
  3366. inputPreview: "/goal 新目标",
  3367. inputSize: 12,
  3368. targetTurnId: turnId,
  3369. queueLength: 1,
  3370. },
  3371. { turnId },
  3372. );
  3373. const { projection } = runAll(log.events);
  3374. expect(projection.getSnapshot().queue.items[0]).toMatchObject({
  3375. queueItemId: "pi-goal",
  3376. kind: "sendGoalCommand",
  3377. text: "/goal 新目标",
  3378. });
  3379. });
  3380. it("M:guide/附件 fallback 保留 requested/admitted 与 reasonCode", () => {
  3381. const log = new EventLog();
  3382. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3383. log.push(
  3384. SessionEventType.TurnSteerQueued,
  3385. {
  3386. pendingInputId: "queue-fallback",
  3387. inputId: "command-fallback",
  3388. input: "带附件",
  3389. inputPreview: "带附件",
  3390. inputSize: 9,
  3391. delivery: "queue",
  3392. targetTurnId: "turn-1",
  3393. queueLength: 1,
  3394. intent: {
  3395. sourceCommandId: "command-fallback",
  3396. queueItemId: "queue-fallback",
  3397. clientId: "desktop-client",
  3398. kind: "sendText",
  3399. admissionSeq: 2,
  3400. admittedAt: 50,
  3401. requestedDelivery: "guide",
  3402. admittedDelivery: "queue",
  3403. fallbackReasonCode: "guide.attachmentsUnsupported",
  3404. attachmentRefs: [
  3405. { ref: "artifact://a", fileName: "a.txt", mime: "text/plain", bytes: 1 },
  3406. ],
  3407. },
  3408. },
  3409. { turnId: "turn-1" },
  3410. );
  3411. const { projection } = runAll(log.events);
  3412. expect(projection.getSnapshot().queue.items[0]).toMatchObject({
  3413. sourceCommandId: "command-fallback",
  3414. attachments: [{ ref: "artifact://a" }],
  3415. delivery: {
  3416. requested: "guide",
  3417. admitted: "queue",
  3418. fallbackReasonCode: "guide.attachmentsUnsupported",
  3419. },
  3420. steer: { state: "fellBack", reasonCode: "guide.attachmentsUnsupported" },
  3421. });
  3422. });
  3423. it("M:text-only terminal 以 delivery changed 原地把 guide 改投 queue", () => {
  3424. const log = new EventLog();
  3425. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3426. log.push(
  3427. SessionEventType.TurnSteerQueued,
  3428. {
  3429. pendingInputId: "queue-guide-terminal",
  3430. input: "等下一个工具边界",
  3431. inputPreview: "等下一个工具边界",
  3432. inputSize: 9,
  3433. delivery: "guide",
  3434. targetTurnId: "turn-1",
  3435. queueLength: 1,
  3436. intent: {
  3437. sourceCommandId: "command-guide-terminal",
  3438. queueItemId: "queue-guide-terminal",
  3439. clientId: "desktop-client",
  3440. kind: "sendText",
  3441. admissionSeq: 3,
  3442. admittedAt: 60,
  3443. requestedDelivery: "guide",
  3444. admittedDelivery: "guide",
  3445. },
  3446. },
  3447. { turnId: "turn-1" },
  3448. );
  3449. log.push(
  3450. SessionEventType.TurnSteerDeliveryChanged,
  3451. {
  3452. pendingInputId: "queue-guide-terminal",
  3453. targetTurnId: "turn-1",
  3454. requestedDelivery: "guide",
  3455. admittedDelivery: "queue",
  3456. fallbackReasonCode: "guide.noToolBoundary",
  3457. },
  3458. { turnId: "turn-1" },
  3459. );
  3460. const { projection } = runAll(log.events);
  3461. expect(projection.getSnapshot().queue.items).toEqual([
  3462. expect.objectContaining({
  3463. queueItemId: "queue-guide-terminal",
  3464. text: "等下一个工具边界",
  3465. delivery: {
  3466. requested: "guide",
  3467. admitted: "queue",
  3468. fallbackReasonCode: "guide.noToolBoundary",
  3469. },
  3470. steer: { state: "fellBack", reasonCode: "guide.noToolBoundary" },
  3471. }),
  3472. ]);
  3473. });
  3474. // ── 错误态 ──
  3475. it("错误:turn_error → phase=error + lastError + turnHeader failed", () => {
  3476. const turnId = "turn-1";
  3477. const log = new EventLog();
  3478. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3479. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  3480. log.push(
  3481. SessionEventType.TurnError,
  3482. { error: { type: "ProviderError", message: "rate limited" }, turnPhase: "model" },
  3483. { turnId },
  3484. );
  3485. const { projection } = runAll(log.events);
  3486. const snapshot = projection.getSnapshot();
  3487. expect(snapshot.control.phase).toBe("error");
  3488. expect(snapshot.control.lastError).toMatchObject({
  3489. code: "ProviderError",
  3490. message: "rate limited",
  3491. recoverable: true,
  3492. source: "runtime",
  3493. });
  3494. expect(snapshot.rows.window.find((row) => row.kind === "turnHeader")).toMatchObject({
  3495. state: "failed",
  3496. });
  3497. });
  3498. it("错误:TurnError 保留底层错误详情到 V4 lastError", () => {
  3499. const log = new EventLog();
  3500. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3501. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  3502. log.push(
  3503. SessionEventType.TurnError,
  3504. {
  3505. error: {
  3506. type: "ModelError",
  3507. message: "Model request failed",
  3508. underlyingErrorMessage: "Runtime headers request failed",
  3509. underlyingErrorDetail: "Runtime headers helper timed out after 10000ms.",
  3510. },
  3511. turnPhase: "model",
  3512. },
  3513. { turnId: "turn-1" },
  3514. );
  3515. expect(runAll(log.events).projection.getSnapshot().control.lastError).toMatchObject({
  3516. underlyingErrorMessage: "Runtime headers request failed",
  3517. underlyingErrorDetail: "Runtime headers helper timed out after 10000ms.",
  3518. });
  3519. });
  3520. it.each([
  3521. ["card-highspeed-1", "card-highspeed-1"],
  3522. [null, null],
  3523. ] as const)("错误:TurnError 的 Highspeed 卡归因 %s 透传到 V4 lastError", (value, expected) => {
  3524. const log = new EventLog();
  3525. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3526. log.push(
  3527. SessionEventType.TurnError,
  3528. {
  3529. error: {
  3530. type: "ModelError",
  3531. message: "Model creation failed",
  3532. code: "provider_not_found",
  3533. attribution: { source: "provider", highspeedCardId: value },
  3534. },
  3535. turnPhase: "model_creation",
  3536. },
  3537. { turnId: "turn-1" },
  3538. );
  3539. expect(runAll(log.events).projection.getSnapshot().control.lastError).toMatchObject({
  3540. code: "provider_not_found",
  3541. attribution: { source: "provider", highspeedCardId: expected },
  3542. });
  3543. });
  3544. it("错误:请求期 Highspeed 无处可退的归因原样透传到 V4 lastError", () => {
  3545. // 3402 是 provider 错误码而非目录错误;Renderer 退卡只能依赖 Core 发布的结构化事实。
  3546. const log = new EventLog();
  3547. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3548. log.push(
  3549. SessionEventType.TurnError,
  3550. {
  3551. error: {
  3552. type: "ModelError",
  3553. message: "highspeed card is invalid",
  3554. code: "3402",
  3555. attribution: {
  3556. source: "provider",
  3557. providerId: "account:bigmodel-highspeed-card",
  3558. providerErrorCode: "3402",
  3559. statusCode: 400,
  3560. highspeedCardId: "card-highspeed-request",
  3561. highspeedFallbackUnavailable: true,
  3562. },
  3563. },
  3564. turnPhase: "model",
  3565. },
  3566. { turnId: "turn-1" },
  3567. );
  3568. expect(runAll(log.events).projection.getSnapshot().control.lastError).toMatchObject({
  3569. code: "3402",
  3570. source: "provider",
  3571. attribution: {
  3572. providerErrorCode: "3402",
  3573. highspeedCardId: "card-highspeed-request",
  3574. highspeedFallbackUnavailable: true,
  3575. },
  3576. });
  3577. });
  3578. it("错误:TurnError 保留 future queue 并暂停自动消费", () => {
  3579. const turnId = "turn-error-queue";
  3580. const log = new EventLog();
  3581. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3582. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "首轮失败" }, { turnId });
  3583. log.push(
  3584. SessionEventType.TurnSteerQueued,
  3585. {
  3586. pendingInputId: "queue-after-error",
  3587. inputId: "input-after-error",
  3588. input: "错误后仍要发送",
  3589. inputPreview: "错误后仍要发送",
  3590. inputSize: 24,
  3591. targetTurnId: turnId,
  3592. queueLength: 1,
  3593. delivery: "queue",
  3594. },
  3595. { turnId },
  3596. );
  3597. log.push(
  3598. SessionEventType.TurnError,
  3599. { error: { type: "ProviderError", message: "provider 失败" }, turnPhase: "model" },
  3600. { turnId },
  3601. );
  3602. const { projection } = runAll(log.events);
  3603. const snapshot = projection.getSnapshot();
  3604. expect(snapshot.control.phase).toBe("error");
  3605. expect(snapshot.queue).toMatchObject({
  3606. autoDrain: false,
  3607. pauseReason: "error",
  3608. items: [expect.objectContaining({ queueItemId: "queue-after-error" })],
  3609. });
  3610. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  3611. });
  3612. it.each([true, false])("错误:TurnError retryable=%s 原样映射 recoverable", (retryable) => {
  3613. const turnId = "turn-retryable";
  3614. const log = new EventLog();
  3615. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3616. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  3617. log.push(
  3618. SessionEventType.TurnError,
  3619. {
  3620. error: { type: "ProviderError", message: "failed", retryable },
  3621. turnPhase: "model",
  3622. },
  3623. { turnId },
  3624. );
  3625. const { projection } = runAll(log.events);
  3626. expect(projection.getSnapshot().control.lastError?.recoverable).toBe(retryable);
  3627. });
  3628. it("错误:TurnError 结构化归因进入 lastError,但不改写既有 recoverable", () => {
  3629. const turnId = "turn-attribution";
  3630. const log = new EventLog();
  3631. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3632. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  3633. log.push(
  3634. SessionEventType.TurnError,
  3635. {
  3636. error: {
  3637. type: "model_request_failed",
  3638. message: "Provider stream failed",
  3639. attribution: {
  3640. source: "network",
  3641. reason: "network_error",
  3642. providerId: "default-deepseek",
  3643. modelId: "deepseek-v4-flash",
  3644. providerKind: "anthropic",
  3645. transport: "sse",
  3646. statusCode: 503,
  3647. retryable: false,
  3648. },
  3649. },
  3650. turnPhase: "model",
  3651. },
  3652. { turnId },
  3653. );
  3654. const { projection } = runAll(log.events);
  3655. const snapshot = projection.getSnapshot();
  3656. expect(snapshot.control.lastError).toMatchObject({
  3657. source: "network",
  3658. recoverable: true,
  3659. attribution: {
  3660. source: "network",
  3661. reason: "network_error",
  3662. providerId: "default-deepseek",
  3663. modelId: "deepseek-v4-flash",
  3664. providerKind: "anthropic",
  3665. transport: "sse",
  3666. statusCode: 503,
  3667. retryable: false,
  3668. },
  3669. });
  3670. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  3671. });
  3672. it("错误后新 turn 清除 lastError(与旧 reducer 同一裁决)", () => {
  3673. const log = new EventLog();
  3674. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3675. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  3676. log.push(
  3677. SessionEventType.TurnError,
  3678. { error: { type: "X", message: "boom" }, turnPhase: "model" },
  3679. { turnId: "turn-1" },
  3680. );
  3681. log.push(SessionEventType.TurnStarted, { turnNumber: 2, input: "retry" }, { turnId: "turn-2" });
  3682. const { projection } = runAll(log.events);
  3683. expect(projection.getSnapshot().control.lastError).toBeNull();
  3684. expect(projection.getSnapshot().control.phase).toBe("running");
  3685. });
  3686. it("K10:retry 目标只允许全时间线最后一条 assistantText row", () => {
  3687. const log = new EventLog();
  3688. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3689. for (const turnNumber of [1, 2]) {
  3690. const turnId = `turn-${turnNumber}`;
  3691. log.push(
  3692. SessionEventType.TurnStarted,
  3693. { turnNumber, input: `Q${turnNumber}`, messageId: `user-${turnNumber}` },
  3694. { turnId },
  3695. );
  3696. log.push(
  3697. SessionEventType.ModelStreaming,
  3698. {
  3699. kind: "text_start",
  3700. delta: "",
  3701. done: false,
  3702. assistantMessageId: `assistant-${turnNumber}`,
  3703. },
  3704. { turnId },
  3705. );
  3706. log.push(
  3707. SessionEventType.ModelStreaming,
  3708. { kind: "text_delta", delta: `A${turnNumber}`, done: false },
  3709. { turnId },
  3710. );
  3711. log.push(
  3712. SessionEventType.ModelStreaming,
  3713. { kind: "text_end", delta: "", done: false },
  3714. { turnId },
  3715. );
  3716. log.push(
  3717. SessionEventType.TurnComplete,
  3718. {
  3719. response: `A${turnNumber}`,
  3720. tokenCount: 1,
  3721. toolCallCount: 0,
  3722. duration: 100,
  3723. resultType: "success",
  3724. },
  3725. { turnId },
  3726. );
  3727. }
  3728. const { projection } = runAll(log.events);
  3729. const assistantRows = projection
  3730. .getSnapshot()
  3731. .rows.window.filter((row) => row.kind === "assistantText");
  3732. expect(assistantRows).toHaveLength(2);
  3733. expect(projection.isLatestRetryAssistantRow(assistantRows[0]!.rowId)).toBe(false);
  3734. expect(projection.isLatestRetryAssistantRow(assistantRows[1]!.rowId)).toBe(true);
  3735. expect(assistantRows[0]!.actions?.canRetry).not.toBe(true);
  3736. expect(assistantRows[1]!.actions?.canRetry).toBe(true);
  3737. expect(projection.getMessageIdForRow(assistantRows[1]!.rowId)).toBe("assistant-2");
  3738. });
  3739. it("BG33/K11:background 结果轮无普通 retry,且不会恢复更早真实用户轮", () => {
  3740. const log = new EventLog();
  3741. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3742. const { projection } = runAll(log.events);
  3743. const apply = (type: SessionEventTypeUnion, payload: unknown, turnId: string): void => {
  3744. projection.applyEvent(log.push(type, payload, { turnId }));
  3745. };
  3746. const appendCompletedTurn = (input: {
  3747. assistantMessageId: string;
  3748. input: string;
  3749. inputSource?: "background_task";
  3750. messageId: string;
  3751. turnId: string;
  3752. turnNumber: number;
  3753. }): void => {
  3754. apply(
  3755. SessionEventType.TurnStarted,
  3756. {
  3757. turnNumber: input.turnNumber,
  3758. input: input.input,
  3759. messageId: input.messageId,
  3760. ...(input.inputSource
  3761. ? { inputSource: input.inputSource, inputVisibility: "model-only" }
  3762. : {}),
  3763. },
  3764. input.turnId,
  3765. );
  3766. apply(
  3767. SessionEventType.ModelStreaming,
  3768. {
  3769. kind: "text_start",
  3770. delta: "",
  3771. done: false,
  3772. assistantMessageId: input.assistantMessageId,
  3773. },
  3774. input.turnId,
  3775. );
  3776. apply(
  3777. SessionEventType.ModelStreaming,
  3778. { kind: "text_delta", delta: `answer ${input.turnNumber}`, done: false },
  3779. input.turnId,
  3780. );
  3781. apply(
  3782. SessionEventType.ModelStreaming,
  3783. { kind: "text_end", delta: "", done: false },
  3784. input.turnId,
  3785. );
  3786. apply(
  3787. SessionEventType.TurnComplete,
  3788. {
  3789. response: `answer ${input.turnNumber}`,
  3790. tokenCount: 1,
  3791. toolCallCount: 0,
  3792. duration: 100,
  3793. resultType: "success",
  3794. },
  3795. input.turnId,
  3796. );
  3797. };
  3798. appendCompletedTurn({
  3799. assistantMessageId: "assistant-user-1",
  3800. input: "Q1",
  3801. messageId: "user-1",
  3802. turnId: "turn-user-1",
  3803. turnNumber: 1,
  3804. });
  3805. let assistantRows = projection
  3806. .getSnapshot()
  3807. .rows.window.filter((row) => row.kind === "assistantText");
  3808. expect(assistantRows.map((row) => row.actions?.canRetry === true)).toEqual([true]);
  3809. appendCompletedTurn({
  3810. assistantMessageId: "assistant-background-1",
  3811. input: "background result",
  3812. inputSource: "background_task",
  3813. messageId: "wake-1",
  3814. turnId: "turn-background-1",
  3815. turnNumber: 2,
  3816. });
  3817. assistantRows = projection
  3818. .getSnapshot()
  3819. .rows.window.filter((row) => row.kind === "assistantText");
  3820. expect(assistantRows.map((row) => row.actions?.canRetry === true)).toEqual([false, false]);
  3821. expect(assistantRows[1]!.actions?.canFork).toBe(true);
  3822. const backgroundEntityId = projection.getEntityIdForRow(assistantRows[1]!.rowId);
  3823. expect(backgroundEntityId).toBeTruthy();
  3824. expect(
  3825. projection.resolveRowActionTarget(
  3826. { rowId: assistantRows[1]!.rowId, entityId: backgroundEntityId! },
  3827. "retryTurn",
  3828. ),
  3829. ).toEqual({ ok: false, status: "rejected", reasonCode: "guard.actionUnavailable" });
  3830. appendCompletedTurn({
  3831. assistantMessageId: "assistant-user-2",
  3832. input: "Q2",
  3833. messageId: "user-2",
  3834. turnId: "turn-user-2",
  3835. turnNumber: 3,
  3836. });
  3837. assistantRows = projection
  3838. .getSnapshot()
  3839. .rows.window.filter((row) => row.kind === "assistantText");
  3840. expect(assistantRows.map((row) => row.actions?.canRetry === true)).toEqual([
  3841. false,
  3842. false,
  3843. true,
  3844. ]);
  3845. });
  3846. });
  3847. describe("V4 API 重试状态投影", () => {
  3848. function runningProjection(): { log: EventLog; projection: ProductProjection } {
  3849. const log = new EventLog();
  3850. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  3851. log.push(
  3852. SessionEventType.TurnStarted,
  3853. { turnNumber: 1, input: "触发模型请求", messageId: "user-retry-1" },
  3854. { turnId: "turn-retry-1" },
  3855. );
  3856. return { log, projection: runAll(log.events).projection };
  3857. }
  3858. function modelStatus(overrides: Record<string, unknown>): Record<string, unknown> {
  3859. return {
  3860. timestamp: "2026-07-14T07:25:25.985Z",
  3861. traceId: "trace-1",
  3862. requestId: "request-retry-1",
  3863. model: { providerId: "bigmodel", modelId: "glm-5.2" },
  3864. transport: "sse",
  3865. attempt: 1,
  3866. maxAttempts: 11,
  3867. ...overrides,
  3868. };
  3869. }
  3870. it("配置读取重试保留错误类别,桌面与手机使用同一状态", () => {
  3871. const { log, projection } = runningProjection();
  3872. const deltas = projection.applyEvent(log.push(
  3873. SessionEventType.ModelNetworkStatus,
  3874. modelStatus({ type: "model_retry_scheduled", delayMs: 2000, nextAttempt: 2,
  3875. reason: "network_error", errorCode: ModelErrorCode.ModelRequestVerificationConfigNetwork }),
  3876. { turnId: "turn-retry-1" },
  3877. ));
  3878. expect(projection.getSnapshot().control.apiRetry?.reasonCode).toBe("request_verification_config_network");
  3879. expect(() => conversationSnapshotSchema.parse(projection.getSnapshot())).not.toThrow();
  3880. for (const profile of [DELIVERY_PROFILES.continuous, DELIVERY_PROFILES.replayable]) {
  3881. expect(filterConversationDeltasForProfile(deltas, profile)).toEqual(deltas);
  3882. }
  3883. });
  3884. it("429 重试在两个 delivery profile 中可见,并保持到首次有效模型进展", () => {
  3885. const { log, projection } = runningProjection();
  3886. const scheduledAt = 1_721_000_000_000;
  3887. const scheduled = log.push(
  3888. SessionEventType.ModelNetworkStatus,
  3889. modelStatus({
  3890. type: "model_retry_scheduled",
  3891. delayMs: 44_000,
  3892. nextAttempt: 2,
  3893. reason: "rate_limited",
  3894. message: "rate limited",
  3895. statusCode: 429,
  3896. }),
  3897. { turnId: "turn-retry-1", timestampMs: scheduledAt },
  3898. );
  3899. const retryDeltas = projection.applyEvent(scheduled);
  3900. expect(projection.getSnapshot().control.apiRetry).toEqual({
  3901. attempt: 1,
  3902. maxAttempts: 11,
  3903. nextRetryAt: scheduledAt + 44_000,
  3904. reasonCode: "fault.provider.rateLimited",
  3905. });
  3906. expect(() => conversationSnapshotSchema.parse(projection.getSnapshot())).not.toThrow();
  3907. for (const profile of [DELIVERY_PROFILES.continuous, DELIVERY_PROFILES.replayable]) {
  3908. expect(filterConversationDeltasForProfile(retryDeltas, profile)).toEqual(retryDeltas);
  3909. }
  3910. const retryStarted = log.push(
  3911. SessionEventType.ModelNetworkStatus,
  3912. modelStatus({ type: "model_request_started", attempt: 2 }),
  3913. { turnId: "turn-retry-1" },
  3914. );
  3915. expect(projection.applyEvent(retryStarted)).toEqual([]);
  3916. expect(projection.getSnapshot().control.apiRetry?.attempt).toBe(1);
  3917. projection.applyEvent(
  3918. log.push(
  3919. SessionEventType.ModelStreaming,
  3920. {
  3921. kind: "text_start",
  3922. delta: "",
  3923. done: false,
  3924. assistantMessageId: "assistant-retry-1",
  3925. },
  3926. { turnId: "turn-retry-1" },
  3927. ),
  3928. );
  3929. expect(projection.getSnapshot().control.apiRetry?.attempt).toBe(1);
  3930. projection.applyEvent(
  3931. log.push(
  3932. SessionEventType.ModelStreaming,
  3933. { kind: "text_delta", delta: "连接已恢复", done: false },
  3934. { turnId: "turn-retry-1" },
  3935. ),
  3936. );
  3937. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  3938. });
  3939. it("签名修复复用 provider retry live-tail 状态", () => {
  3940. const { log, projection } = runningProjection();
  3941. const scheduledAt = 1_721_000_000_000;
  3942. projection.applyEvent(
  3943. log.push(
  3944. SessionEventType.ModelNetworkStatus,
  3945. modelStatus({
  3946. type: "model_retry_scheduled",
  3947. delayMs: 0,
  3948. maxAttempts: 2,
  3949. nextAttempt: 2,
  3950. reason: "reasoning_signature_repair",
  3951. message: "thinking signature rejected",
  3952. statusCode: 400,
  3953. }),
  3954. { turnId: "turn-retry-1", timestampMs: scheduledAt },
  3955. ),
  3956. );
  3957. expect(projection.getSnapshot().control.apiRetry).toEqual({
  3958. attempt: 1,
  3959. maxAttempts: 2,
  3960. nextRetryAt: scheduledAt,
  3961. reasonCode: "fault.provider.requestFailed",
  3962. });
  3963. });
  3964. it("忽略非当前 turn 的迟到重试与完成事件", () => {
  3965. const { log, projection } = runningProjection();
  3966. const retryPayload = modelStatus({
  3967. type: "model_retry_scheduled",
  3968. delayMs: 1_000,
  3969. nextAttempt: 2,
  3970. reason: "rate_limited",
  3971. message: "rate limited",
  3972. statusCode: 429,
  3973. });
  3974. projection.applyEvent(
  3975. log.push(SessionEventType.ModelNetworkStatus, retryPayload, { turnId: "turn-stale" }),
  3976. );
  3977. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  3978. projection.applyEvent(
  3979. log.push(SessionEventType.ModelNetworkStatus, retryPayload, { turnId: "turn-retry-1" }),
  3980. );
  3981. expect(projection.getSnapshot().control.apiRetry).not.toBeNull();
  3982. projection.applyEvent(
  3983. log.push(
  3984. SessionEventType.ModelNetworkStatus,
  3985. modelStatus({ type: "model_request_completed", durationMs: 50 }),
  3986. { turnId: "turn-stale" },
  3987. ),
  3988. );
  3989. expect(projection.getSnapshot().control.apiRetry).not.toBeNull();
  3990. });
  3991. it("请求完成、不可重试失败和 turn 终态都会清理重试状态", () => {
  3992. const { log, projection } = runningProjection();
  3993. const scheduleRetry = (attempt: number) =>
  3994. projection.applyEvent(
  3995. log.push(
  3996. SessionEventType.ModelNetworkStatus,
  3997. modelStatus({
  3998. type: "model_retry_scheduled",
  3999. attempt,
  4000. delayMs: 1_000,
  4001. nextAttempt: attempt + 1,
  4002. reason: "server_error",
  4003. message: "server error",
  4004. statusCode: 503,
  4005. }),
  4006. { turnId: "turn-retry-1" },
  4007. ),
  4008. );
  4009. scheduleRetry(1);
  4010. projection.applyEvent(
  4011. log.push(
  4012. SessionEventType.ModelNetworkStatus,
  4013. modelStatus({
  4014. type: "model_request_failed",
  4015. reason: "server_error",
  4016. retryable: true,
  4017. message: "retryable",
  4018. statusCode: 503,
  4019. }),
  4020. { turnId: "turn-retry-1" },
  4021. ),
  4022. );
  4023. expect(projection.getSnapshot().control.apiRetry).not.toBeNull();
  4024. projection.applyEvent(
  4025. log.push(
  4026. SessionEventType.ModelNetworkStatus,
  4027. modelStatus({ type: "model_request_completed", attempt: 2, durationMs: 50 }),
  4028. { turnId: "turn-retry-1" },
  4029. ),
  4030. );
  4031. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  4032. scheduleRetry(2);
  4033. projection.applyEvent(
  4034. log.push(
  4035. SessionEventType.ModelNetworkStatus,
  4036. modelStatus({
  4037. type: "model_request_failed",
  4038. attempt: 3,
  4039. reason: "server_error",
  4040. retryable: false,
  4041. message: "exhausted",
  4042. statusCode: 503,
  4043. }),
  4044. { turnId: "turn-retry-1" },
  4045. ),
  4046. );
  4047. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  4048. scheduleRetry(3);
  4049. projection.applyEvent(
  4050. log.push(
  4051. SessionEventType.TurnComplete,
  4052. {
  4053. response: "done",
  4054. tokenCount: 1,
  4055. toolCallCount: 0,
  4056. duration: 100,
  4057. resultType: "success",
  4058. },
  4059. { turnId: "turn-retry-1" },
  4060. ),
  4061. );
  4062. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  4063. });
  4064. it("core SSE 恢复次数进入同一 apiRetry,并在工具进展后清理", () => {
  4065. const { log, projection } = runningProjection();
  4066. const recoveryStartedAt = 1_721_000_100_000;
  4067. projection.applyEvent(
  4068. log.push(
  4069. SessionEventType.StreamRecoveryStarted,
  4070. {
  4071. attemptId: "stream-attempt-1",
  4072. assistantMessageId: "assistant-retry-1",
  4073. failedRequestId: "request-retry-1",
  4074. failureKind: "provider_stream_error",
  4075. message: "stream disconnected",
  4076. retryNumber: 3,
  4077. maxRetries: 10,
  4078. },
  4079. { turnId: "turn-retry-1", timestampMs: recoveryStartedAt },
  4080. ),
  4081. );
  4082. expect(projection.getSnapshot().control.apiRetry).toEqual({
  4083. attempt: 3,
  4084. maxAttempts: 11,
  4085. nextRetryAt: recoveryStartedAt,
  4086. reasonCode: "fault.network.sseDisconnected",
  4087. });
  4088. projection.applyEvent(
  4089. log.push(
  4090. SessionEventType.StreamRecoveryRetryStarted,
  4091. {
  4092. attemptId: "stream-attempt-1",
  4093. anchorId: "anchor-1",
  4094. failedRequestId: "request-retry-1",
  4095. retryNumber: 3,
  4096. maxRetries: 10,
  4097. streamMode: "sse",
  4098. },
  4099. { turnId: "turn-retry-1" },
  4100. ),
  4101. );
  4102. projection.applyEvent(
  4103. log.push(
  4104. SessionEventType.ModelNetworkStatus,
  4105. modelStatus({
  4106. type: "model_request_started",
  4107. streamRecovery: {
  4108. attemptId: "stream-attempt-1",
  4109. anchorId: "anchor-1",
  4110. recoveredFromRequestId: "request-retry-1",
  4111. retryNumber: 3,
  4112. maxRetries: 10,
  4113. },
  4114. }),
  4115. { turnId: "turn-retry-1" },
  4116. ),
  4117. );
  4118. expect(projection.getSnapshot().control.apiRetry).toMatchObject({
  4119. attempt: 3,
  4120. maxAttempts: 11,
  4121. reasonCode: "fault.network.sseDisconnected",
  4122. });
  4123. projection.applyEvent(
  4124. log.push(
  4125. SessionEventType.ModelStreaming,
  4126. {
  4127. kind: "tool_input_start",
  4128. delta: "",
  4129. done: false,
  4130. toolCallId: "tool-retry-1",
  4131. toolName: "Read",
  4132. },
  4133. { turnId: "turn-retry-1" },
  4134. ),
  4135. );
  4136. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  4137. });
  4138. it("reasoning-only recovery 将旧思考行收口为 interrupted,再用新行承接恢复流", () => {
  4139. const { log, projection } = runningProjection();
  4140. projection.applyEvent(
  4141. log.push(
  4142. SessionEventType.ModelStreaming,
  4143. { kind: "reasoning_start", delta: "", done: false },
  4144. { turnId: "turn-retry-1" },
  4145. ),
  4146. );
  4147. projection.applyEvent(
  4148. log.push(
  4149. SessionEventType.ModelStreaming,
  4150. { kind: "reasoning_delta", delta: "unfinished", done: false },
  4151. { turnId: "turn-retry-1" },
  4152. ),
  4153. );
  4154. projection.applyEvent(
  4155. log.push(
  4156. SessionEventType.StreamRecoveryTailDiscarded,
  4157. {
  4158. attemptId: "stream-attempt-1",
  4159. anchorId: "anchor-1",
  4160. assistantMessageId: "assistant-retry-1",
  4161. discardedReasoningBytes: 10,
  4162. discardedTextBytes: 0,
  4163. discardedToolCallIds: [],
  4164. },
  4165. { turnId: "turn-retry-1" },
  4166. ),
  4167. );
  4168. expect(projection.getSnapshot().rows.window.filter((row) => row.kind === "reasoning")).toEqual([
  4169. expect.objectContaining({ state: "interrupted", text: "unfinished" }),
  4170. ]);
  4171. projection.applyEvent(
  4172. log.push(
  4173. SessionEventType.ModelStreaming,
  4174. { kind: "reasoning_delta", delta: "fresh", done: false },
  4175. { turnId: "turn-retry-1" },
  4176. ),
  4177. );
  4178. expect(
  4179. projection
  4180. .getSnapshot()
  4181. .rows.window.filter((row) => row.kind === "reasoning")
  4182. .map((row) => ({ state: row.state, text: row.text })),
  4183. ).toEqual([
  4184. { state: "interrupted", text: "unfinished" },
  4185. { state: "streaming", text: "fresh" },
  4186. ]);
  4187. });
  4188. it("tail_discarded 收口未定稿的流式 tool row,已提交的 running 行不动,恢复流用新 id 重开", () => {
  4189. const { log, projection } = runningProjection();
  4190. const turnId = "turn-retry-1";
  4191. // 已提交并在执行中的工具:它的终态由 executor 发布,recovery 不能替它收口。
  4192. projection.applyEvent(
  4193. log.push(
  4194. SessionEventType.ToolCallScheduled,
  4195. {
  4196. toolCallId: "tool-committed",
  4197. assistantMessageId: "assistant-retry-1",
  4198. toolName: "Read",
  4199. input: { file_path: "a.ts" },
  4200. schedule: { parallelGroups: [["tool-committed"]], executionOrder: ["tool-committed"] },
  4201. },
  4202. { turnId },
  4203. ),
  4204. );
  4205. projection.applyEvent(
  4206. log.push(
  4207. SessionEventType.ToolCallStarted,
  4208. { toolCallId: "tool-committed", toolName: "Read", startedAt: new Date() },
  4209. { turnId },
  4210. ),
  4211. );
  4212. // 断流时只写到一半的 CreateWorkflow:tool_input_start 已开行,tool_call 永远不会来。
  4213. projection.applyEvent(
  4214. log.push(
  4215. SessionEventType.ModelStreaming,
  4216. {
  4217. kind: "tool_input_start",
  4218. delta: "",
  4219. done: false,
  4220. toolCallId: "tool-orphan",
  4221. toolName: "CreateWorkflow",
  4222. },
  4223. { turnId },
  4224. ),
  4225. );
  4226. projection.applyEvent(
  4227. log.push(
  4228. SessionEventType.ModelStreaming,
  4229. {
  4230. kind: "tool_input_delta",
  4231. delta: '{"script":"const a = agent(',
  4232. done: false,
  4233. toolCallId: "tool-orphan",
  4234. },
  4235. { turnId },
  4236. ),
  4237. );
  4238. projection.applyEvent(
  4239. log.push(
  4240. SessionEventType.StreamRecoveryTailDiscarded,
  4241. {
  4242. attemptId: "stream-attempt-1",
  4243. anchorId: "anchor-1",
  4244. assistantMessageId: "assistant-retry-1",
  4245. discardedReasoningBytes: 0,
  4246. discardedTextBytes: 12,
  4247. discardedToolCallIds: [],
  4248. },
  4249. { turnId },
  4250. ),
  4251. );
  4252. const toolRows = () =>
  4253. projection
  4254. .getSnapshot()
  4255. .rows.window.filter((row) => row.kind === "toolCall")
  4256. .map((row) => ({
  4257. toolCallId: row.toolCallId,
  4258. status: row.status,
  4259. inputText: row.inputText,
  4260. }));
  4261. expect(toolRows()).toEqual([
  4262. { toolCallId: "tool-committed", status: "running", inputText: '{"file_path":"a.ts"}' },
  4263. { toolCallId: "tool-orphan", status: "cancelled", inputText: '{"script":"const a = agent(' },
  4264. ]);
  4265. // 恢复请求重新写脚本:新 id 开新行,旧行保持已收口,不会并排两张「正在编写工作流」。
  4266. projection.applyEvent(
  4267. log.push(
  4268. SessionEventType.ModelStreaming,
  4269. {
  4270. kind: "tool_input_start",
  4271. delta: "",
  4272. done: false,
  4273. toolCallId: "tool-retry",
  4274. toolName: "CreateWorkflow",
  4275. },
  4276. { turnId },
  4277. ),
  4278. );
  4279. expect(toolRows().map((row) => [row.toolCallId, row.status])).toEqual([
  4280. ["tool-committed", "running"],
  4281. ["tool-orphan", "cancelled"],
  4282. ["tool-retry", "inputStreaming"],
  4283. ]);
  4284. });
  4285. });
  4286. // ── 结构性黄金测试(13-golden-test-mapping §v4 新增)──
  4287. describe("结构性不变量", () => {
  4288. function fullDeltaStream(events: readonly SessionEvent[]): {
  4289. deltasPerEvent: ConversationDelta[][];
  4290. snapshots: ConversationSnapshot[];
  4291. } {
  4292. const { deltasPerEvent, snapshots } = runAll(events);
  4293. return { deltasPerEvent, snapshots };
  4294. }
  4295. it("结构性1:任意水位 W 取 snapshot + 续流 ≡ 全量重放(R-03)", () => {
  4296. const log = new EventLog();
  4297. basicTurnEvents(log);
  4298. const { deltasPerEvent, snapshots } = fullDeltaStream(log.events);
  4299. const final = snapshots[snapshots.length - 1]!;
  4300. for (let w = 0; w < log.events.length; w++) {
  4301. const snapshotAtW = snapshots[w + 1]!;
  4302. const tail = deltasPerEvent.slice(w + 1).flat();
  4303. const resumed = applyConversationDeltas(snapshotAtW, tail);
  4304. // seq 由帧区间记账推进(不在 delta 内),对比时对齐到终值。
  4305. expect({ ...resumed, seq: final.seq }).toEqual(final);
  4306. }
  4307. });
  4308. it("结构性4(半):coalesce 后的 delta 流与逐条投递终态逐字节一致", () => {
  4309. const log = new EventLog();
  4310. basicTurnEvents(log);
  4311. const { deltasPerEvent, snapshots } = fullDeltaStream(log.events);
  4312. const base = snapshots[0]!;
  4313. const all = deltasPerEvent.flat();
  4314. const direct = applyConversationDeltas(base, all);
  4315. const coalesced = applyConversationDeltas(base, coalesceConversationDeltas(all));
  4316. expect(coalesced).toEqual(direct);
  4317. });
  4318. it("结构性10:fault 注入 session A,session B 投影逐字节不变(X 组)", () => {
  4319. const logA = new EventLog("session-a");
  4320. logA.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4321. logA.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-a" });
  4322. const logB = new EventLog("session-b");
  4323. basicTurnEvents(logB, "turn-b");
  4324. const projectionA = new ProductProjection("session-a", "epoch-1");
  4325. const projectionB = new ProductProjection("session-b", "epoch-1");
  4326. for (const event of logB.events) projectionB.applyEvent(event);
  4327. const snapshotB = structuredClone(projectionB.getSnapshot());
  4328. for (const event of logA.events) projectionA.applyEvent(event);
  4329. const fault = new EventLog("session-a");
  4330. fault.push(
  4331. SessionEventType.TurnError,
  4332. { error: { type: "fault.network.unreachable", message: "ECONNREFUSED" }, turnPhase: "model" },
  4333. { turnId: "turn-a" },
  4334. );
  4335. for (const event of fault.events) projectionA.applyEvent(event);
  4336. expect(projectionA.getSnapshot().control.phase).toBe("error");
  4337. expect(projectionB.getSnapshot()).toEqual(snapshotB);
  4338. });
  4339. it("revision 递进:结构性事件 +1 且随帧携带;纯 row.delta 不递增(R-04)", () => {
  4340. const log = new EventLog();
  4341. basicTurnEvents(log);
  4342. const { deltasPerEvent, snapshots } = fullDeltaStream(log.events);
  4343. deltasPerEvent.forEach((deltas, index) => {
  4344. const structural = deltas.some(
  4345. (delta) =>
  4346. delta.op === "row.appended" ||
  4347. delta.op === "row.upserted" ||
  4348. delta.op === "row.removed" ||
  4349. (delta.op === "state.updated" &&
  4350. Object.keys(delta.patch).some((key) => key !== "revision" && key !== "usage")),
  4351. );
  4352. const prev = snapshots[index]!.revision;
  4353. const next = snapshots[index + 1]!.revision;
  4354. if (structural) {
  4355. expect(next).toBe(prev + 1);
  4356. // 携带规则:含 revision 递增事件的帧,deltas 必含 state.updated.revision。
  4357. const carried = deltas.some(
  4358. (delta) => delta.op === "state.updated" && delta.patch.revision === next,
  4359. );
  4360. expect(carried).toBe(true);
  4361. } else {
  4362. expect(next).toBe(prev);
  4363. }
  4364. });
  4365. // 纯文本流事件(text_delta)revision 不动。
  4366. const textDeltaIndex = log.events.findIndex(
  4367. (event) =>
  4368. event.type === SessionEventType.ModelStreaming &&
  4369. (event.payload as { kind?: string }).kind === "text_delta",
  4370. );
  4371. expect(snapshots[textDeltaIndex + 1]!.revision).toBe(snapshots[textDeltaIndex]!.revision);
  4372. });
  4373. it("确定性:同一事件日志重放两次,投影与 delta 流逐字节一致(rowId 纯函数,R-04)", () => {
  4374. const log = new EventLog();
  4375. basicTurnEvents(log);
  4376. const first = runAll(log.events);
  4377. const second = runAll(log.events);
  4378. expect(second.projection.getSnapshot()).toEqual(first.projection.getSnapshot());
  4379. expect(second.deltasPerEvent).toEqual(first.deltasPerEvent);
  4380. });
  4381. });
  4382. // ── 结构性4:两 profile 终态逐字节一致(05 §delivery-profile 收敛性黄金测试)──
  4383. // 同一事件序列跑 continuous / replayable 两档 flush 管线(filter → coalesce → apply),
  4384. // 断言终态与逐条直投逐字节一致。replayable 只是中间帧少,终态必须相同——
  4385. // 这同时机械验证收口不变量:被 profile 过滤的 row.delta(inputText/output.text/
  4386. // summaryText)必须被后续不可过滤的 row.upserted 蕴含。
  4387. describe("结构性4:两 profile 终态一致", () => {
  4388. function pipelineFinalState(
  4389. events: readonly SessionEvent[],
  4390. profile: DeliveryProfile,
  4391. ): ConversationSnapshot {
  4392. const { deltasPerEvent, snapshots } = runAll(events);
  4393. const base = snapshots[0]!;
  4394. const piped = coalesceConversationDeltas(
  4395. filterConversationDeltasForProfile(deltasPerEvent.flat(), profile),
  4396. );
  4397. return applyConversationDeltas(base, piped);
  4398. }
  4399. function assertProfileConvergence(events: readonly SessionEvent[]): void {
  4400. const { deltasPerEvent, snapshots } = runAll(events);
  4401. const direct = applyConversationDeltas(snapshots[0]!, deltasPerEvent.flat());
  4402. expect(pipelineFinalState(events, DELIVERY_PROFILES.continuous)).toEqual(direct);
  4403. expect(pipelineFinalState(events, DELIVERY_PROFILES.replayable)).toEqual(direct);
  4404. }
  4405. it("基础 turn(文本流式)", () => {
  4406. const log = new EventLog();
  4407. basicTurnEvents(log);
  4408. assertProfileConvergence(log.events);
  4409. });
  4410. it("tool 输入流式 → 权限 → 执行成功(inputText 被 upsert 收口)", () => {
  4411. const turnId = "turn-1";
  4412. const log = new EventLog();
  4413. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4414. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run ls" }, { turnId });
  4415. log.push(
  4416. SessionEventType.ModelStreaming,
  4417. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-1", toolName: "bash" },
  4418. { turnId },
  4419. );
  4420. log.push(
  4421. SessionEventType.ModelStreaming,
  4422. { kind: "tool_input_delta", delta: '{"command":', done: false, toolCallId: "tc-1" },
  4423. { turnId },
  4424. );
  4425. log.push(
  4426. SessionEventType.ModelStreaming,
  4427. { kind: "tool_input_delta", delta: '"ls"}', done: false, toolCallId: "tc-1" },
  4428. { turnId },
  4429. );
  4430. log.push(
  4431. SessionEventType.ToolCallScheduled,
  4432. {
  4433. toolCallId: "tc-1",
  4434. toolName: "bash",
  4435. input: { command: "ls" },
  4436. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  4437. },
  4438. { turnId },
  4439. );
  4440. log.push(
  4441. SessionEventType.PermissionRequested,
  4442. {
  4443. requestId: "req-1",
  4444. toolCallId: "tc-1",
  4445. toolName: "bash",
  4446. riskLevel: "medium",
  4447. reason: "Run",
  4448. input: { command: "ls" },
  4449. },
  4450. { turnId },
  4451. );
  4452. log.push(
  4453. SessionEventType.PermissionResolved,
  4454. { requestId: "req-1", toolCallId: "tc-1", decision: "allow" },
  4455. { turnId },
  4456. );
  4457. log.push(
  4458. SessionEventType.ToolCallStarted,
  4459. { toolCallId: "tc-1", toolName: "bash", startedAt: new Date() },
  4460. { turnId },
  4461. );
  4462. log.push(
  4463. SessionEventType.ToolCallResult,
  4464. { toolCallId: "tc-1", result: { success: true, content: "file-a" }, duration: 42 },
  4465. { turnId },
  4466. );
  4467. log.push(
  4468. SessionEventType.TurnComplete,
  4469. { response: "done", tokenCount: 1, toolCallCount: 1, duration: 100, resultType: "success" },
  4470. { turnId },
  4471. );
  4472. assertProfileConvergence(log.events);
  4473. });
  4474. it("BG13:foreground subagent child tool 只留在 child conversation,main 仍由父 Agent 保持 running", () => {
  4475. const turnId = "turn-foreground-agent";
  4476. const parentToolCallId = "call_parent_agent";
  4477. const childToolCallId = "tool_subagent_agent-1_call_child_todo";
  4478. const mirrored = {
  4479. agentId: "agent-1",
  4480. agentType: "general-purpose",
  4481. childSessionId: "session-child-1",
  4482. childToolCallId: "call_child_todo",
  4483. description: "Inspect the project",
  4484. parentToolCallId,
  4485. source: "subagent",
  4486. };
  4487. const log = new EventLog();
  4488. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4489. log.push(
  4490. SessionEventType.TurnStarted,
  4491. { turnNumber: 1, input: "inspect with a foreground agent" },
  4492. { turnId },
  4493. );
  4494. log.push(
  4495. SessionEventType.ToolCallScheduled,
  4496. {
  4497. toolCallId: parentToolCallId,
  4498. toolName: "Agent",
  4499. input: { description: "Inspect the project", prompt: "Inspect the project" },
  4500. schedule: {
  4501. parallelGroups: [[parentToolCallId]],
  4502. executionOrder: [parentToolCallId],
  4503. },
  4504. },
  4505. { turnId },
  4506. );
  4507. log.push(
  4508. SessionEventType.ToolCallStarted,
  4509. { toolCallId: parentToolCallId, toolName: "Agent", startedAt: new Date() },
  4510. { turnId },
  4511. );
  4512. log.push(
  4513. SessionEventType.SubagentSpawned,
  4514. {
  4515. agentId: "agent-1",
  4516. agentType: "general-purpose",
  4517. childSessionId: "session-child-1",
  4518. description: "Inspect the project",
  4519. parentToolCallId,
  4520. status: "running",
  4521. },
  4522. { turnId },
  4523. );
  4524. log.push(
  4525. SessionEventType.ToolCallScheduled,
  4526. {
  4527. ...mirrored,
  4528. toolCallId: childToolCallId,
  4529. toolName: "TodoWrite",
  4530. input: { todos: [{ id: "child-only", content: "Read files", status: "in_progress" }] },
  4531. schedule: {
  4532. parallelGroups: [[childToolCallId]],
  4533. executionOrder: [childToolCallId],
  4534. },
  4535. },
  4536. { turnId },
  4537. );
  4538. log.push(
  4539. SessionEventType.ToolCallStarted,
  4540. { ...mirrored, toolCallId: childToolCallId, toolName: "TodoWrite", startedAt: new Date() },
  4541. { turnId },
  4542. );
  4543. log.push(
  4544. SessionEventType.ToolCallResult,
  4545. {
  4546. ...mirrored,
  4547. toolCallId: childToolCallId,
  4548. result: { success: true, content: "child todo updated" },
  4549. duration: 10,
  4550. },
  4551. { turnId },
  4552. );
  4553. assertProfileConvergence(log.events);
  4554. const snapshot = runAll(log.events).projection.getSnapshot();
  4555. expect(snapshot.control.phase).toBe("running");
  4556. expect(snapshot.plan).toBeNull();
  4557. expect(
  4558. snapshot.rows.window.filter((row) => row.kind === "toolCall").map((row) => row.toolCallId),
  4559. ).toEqual([parentToolCallId]);
  4560. expect(snapshot.rows.window).toContainEqual(
  4561. expect.objectContaining({
  4562. kind: "subagent",
  4563. childSessionId: "session-child-1",
  4564. parentToolCallId,
  4565. status: "running",
  4566. }),
  4567. );
  4568. const childLog = new EventLog();
  4569. childLog.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4570. childLog.push(
  4571. SessionEventType.TurnStarted,
  4572. { turnNumber: 1, input: "Inspect the project" },
  4573. { turnId: "turn-child-1" },
  4574. );
  4575. childLog.push(
  4576. SessionEventType.ToolCallScheduled,
  4577. {
  4578. toolCallId: "call_child_todo",
  4579. toolName: "TodoWrite",
  4580. input: { todos: [{ id: "child-only", content: "Read files", status: "in_progress" }] },
  4581. schedule: {
  4582. parallelGroups: [["call_child_todo"]],
  4583. executionOrder: ["call_child_todo"],
  4584. },
  4585. },
  4586. { turnId: "turn-child-1" },
  4587. );
  4588. childLog.push(
  4589. SessionEventType.ToolCallStarted,
  4590. { toolCallId: "call_child_todo", toolName: "TodoWrite", startedAt: new Date() },
  4591. { turnId: "turn-child-1" },
  4592. );
  4593. childLog.push(
  4594. SessionEventType.ToolCallResult,
  4595. {
  4596. toolCallId: "call_child_todo",
  4597. result: { success: true, content: "child todo updated" },
  4598. duration: 10,
  4599. },
  4600. { turnId: "turn-child-1" },
  4601. );
  4602. assertProfileConvergence(childLog.events);
  4603. expect(runAll(childLog.events).projection.getSnapshot().rows.window).toContainEqual(
  4604. expect.objectContaining({
  4605. kind: "toolCall",
  4606. toolCallId: "call_child_todo",
  4607. status: "success",
  4608. }),
  4609. );
  4610. });
  4611. it("BG26:真实失败 lifecycle 归并 hydration 合成行并补齐 child session 身份", () => {
  4612. const turnId = "turn-background-agent-rate-limit";
  4613. const parentToolCallId = "call-background-agent-rate-limit";
  4614. const realAgentId = "agent-background-rate-limit";
  4615. const childSessionId = "session-child-rate-limit";
  4616. const log = new EventLog();
  4617. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4618. log.push(
  4619. SessionEventType.TurnStarted,
  4620. { turnNumber: 1, input: "launch background agent" },
  4621. { turnId },
  4622. );
  4623. log.push(
  4624. SessionEventType.ToolCallScheduled,
  4625. {
  4626. toolCallId: parentToolCallId,
  4627. toolName: "Agent",
  4628. input: {
  4629. description: "Trigger provider rate limit",
  4630. prompt: "Trigger provider rate limit",
  4631. run_in_background: true,
  4632. },
  4633. schedule: {
  4634. parallelGroups: [[parentToolCallId]],
  4635. executionOrder: [parentToolCallId],
  4636. },
  4637. },
  4638. { turnId },
  4639. );
  4640. log.push(
  4641. SessionEventType.ToolCallStarted,
  4642. { toolCallId: parentToolCallId, toolName: "Agent", startedAt: new Date() },
  4643. { turnId },
  4644. );
  4645. // transcript hydration 只能从文本 tool output 合成出 toolCallId 身份,拿不到 childSessionId。
  4646. log.push(
  4647. SessionEventType.SubagentSpawned,
  4648. {
  4649. agentId: parentToolCallId,
  4650. agentType: "general-purpose",
  4651. description: "Trigger provider rate limit",
  4652. parentToolCallId,
  4653. status: "running",
  4654. },
  4655. { turnId },
  4656. );
  4657. // hydration await 窗口内补回的真实 spawned 也必须复用合成行,并建立真实 agentId 映射。
  4658. log.push(
  4659. SessionEventType.SubagentSpawned,
  4660. {
  4661. agentId: realAgentId,
  4662. agentType: "general-purpose",
  4663. background: true,
  4664. childSessionId,
  4665. description: "Trigger provider rate limit",
  4666. parentToolCallId,
  4667. status: "running",
  4668. },
  4669. { turnId },
  4670. );
  4671. // live terminal 事件携带真实 runtime 身份,必须更新上一行而不是追加重复 SubagentRow。
  4672. log.push(
  4673. SessionEventType.SubagentStopped,
  4674. {
  4675. agentId: realAgentId,
  4676. agentType: "general-purpose",
  4677. background: true,
  4678. parentToolCallId,
  4679. status: "failed",
  4680. error: "PROVIDER_ERROR: 429 rate limited",
  4681. },
  4682. { turnId },
  4683. );
  4684. const snapshot = runAll(log.events).projection.getSnapshot();
  4685. const subagentRows = snapshot.rows.window.filter(
  4686. (row): row is Extract<(typeof snapshot.rows.window)[number], { kind: "subagent" }> =>
  4687. row.kind === "subagent",
  4688. );
  4689. expect(subagentRows).toHaveLength(1);
  4690. expect(subagentRows[0]).toMatchObject({
  4691. childSessionId,
  4692. parentToolCallId,
  4693. status: "failed",
  4694. summaryText: "PROVIDER_ERROR: 429 rate limited",
  4695. });
  4696. });
  4697. it("BG35:background subagent child tool 不生成父 row,迟到终态也不复活", () => {
  4698. const turnId = "turn-background-agent";
  4699. const parentToolCallId = "call_parent_agent";
  4700. const childToolCallId = "tool_subagent_agent-1_call_child_bash";
  4701. const mirrored = {
  4702. agentId: "agent-1",
  4703. agentType: "general-purpose",
  4704. background: true,
  4705. childSessionId: "session-child-1",
  4706. childToolCallId: "call_child_bash",
  4707. description: "Run delayed Bash",
  4708. parentToolCallId,
  4709. source: "subagent",
  4710. };
  4711. const log = new EventLog();
  4712. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4713. log.push(
  4714. SessionEventType.TurnStarted,
  4715. { turnNumber: 1, input: "launch background agent" },
  4716. { turnId },
  4717. );
  4718. log.push(
  4719. SessionEventType.ToolCallScheduled,
  4720. {
  4721. toolCallId: parentToolCallId,
  4722. toolName: "Agent",
  4723. input: {
  4724. description: "Run delayed Bash",
  4725. prompt: "Run delayed Bash",
  4726. run_in_background: true,
  4727. },
  4728. schedule: {
  4729. parallelGroups: [[parentToolCallId]],
  4730. executionOrder: [parentToolCallId],
  4731. },
  4732. },
  4733. { turnId },
  4734. );
  4735. log.push(
  4736. SessionEventType.ToolCallStarted,
  4737. { toolCallId: parentToolCallId, toolName: "Agent", startedAt: new Date() },
  4738. { turnId },
  4739. );
  4740. log.push(
  4741. SessionEventType.ToolCallResult,
  4742. {
  4743. toolCallId: parentToolCallId,
  4744. result: { success: true, content: "background agent launched" },
  4745. duration: 5,
  4746. },
  4747. { turnId },
  4748. );
  4749. log.push(
  4750. SessionEventType.ToolCallScheduled,
  4751. {
  4752. ...mirrored,
  4753. toolCallId: childToolCallId,
  4754. toolName: "Bash",
  4755. input: { command: "sleep 60 && date" },
  4756. schedule: {
  4757. parallelGroups: [[childToolCallId]],
  4758. executionOrder: [childToolCallId],
  4759. },
  4760. },
  4761. { turnId },
  4762. );
  4763. log.push(
  4764. SessionEventType.ToolCallStarted,
  4765. { ...mirrored, toolCallId: childToolCallId, toolName: "Bash", startedAt: new Date() },
  4766. { turnId },
  4767. );
  4768. log.push(
  4769. SessionEventType.TurnComplete,
  4770. {
  4771. response: "launched",
  4772. tokenCount: 1,
  4773. toolCallCount: 1,
  4774. duration: 10,
  4775. resultType: "success",
  4776. },
  4777. { turnId },
  4778. );
  4779. const beforeChildTerminal = runAll(log.events).projection.getSnapshot();
  4780. expect(beforeChildTerminal.control.phase).toBe("completedSuccess");
  4781. expect(
  4782. beforeChildTerminal.rows.window
  4783. .filter((row) => row.kind === "toolCall")
  4784. .map((row) => row.toolCallId),
  4785. ).toEqual([parentToolCallId]);
  4786. log.push(
  4787. SessionEventType.ToolCallResult,
  4788. {
  4789. ...mirrored,
  4790. toolCallId: childToolCallId,
  4791. result: { success: true, content: "Fri Jul 17 12:40:36 CST 2026" },
  4792. duration: 60_000,
  4793. },
  4794. { turnId },
  4795. );
  4796. log.push(
  4797. SessionEventType.ToolCallError,
  4798. {
  4799. ...mirrored,
  4800. toolCallId: "tool_subagent_agent-1_call_child_error",
  4801. error: { type: "fault.runtime.toolFailed", message: "late child failure" },
  4802. },
  4803. { turnId },
  4804. );
  4805. assertProfileConvergence(log.events);
  4806. const terminalSnapshot = runAll(log.events).projection.getSnapshot();
  4807. expect(terminalSnapshot.control.phase).toBe("completedSuccess");
  4808. expect(
  4809. terminalSnapshot.rows.window
  4810. .filter((row) => row.kind === "toolCall")
  4811. .map((row) => row.toolCallId),
  4812. ).toEqual([parentToolCallId]);
  4813. });
  4814. it("BG18:父轮结束后的 child tool 事件不应清掉原 background Agent 控制身份", () => {
  4815. const parentTurnId = "turn-background-parent-anchor";
  4816. const followUpTurnId = "turn-background-parent-anchor-follow-up";
  4817. const parentToolCallId = "toolu_e2e_background_parent_anchor_agent";
  4818. const agentId = "agent-parent-anchor";
  4819. const childSessionId = "session-child-parent-anchor";
  4820. const log = new EventLog();
  4821. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4822. log.push(
  4823. SessionEventType.TurnStarted,
  4824. { turnNumber: 1, input: "launch background agent" },
  4825. { turnId: parentTurnId },
  4826. );
  4827. log.push(
  4828. SessionEventType.SubagentSpawned,
  4829. {
  4830. agentId,
  4831. agentType: "general-purpose",
  4832. background: true,
  4833. childSessionId,
  4834. description: "E2E background child tool parent anchor",
  4835. parentToolCallId,
  4836. status: "running",
  4837. },
  4838. { turnId: parentTurnId },
  4839. );
  4840. log.push(SessionEventType.TurnComplete, {}, { turnId: parentTurnId });
  4841. log.push(
  4842. SessionEventType.TurnStarted,
  4843. { turnNumber: 2, input: "finish a main follow-up first" },
  4844. { turnId: followUpTurnId },
  4845. );
  4846. log.push(SessionEventType.TurnComplete, {}, { turnId: followUpTurnId });
  4847. log.push(
  4848. SessionEventType.ToolCallStarted,
  4849. {
  4850. agentId,
  4851. childSessionId,
  4852. parentToolCallId,
  4853. source: "subagent",
  4854. toolCallId: "toolu_e2e_background_parent_anchor_child_bash",
  4855. toolName: "Bash",
  4856. },
  4857. { turnId: parentTurnId },
  4858. );
  4859. const snapshot = runAll(log.events).projection.getSnapshot();
  4860. expect(snapshot.subagents.running).toEqual([
  4861. expect.objectContaining({
  4862. agentId,
  4863. childSessionId,
  4864. title: "E2E background child tool parent anchor",
  4865. }),
  4866. ]);
  4867. });
  4868. it("tool 输入流到一半被 stop(cancelled 收口,inputStreaming 不悬挂)", () => {
  4869. const turnId = "turn-1";
  4870. const log = new EventLog();
  4871. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4872. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  4873. log.push(
  4874. SessionEventType.ModelStreaming,
  4875. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-1", toolName: "bash" },
  4876. { turnId },
  4877. );
  4878. log.push(
  4879. SessionEventType.ModelStreaming,
  4880. { kind: "tool_input_delta", delta: '{"command":"rm', done: false, toolCallId: "tc-1" },
  4881. { turnId },
  4882. );
  4883. log.push(
  4884. SessionEventType.TurnComplete,
  4885. { response: "", tokenCount: 0, toolCallCount: 0, duration: 50, resultType: "cancelled" },
  4886. { turnId },
  4887. );
  4888. assertProfileConvergence(log.events);
  4889. // 收口语义本体:中断后 tool row 必须离开 inputStreaming(cancelled + 完整 inputText)。
  4890. const { projection } = runAll(log.events);
  4891. expect(
  4892. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  4893. ).toMatchObject({ status: "cancelled", inputText: '{"command":"rm' });
  4894. });
  4895. it("success turn 兜底收口缺少 terminal event 的 foreground tool", () => {
  4896. const turnId = "turn-1";
  4897. const log = new EventLog();
  4898. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4899. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "search" }, { turnId });
  4900. log.push(
  4901. SessionEventType.ModelStreaming,
  4902. {
  4903. kind: "tool_input_start",
  4904. delta: "",
  4905. done: false,
  4906. toolCallId: "tc-missing",
  4907. toolName: "GrepMissingFromRegistry",
  4908. },
  4909. { turnId },
  4910. );
  4911. log.push(
  4912. SessionEventType.ModelStreaming,
  4913. {
  4914. kind: "tool_input_delta",
  4915. delta: '{"pattern":"needle"}',
  4916. done: false,
  4917. toolCallId: "tc-missing",
  4918. },
  4919. { turnId },
  4920. );
  4921. log.push(
  4922. SessionEventType.PermissionRequested,
  4923. {
  4924. requestId: "req-missing",
  4925. toolCallId: "tc-missing",
  4926. toolName: "GrepMissingFromRegistry",
  4927. riskLevel: "low",
  4928. reason: "Search",
  4929. input: { pattern: "needle" },
  4930. },
  4931. { turnId },
  4932. );
  4933. log.push(
  4934. SessionEventType.TurnComplete,
  4935. { response: "done", tokenCount: 1, toolCallCount: 1, duration: 50, resultType: "success" },
  4936. { turnId },
  4937. );
  4938. assertProfileConvergence(log.events);
  4939. const { projection } = runAll(log.events);
  4940. expect(
  4941. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  4942. ).toMatchObject({
  4943. status: "error",
  4944. inputText: '{"pattern":"needle"}',
  4945. error: { code: "fault.runtime.toolLifecycleIncomplete" },
  4946. });
  4947. expect(projection.getSnapshot().pendingInteractions).toEqual([]);
  4948. });
  4949. it("reasoning 流式 + 中断", () => {
  4950. const turnId = "turn-1";
  4951. const log = new EventLog();
  4952. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4953. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "think" }, { turnId });
  4954. log.push(
  4955. SessionEventType.ModelStreaming,
  4956. { kind: "reasoning_start", delta: "", done: false },
  4957. { turnId },
  4958. );
  4959. log.push(
  4960. SessionEventType.ModelStreaming,
  4961. { kind: "reasoning_delta", delta: "hmm...", done: false },
  4962. { turnId },
  4963. );
  4964. log.push(
  4965. SessionEventType.ModelStreaming,
  4966. { kind: "text_start", delta: "", done: false },
  4967. { turnId },
  4968. );
  4969. log.push(
  4970. SessionEventType.ModelStreaming,
  4971. { kind: "text_delta", delta: "part", done: false },
  4972. { turnId },
  4973. );
  4974. log.push(
  4975. SessionEventType.TurnComplete,
  4976. { response: "", tokenCount: 0, toolCallCount: 0, duration: 10, resultType: "cancelled" },
  4977. { turnId },
  4978. );
  4979. assertProfileConvergence(log.events);
  4980. });
  4981. it("compact 生命周期(marker + usage 回落)", () => {
  4982. const log = new EventLog();
  4983. basicTurnEvents(log);
  4984. log.push(SessionEventType.CompactStarted, {
  4985. operationId: "op-1",
  4986. messageId: "msg-1",
  4987. status: "started",
  4988. trigger: "manual",
  4989. display: "separator",
  4990. sourceCommandId: "command-compact",
  4991. });
  4992. log.push(SessionEventType.CompactCompleted, {
  4993. operationId: "op-1",
  4994. messageId: "msg-1",
  4995. status: "completed",
  4996. trigger: "manual",
  4997. display: "separator",
  4998. preCompactTokenCount: 150,
  4999. postCompactTokenCount: 50,
  5000. });
  5001. assertProfileConvergence(log.events);
  5002. });
  5003. it("goal set → verify pass → fork → modelChange 全链路", () => {
  5004. const log = new EventLog();
  5005. basicTurnEvents(log);
  5006. log.push(SessionEventType.TargetChanged, {
  5007. action: "set",
  5008. source: "command",
  5009. target: {
  5010. sessionID: "session-1",
  5011. targetID: "target-1",
  5012. objective: "修绿",
  5013. summaryTitle: null,
  5014. status: "active",
  5015. tokenBudget: null,
  5016. tokensUsed: 0,
  5017. timeUsedSeconds: 0,
  5018. time: { created: 0, updated: 0 },
  5019. },
  5020. previousTarget: null,
  5021. });
  5022. log.push(SessionEventType.TargetCompletionVerification, {
  5023. targetId: "target-1",
  5024. status: "started",
  5025. verificationId: "verify-1",
  5026. goalIteration: 1,
  5027. });
  5028. log.push(SessionEventType.TargetCompletionVerification, {
  5029. targetId: "target-1",
  5030. status: "completed",
  5031. verificationId: "verify-1",
  5032. goalIteration: 1,
  5033. verification: { passed: true, reason: "ok" },
  5034. });
  5035. log.push(SessionEventType.SessionForked, {
  5036. originalSessionId: "session-1",
  5037. forkedSessionId: "session-child",
  5038. });
  5039. log.push(SessionEventType.ModelSelected, {
  5040. modelSelection: { providerId: "anthropic", modelId: "claude-4" },
  5041. });
  5042. log.push(SessionEventType.ModelSelected, {
  5043. modelSelection: { providerId: "openai", modelId: "gpt-6" },
  5044. });
  5045. assertProfileConvergence(log.events);
  5046. });
  5047. });
  5048. // ── G 组:compact marker ──
  5049. describe("compact marker(10 §4.4.7 / §6.4)", () => {
  5050. it("G:manual compact running→success —— 同一 marker row 状态迁移 + usage 回落", () => {
  5051. const log = new EventLog();
  5052. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  5053. log.push(SessionEventType.CompactStarted, {
  5054. operationId: "op-1",
  5055. messageId: "msg-marker",
  5056. status: "started",
  5057. trigger: "manual",
  5058. display: "separator",
  5059. sourceCommandId: "command-compact",
  5060. });
  5061. const { projection, deltasPerEvent } = runAll(log.events);
  5062. const runningMarker = projection
  5063. .getSnapshot()
  5064. .rows.window.find((row) => row.kind === "timelineMarker");
  5065. expect(runningMarker).toMatchObject({
  5066. sourceCommandId: "command-compact",
  5067. marker: { type: "compact", origin: "manual", status: "running" },
  5068. });
  5069. expect(deltasPerEvent[1]![0]!.op).toBe("row.appended");
  5070. projection.applyEvent(
  5071. new EventLog().push(SessionEventType.CompactCompleted, {
  5072. operationId: "op-1",
  5073. messageId: "msg-marker",
  5074. status: "completed",
  5075. trigger: "manual",
  5076. display: "separator",
  5077. sourceCommandId: "command-compact",
  5078. preCompactTokenCount: 100_000,
  5079. postCompactTokenCount: 30_000,
  5080. truePostCompactTokenCount: 20_000,
  5081. summaryMessageId: "msg-summary",
  5082. }),
  5083. );
  5084. const snapshot = projection.getSnapshot();
  5085. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  5086. const markers = snapshot.rows.window.filter((row) => row.kind === "timelineMarker");
  5087. // 全生命周期占同一行:终态是 upsert 不是新行。
  5088. expect(markers).toHaveLength(1);
  5089. expect(markers[0]).toMatchObject({
  5090. rowId: runningMarker?.rowId,
  5091. sourceCommandId: "command-compact",
  5092. marker: {
  5093. type: "compact",
  5094. origin: "manual",
  5095. status: "success",
  5096. tokensBefore: 100_000,
  5097. tokensAfter: 20_000,
  5098. summaryRef: "msg-summary",
  5099. },
  5100. });
  5101. // compact 成功 → context 水位立即回落(§6.4)。
  5102. expect(snapshot.usage.contextWindow?.usedTokens).toBe(20_000);
  5103. });
  5104. it("G12:auto compact 被 stop —— marker=cancelled,usage 不动", () => {
  5105. const log = new EventLog();
  5106. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5107. log.push(SessionEventType.CompactStarted, {
  5108. operationId: "op-1",
  5109. messageId: "msg-1",
  5110. status: "started",
  5111. trigger: "auto",
  5112. display: "separator",
  5113. });
  5114. log.push(SessionEventType.CompactFailed, {
  5115. operationId: "op-1",
  5116. messageId: "msg-1",
  5117. status: "interrupted",
  5118. trigger: "auto",
  5119. display: "separator",
  5120. });
  5121. const { projection } = runAll(log.events);
  5122. const snapshot = projection.getSnapshot();
  5123. expect(snapshot.rows.window.find((row) => row.kind === "timelineMarker")).toMatchObject({
  5124. marker: { type: "compact", origin: "auto", status: "cancelled" },
  5125. });
  5126. expect(snapshot.usage.contextWindow).toBeNull();
  5127. });
  5128. it("F09:compact 失败 —— marker=failed(retry 入口),会话状态不受污染", () => {
  5129. const log = new EventLog();
  5130. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5131. log.push(SessionEventType.CompactStarted, {
  5132. operationId: "op-1",
  5133. messageId: "msg-1",
  5134. status: "started",
  5135. trigger: "manual",
  5136. display: "separator",
  5137. });
  5138. log.push(SessionEventType.CompactFailed, {
  5139. operationId: "op-1",
  5140. messageId: "msg-1",
  5141. status: "failed",
  5142. trigger: "manual",
  5143. display: "separator",
  5144. reason: "api_error",
  5145. });
  5146. const { projection } = runAll(log.events);
  5147. const snapshot = projection.getSnapshot();
  5148. expect(snapshot.rows.window.find((row) => row.kind === "timelineMarker")).toMatchObject({
  5149. marker: { type: "compact", status: "failed" },
  5150. });
  5151. expect(snapshot.control.lastError).toBeNull();
  5152. });
  5153. });
  5154. // ── goal 状态机(10 §4.2.8)──
  5155. describe("goal 状态机", () => {
  5156. const goalTarget = (status: string, objective = "把测试全修绿") => ({
  5157. sessionID: "session-1",
  5158. targetID: "target-1",
  5159. objective,
  5160. summaryTitle: null,
  5161. status,
  5162. tokenBudget: null,
  5163. tokensUsed: 0,
  5164. timeUsedSeconds: 0,
  5165. time: { created: 0, updated: 0 },
  5166. });
  5167. it("goal set → stateOnly(不产 row)+ GoalState.active;verify pass → verified + 摘要锚点", () => {
  5168. const log = new EventLog();
  5169. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5170. log.push(SessionEventType.TargetChanged, {
  5171. action: "set",
  5172. source: "command",
  5173. target: goalTarget("active"),
  5174. previousTarget: null,
  5175. });
  5176. log.push(SessionEventType.TargetCompletionVerification, {
  5177. targetId: "target-1",
  5178. status: "started",
  5179. verificationId: "verify-1",
  5180. foregroundExecutionId: "foreground-1",
  5181. goalIteration: 1,
  5182. });
  5183. const { projection } = runAll(log.events);
  5184. const verifying = projection.getSnapshot();
  5185. expect(verifying.goal).toMatchObject({
  5186. objective: "把测试全修绿",
  5187. status: "verifying",
  5188. iteration: 1,
  5189. });
  5190. expect(verifying.control).toMatchObject({
  5191. phase: "running",
  5192. canStop: true,
  5193. stopState: "stoppable",
  5194. stopTargetKind: "goalVerifier",
  5195. sessionEnded: false,
  5196. });
  5197. expect(verifying.control.activeWorks).toEqual([
  5198. expect.objectContaining({
  5199. kind: "goalVerifier",
  5200. foregroundExecutionId: "foreground-1",
  5201. }),
  5202. ]);
  5203. expect(verifying.inputRouting).toEqual({
  5204. mode: "enqueue",
  5205. reasonCode: "goalVerifierAcceptsFutureInput",
  5206. });
  5207. const verifyMarker = verifying.rows.window.find(
  5208. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  5209. );
  5210. expect(verifyMarker).toMatchObject({
  5211. marker: { type: "goalVerify", iteration: 1, outcome: "running" },
  5212. });
  5213. // S10(16-plan,2026-07-08 裁决):goalSet 是 stateOnly——不进 rows.window
  5214. //(旧实现产「渲染 null」的隐形行,污染 turn 分组),目标由 goal 面板承载。
  5215. expect(
  5216. verifying.rows.window.find(
  5217. (row) => row.kind === "timelineMarker" && row.marker.type === "goalSet",
  5218. ),
  5219. ).toBeUndefined();
  5220. projection.applyEvent(
  5221. new EventLog().push(SessionEventType.TargetCompletionVerification, {
  5222. targetId: "target-1",
  5223. status: "completed",
  5224. verificationId: "verify-1",
  5225. goalIteration: 1,
  5226. verification: { passed: true, reason: "全部通过" },
  5227. }),
  5228. );
  5229. const done = projection.getSnapshot();
  5230. expect(() => conversationSnapshotSchema.parse(done)).not.toThrow();
  5231. expect(done.goal).toMatchObject({ status: "verified", iteration: 1 });
  5232. expect(done.control).toMatchObject({
  5233. phase: "completedSuccess",
  5234. canStop: false,
  5235. stopState: "idle",
  5236. stopTargetKind: "unknown",
  5237. sessionEnded: true,
  5238. });
  5239. expect(done.control.activeWorks).toEqual([]);
  5240. expect(done.goal?.verifications).toEqual([
  5241. expect.objectContaining({
  5242. iteration: 1,
  5243. outcome: "pass",
  5244. anchorRowId: verifyMarker?.rowId,
  5245. }),
  5246. ]);
  5247. // marker 就地终态化(同 rowId)。
  5248. expect(
  5249. done.rows.window.find(
  5250. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  5251. ),
  5252. ).toMatchObject({
  5253. rowId: verifyMarker?.rowId,
  5254. marker: { outcome: "pass", detail: "全部通过" },
  5255. });
  5256. });
  5257. it("goal verifier 被 Stop 时暂停已有 future queue", () => {
  5258. const log = new EventLog();
  5259. log.push(SessionEventType.SessionCreated, {
  5260. mode: "default",
  5261. contextWindow: 1000,
  5262. });
  5263. log.push(SessionEventType.TargetChanged, {
  5264. action: "set",
  5265. source: "command",
  5266. target: goalTarget("active"),
  5267. previousTarget: null,
  5268. });
  5269. log.push(SessionEventType.TargetCompletionVerification, {
  5270. targetId: "target-1",
  5271. status: "started",
  5272. verificationId: "verify-stop",
  5273. foregroundExecutionId: "foreground-stop",
  5274. goalIteration: 1,
  5275. });
  5276. log.push(SessionEventType.TurnSteerQueued, {
  5277. pendingInputId: "queue-after-verifier",
  5278. inputId: "command-after-verifier",
  5279. input: "verifier 后继续的问题",
  5280. inputPreview: "verifier 后继续的问题",
  5281. inputSize: 13,
  5282. targetTurnId: "turn-goal",
  5283. queueLength: 1,
  5284. delivery: "queue",
  5285. });
  5286. log.push(SessionEventType.TargetCompletionVerification, {
  5287. targetId: "target-1",
  5288. status: "cancelled",
  5289. verificationId: "verify-stop",
  5290. foregroundExecutionId: "foreground-stop",
  5291. goalIteration: 1,
  5292. });
  5293. const { projection } = runAll(log.events);
  5294. const snapshot = projection.getSnapshot();
  5295. expect(snapshot.goal?.status).toBe("paused");
  5296. expect(snapshot.queue).toMatchObject({
  5297. autoDrain: false,
  5298. pauseReason: "stopped",
  5299. items: [expect.objectContaining({ queueItemId: "queue-after-verifier" })],
  5300. });
  5301. expect(snapshot.inputRouting).toEqual({
  5302. mode: "choice",
  5303. reasonCode: "heldQueueInputRequiresChoice",
  5304. });
  5305. });
  5306. it("M07j:sendQueuedNow 抢占 goal verifier 时不暂停 future queue", () => {
  5307. const log = new EventLog();
  5308. log.push(SessionEventType.SessionCreated, {
  5309. mode: "default",
  5310. contextWindow: 1000,
  5311. });
  5312. log.push(SessionEventType.TargetChanged, {
  5313. action: "set",
  5314. source: "command",
  5315. target: goalTarget("active"),
  5316. previousTarget: null,
  5317. });
  5318. log.push(SessionEventType.TargetCompletionVerification, {
  5319. targetId: "target-1",
  5320. status: "started",
  5321. verificationId: "verify-send-now",
  5322. foregroundExecutionId: "foreground-send-now",
  5323. goalIteration: 1,
  5324. });
  5325. log.push(SessionEventType.TurnSteerQueued, {
  5326. pendingInputId: "queue-send-now",
  5327. inputId: "command-send-now",
  5328. input: "立即发送的问题",
  5329. inputPreview: "立即发送的问题",
  5330. inputSize: 21,
  5331. targetTurnId: "turn-goal",
  5332. queueLength: 1,
  5333. delivery: "queue",
  5334. });
  5335. log.push(SessionEventType.TargetCompletionVerification, {
  5336. targetId: "target-1",
  5337. status: "cancelled",
  5338. verificationId: "verify-send-now",
  5339. foregroundExecutionId: "foreground-send-now",
  5340. preserveQueueAutoDrainOnCancel: true,
  5341. goalIteration: 1,
  5342. });
  5343. const { projection } = runAll(log.events);
  5344. const snapshot = projection.getSnapshot();
  5345. expect(snapshot.goal?.status).toBe("paused");
  5346. expect(snapshot.queue).toMatchObject({
  5347. autoDrain: true,
  5348. items: [expect.objectContaining({ queueItemId: "queue-send-now" })],
  5349. });
  5350. expect(snapshot.queue.pauseReason).toBeUndefined();
  5351. expect(snapshot.inputRouting.mode).toBe("startNow");
  5352. });
  5353. it("verify notSatisfied —— 有效结论与过程失败分离(goalVerificationOutcomeSeparation)", () => {
  5354. const log = new EventLog();
  5355. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5356. log.push(SessionEventType.TargetChanged, {
  5357. action: "set",
  5358. source: "command",
  5359. target: goalTarget("active"),
  5360. });
  5361. log.push(SessionEventType.TargetCompletionVerification, {
  5362. targetId: "target-1",
  5363. status: "started",
  5364. verificationId: "verify-1",
  5365. goalIteration: 1,
  5366. });
  5367. log.push(SessionEventType.TargetCompletionVerification, {
  5368. targetId: "target-1",
  5369. status: "completed",
  5370. verificationId: "verify-1",
  5371. goalIteration: 1,
  5372. verification: { passed: false, reason: "还有 2 个用例红" },
  5373. });
  5374. const { projection } = runAll(log.events);
  5375. expect(projection.getSnapshot().goal).toMatchObject({ status: "notSatisfied" });
  5376. expect(projection.getSnapshot().goal?.verifications[0]).toMatchObject({
  5377. outcome: "notSatisfied",
  5378. });
  5379. });
  5380. it("H13-H16:投影 target 计时/标题、verifier action 与逐轮 Todo 状态", () => {
  5381. const log = new EventLog();
  5382. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5383. log.push(SessionEventType.TargetChanged, {
  5384. action: "set",
  5385. source: "command",
  5386. target: {
  5387. ...goalTarget("active"),
  5388. summaryTitle: "第一轮:恢复摘要",
  5389. timeUsedSeconds: 7,
  5390. activeRunStartedAtMs: 1_700_000_001_000,
  5391. },
  5392. });
  5393. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "first" }, { turnId: "turn-1" });
  5394. log.push(
  5395. SessionEventType.ToolCallScheduled,
  5396. {
  5397. toolCallId: "todo-1",
  5398. toolName: "TodoWrite",
  5399. input: {
  5400. todos: [{ content: "恢复计时", status: "completed", priority: "high" }],
  5401. },
  5402. schedule: { parallelGroups: [["todo-1"]], executionOrder: ["todo-1"] },
  5403. },
  5404. { turnId: "turn-1" },
  5405. );
  5406. log.push(
  5407. SessionEventType.TurnComplete,
  5408. { response: "done", tokenCount: 1, toolCallCount: 1, duration: 1, resultType: "success" },
  5409. { turnId: "turn-1" },
  5410. );
  5411. log.push(SessionEventType.TargetCompletionVerification, {
  5412. targetId: "target-1",
  5413. status: "started",
  5414. verificationId: "verify-1",
  5415. goalIteration: 1,
  5416. });
  5417. log.push(SessionEventType.TargetCompletionVerification, {
  5418. targetId: "target-1",
  5419. status: "completed",
  5420. verificationId: "verify-1",
  5421. goalIteration: 1,
  5422. verification: {
  5423. passed: false,
  5424. reason: "还缺暂停状态",
  5425. nextAction: "第二轮:补暂停和完成态",
  5426. },
  5427. });
  5428. log.push(SessionEventType.TargetChanged, {
  5429. action: "run_started",
  5430. source: "runtime",
  5431. target: {
  5432. ...goalTarget("active"),
  5433. summaryTitle: "第一轮:恢复摘要",
  5434. timeUsedSeconds: 11,
  5435. activeRunStartedAtMs: 1_700_000_009_000,
  5436. },
  5437. });
  5438. log.push(
  5439. SessionEventType.TurnStarted,
  5440. { turnNumber: 2, input: "second" },
  5441. { turnId: "turn-2" },
  5442. );
  5443. log.push(
  5444. SessionEventType.ToolCallScheduled,
  5445. {
  5446. toolCallId: "todo-2",
  5447. toolName: "todo_write",
  5448. input: {
  5449. todos: [
  5450. { content: "恢复暂停按钮", status: "in_progress", priority: "high" },
  5451. { content: "恢复完成图标", status: "pending", priority: "medium" },
  5452. ],
  5453. },
  5454. schedule: { parallelGroups: [["todo-2"]], executionOrder: ["todo-2"] },
  5455. },
  5456. { turnId: "turn-2" },
  5457. );
  5458. const { projection } = runAll(log.events);
  5459. const snapshot = projection.getSnapshot();
  5460. expect(snapshot.goal).toMatchObject({
  5461. targetId: "target-1",
  5462. summaryTitle: "第一轮:恢复摘要",
  5463. timeUsedSeconds: 11,
  5464. activeRunStartedAtMs: 1_700_000_009_000,
  5465. status: "active",
  5466. iteration: 1,
  5467. verifications: [
  5468. expect.objectContaining({
  5469. iteration: 1,
  5470. outcome: "notSatisfied",
  5471. reason: "还缺暂停状态",
  5472. nextAction: "第二轮:补暂停和完成态",
  5473. }),
  5474. ],
  5475. iterations: [
  5476. expect.objectContaining({
  5477. iteration: 1,
  5478. items: [expect.objectContaining({ content: "恢复计时", status: "completed" })],
  5479. }),
  5480. expect.objectContaining({
  5481. iteration: 2,
  5482. items: [
  5483. expect.objectContaining({ content: "恢复暂停按钮", status: "inProgress" }),
  5484. expect.objectContaining({ content: "恢复完成图标", status: "pending" }),
  5485. ],
  5486. }),
  5487. ],
  5488. });
  5489. expect(snapshot.plan?.items).toHaveLength(2);
  5490. expect(snapshot.availability.pauseGoal).toEqual({ allowed: true });
  5491. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  5492. });
  5493. it("stopPausesActiveGoalTarget:stop(cancelled turn)把 active goal 压成 paused,resumeGoal 放行", () => {
  5494. const log = new EventLog();
  5495. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5496. log.push(SessionEventType.TargetChanged, {
  5497. action: "set",
  5498. source: "command",
  5499. target: goalTarget("active"),
  5500. });
  5501. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "go" }, { turnId: "turn-1" });
  5502. log.push(
  5503. SessionEventType.TurnComplete,
  5504. { response: "", tokenCount: 0, toolCallCount: 0, duration: 100, resultType: "cancelled" },
  5505. { turnId: "turn-1" },
  5506. );
  5507. const { projection } = runAll(log.events);
  5508. const snapshot = projection.getSnapshot();
  5509. expect(snapshot.goal).toMatchObject({ status: "paused" });
  5510. expect(snapshot.availability.resumeGoal).toEqual({ allowed: true });
  5511. });
  5512. it("verify 被 stop(cancelled)—— marker=failed(detail=cancelled),goal 回 paused,摘要不追加", () => {
  5513. const log = new EventLog();
  5514. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5515. log.push(SessionEventType.TargetChanged, {
  5516. action: "set",
  5517. source: "command",
  5518. target: goalTarget("active"),
  5519. });
  5520. log.push(SessionEventType.TargetCompletionVerification, {
  5521. targetId: "target-1",
  5522. status: "started",
  5523. verificationId: "verify-1",
  5524. goalIteration: 1,
  5525. });
  5526. log.push(SessionEventType.TargetCompletionVerification, {
  5527. targetId: "target-1",
  5528. status: "cancelled",
  5529. verificationId: "verify-1",
  5530. goalIteration: 1,
  5531. });
  5532. const { projection } = runAll(log.events);
  5533. const snapshot = projection.getSnapshot();
  5534. expect(snapshot.goal).toMatchObject({ status: "paused" });
  5535. expect(snapshot.goal?.verifications).toHaveLength(0);
  5536. expect(
  5537. snapshot.rows.window.find(
  5538. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  5539. ),
  5540. ).toMatchObject({ marker: { outcome: "failed", detail: "cancelled" } });
  5541. expect(snapshot.availability.resumeGoal).toEqual({ allowed: true });
  5542. });
  5543. it("goal cleared → GoalState=null;重复 status_updated 值未变不下发(conflation)", () => {
  5544. const log = new EventLog();
  5545. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5546. log.push(SessionEventType.TargetChanged, {
  5547. action: "set",
  5548. source: "command",
  5549. target: goalTarget("active"),
  5550. });
  5551. const { projection } = runAll(log.events);
  5552. const noop = new EventLog().push(SessionEventType.TargetChanged, {
  5553. action: "status_updated",
  5554. source: "runtime",
  5555. target: goalTarget("active"),
  5556. });
  5557. expect(projection.applyEvent(noop)).toEqual([]);
  5558. projection.applyEvent(
  5559. new EventLog().push(SessionEventType.TargetChanged, {
  5560. action: "cleared",
  5561. source: "command",
  5562. target: null,
  5563. }),
  5564. );
  5565. expect(projection.getSnapshot().goal).toBeNull();
  5566. expect(projection.getSnapshot().availability.resumeGoal).toEqual({
  5567. allowed: false,
  5568. reasonCode: "noGoalToResume",
  5569. });
  5570. });
  5571. });
  5572. // ── fork marker 与 modelChange marker ──
  5573. describe("fork / modelChange marker", () => {
  5574. it("fork:parent 时间线不显示 forkCreated(S7);child 首部 forkNotice", () => {
  5575. const parentLog = new EventLog("session-1");
  5576. basicTurnEvents(parentLog);
  5577. parentLog.push(SessionEventType.SessionForked, {
  5578. originalSessionId: "session-1",
  5579. forkedSessionId: "session-child",
  5580. targetMessageId: "msg-3",
  5581. });
  5582. const { projection: parent } = runAll(parentLog.events);
  5583. const parentSnapshot = parent.getSnapshot();
  5584. expect(() => conversationSnapshotSchema.parse(parentSnapshot)).not.toThrow();
  5585. // S7(16-plan,2026-07-08 裁决):fork 关系只在 sessions 树体现,父时间线零入侵
  5586. //(旧实现的 forkCreated 是「渲染 null」的隐形行 + nextRowId-1 近似锚点)。
  5587. expect(
  5588. parentSnapshot.rows.window.find(
  5589. (row) => row.kind === "timelineMarker" && row.marker.type === "forkCreated",
  5590. ),
  5591. ).toBeUndefined();
  5592. const childProjection = new ProductProjection("session-child", "epoch-1");
  5593. const childLog = new EventLog("session-child");
  5594. childLog.push(SessionEventType.SessionForked, {
  5595. originalSessionId: "session-1",
  5596. forkedSessionId: "session-child",
  5597. });
  5598. for (const event of childLog.events) childProjection.applyEvent(event);
  5599. expect(childProjection.getSnapshot().rows.window[0]).toMatchObject({
  5600. kind: "timelineMarker",
  5601. marker: { type: "forkNotice", parentSessionId: "session-1" },
  5602. });
  5603. });
  5604. it("modelChange(R-17 时机):marker 只在下一 turn 开始且与上一轮选型不同时产生", () => {
  5605. // 场景 1(草稿态 bug 复现,2026-07-07):turn 前任意切换选择器 → 不产 marker,
  5606. // 首轮以最终选型启动也不产(「第一次用什么模型」不构成「变化」)。
  5607. const log = new EventLog();
  5608. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5609. log.push(SessionEventType.ModelSelected, {
  5610. modelSelection: {
  5611. providerId: "anthropic",
  5612. modelId: "claude-4",
  5613. options: { reasoningLevel: "thinking" },
  5614. },
  5615. });
  5616. log.push(SessionEventType.ModelSelected, {
  5617. previousModelSelection: {
  5618. providerId: "anthropic",
  5619. modelId: "claude-4",
  5620. options: { reasoningLevel: "thinking" },
  5621. },
  5622. modelSelection: { providerId: "openai", modelId: "gpt-6" },
  5623. });
  5624. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  5625. const { projection } = runAll(log.events);
  5626. expect(projection.getSnapshot().config).toMatchObject({
  5627. provider: "openai",
  5628. model: "gpt-6",
  5629. });
  5630. expect(
  5631. projection
  5632. .getSnapshot()
  5633. .rows.window.filter(
  5634. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5635. ),
  5636. ).toHaveLength(0);
  5637. // 重复选同一配置:conflation,无 delta。
  5638. const repeat = new EventLog().push(SessionEventType.ModelSelected, {
  5639. modelSelection: { providerId: "openai", modelId: "gpt-6" },
  5640. });
  5641. expect(projection.applyEvent(repeat)).toEqual([]);
  5642. // 场景 2:turn-1 用 gpt-6,期间切换 A→B→A(净变化为零)→ turn-2 不产 marker。
  5643. projection.applyEvent(
  5644. new EventLog().push(SessionEventType.ModelSelected, {
  5645. modelSelection: { providerId: "anthropic", modelId: "claude-4" },
  5646. }),
  5647. );
  5648. projection.applyEvent(
  5649. new EventLog().push(SessionEventType.ModelSelected, {
  5650. modelSelection: { providerId: "openai", modelId: "gpt-6" },
  5651. }),
  5652. );
  5653. projection.applyEvent(
  5654. new EventLog().push(
  5655. SessionEventType.TurnStarted,
  5656. { turnNumber: 2, input: "again" },
  5657. { turnId: "turn-2" },
  5658. ),
  5659. );
  5660. expect(
  5661. projection
  5662. .getSnapshot()
  5663. .rows.window.filter(
  5664. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5665. ),
  5666. ).toHaveLength(0);
  5667. // 场景 3:切到不同选型后 turn-3 启动 → marker 落在 turnHeader 之前,
  5668. // from = 上一轮实际选型(gpt-6),to = 本轮选型(claude-4)。
  5669. projection.applyEvent(
  5670. new EventLog().push(SessionEventType.ModelSelected, {
  5671. modelSelection: { providerId: "anthropic", modelId: "claude-4" },
  5672. }),
  5673. );
  5674. projection.applyEvent(
  5675. new EventLog().push(
  5676. SessionEventType.TurnStarted,
  5677. { turnNumber: 3, input: "switch" },
  5678. { turnId: "turn-3" },
  5679. ),
  5680. );
  5681. const rows = projection.getSnapshot().rows.window;
  5682. const markerIndex = rows.findIndex(
  5683. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5684. );
  5685. expect(rows[markerIndex]).toMatchObject({
  5686. marker: {
  5687. type: "modelChange",
  5688. fromProvider: "openai",
  5689. fromModel: "gpt-6",
  5690. toProvider: "anthropic",
  5691. toModel: "claude-4",
  5692. toThought: "",
  5693. },
  5694. });
  5695. // marker 紧邻 turn-3 的 turnHeader 之前。
  5696. expect(rows[markerIndex + 1]).toMatchObject({
  5697. kind: "turnHeader",
  5698. turnId: "turn-3",
  5699. });
  5700. });
  5701. it("显式 source-less 模型边界经原子投影只在首个 turn 生成一次 marker", () => {
  5702. const log = new EventLog("child-session");
  5703. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  5704. log.push(SessionEventType.ModelSelected, {
  5705. previousModelSelection: null,
  5706. modelSelection: {
  5707. providerId: "child-provider",
  5708. modelId: "child-model",
  5709. options: { reasoningLevel: "high" },
  5710. },
  5711. });
  5712. log.push(SessionEventType.ModelSelected, {
  5713. previousModelSelection: {
  5714. providerId: "child-provider",
  5715. modelId: "child-model",
  5716. options: { reasoningLevel: "high" },
  5717. },
  5718. modelSelection: {
  5719. providerId: "child-provider",
  5720. modelId: "child-model-final",
  5721. options: { reasoningLevel: "max" },
  5722. },
  5723. });
  5724. log.push(
  5725. SessionEventType.TurnStarted,
  5726. { turnNumber: 1, input: "first child prompt" },
  5727. { turnId: "child-turn-1" },
  5728. );
  5729. log.push(
  5730. SessionEventType.TurnComplete,
  5731. {
  5732. response: "done",
  5733. tokenCount: 1,
  5734. toolCallCount: 0,
  5735. duration: 1,
  5736. resultType: "success",
  5737. },
  5738. { turnId: "child-turn-1" },
  5739. );
  5740. log.push(
  5741. SessionEventType.TurnStarted,
  5742. { turnNumber: 2, input: "second child prompt" },
  5743. { turnId: "child-turn-2" },
  5744. );
  5745. const projection = new ProductProjection("child-session", "epoch-1");
  5746. for (const event of log.events) {
  5747. expect(projection.applyEventAtomically(event, () => true)).not.toBeNull();
  5748. }
  5749. const rows = projection.getSnapshot().rows.window;
  5750. const markers = rows.filter(
  5751. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5752. );
  5753. expect(markers).toHaveLength(1);
  5754. expect(markers[0]).toMatchObject({
  5755. turnId: "child-turn-1",
  5756. marker: {
  5757. type: "modelChange",
  5758. toProvider: "child-provider",
  5759. toModel: "child-model-final",
  5760. toThought: "max",
  5761. },
  5762. });
  5763. expect(markers[0]?.kind === "timelineMarker" ? markers[0].marker : {}).not.toHaveProperty(
  5764. "fromProvider",
  5765. );
  5766. const markerIndex = rows.indexOf(markers[0]!);
  5767. expect(rows[markerIndex + 1]).toMatchObject({
  5768. kind: "turnHeader",
  5769. turnId: "child-turn-1",
  5770. });
  5771. expect(() => conversationSnapshotSchema.parse(projection.getSnapshot())).not.toThrow();
  5772. });
  5773. it("H17:切模型后 /goal 控制输入不创建工作生命周期,只有 continuation 为 running", () => {
  5774. const log = new EventLog();
  5775. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5776. log.push(SessionEventType.ModelSelected, {
  5777. modelSelection: { providerId: "zhipu", modelId: "glm-5.2-highspeed" },
  5778. });
  5779. log.push(
  5780. SessionEventType.TurnStarted,
  5781. { turnNumber: 1, input: "上一轮", messageId: "user-previous" },
  5782. { turnId: "turn-previous" },
  5783. );
  5784. log.push(
  5785. SessionEventType.TurnComplete,
  5786. { response: "done", tokenCount: 1, toolCallCount: 0, duration: 1000, resultType: "success" },
  5787. { turnId: "turn-previous" },
  5788. );
  5789. log.push(SessionEventType.ModelSelected, {
  5790. modelSelection: {
  5791. providerId: "deepseek",
  5792. modelId: "deepseek-v4-flash",
  5793. options: { reasoningLevel: "max" },
  5794. },
  5795. });
  5796. log.push(
  5797. SessionEventType.TurnStarted,
  5798. {
  5799. turnNumber: 2,
  5800. input: "/Goal 开发一个招投标管理系统",
  5801. messageId: "user-goal",
  5802. executionKind: "controlOnly",
  5803. intent: {
  5804. sourceCommandId: "command-goal",
  5805. queueItemId: "queue-goal",
  5806. clientId: "desktop",
  5807. kind: "sendGoalCommand",
  5808. text: "开发一个招投标管理系统",
  5809. admissionSeq: 1,
  5810. admittedAt: 1,
  5811. requestedDelivery: "startNow",
  5812. admittedDelivery: "startNow",
  5813. },
  5814. },
  5815. { turnId: "turn-goal-query" },
  5816. );
  5817. const projection = new ProductProjection("session-1", "epoch-1");
  5818. for (const event of log.events) projection.applyEvent(event);
  5819. expect(projection.getSnapshot().control).toMatchObject({
  5820. phase: "completedSuccess",
  5821. canStop: false,
  5822. activeWorks: [],
  5823. });
  5824. log.push(
  5825. SessionEventType.TurnComplete,
  5826. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  5827. { turnId: "turn-goal-query" },
  5828. );
  5829. projection.applyEvent(log.events.at(-1)!);
  5830. const goalHeader = projection
  5831. .getSnapshot()
  5832. .rows.window.find((row) => row.kind === "turnHeader" && row.turnId === "user-goal");
  5833. expect(goalHeader).toMatchObject({
  5834. kind: "turnHeader",
  5835. executionKind: "controlOnly",
  5836. state: "completedSuccess",
  5837. });
  5838. expect(goalHeader).not.toHaveProperty("activeMs");
  5839. expect(projection.getSnapshot().control).toMatchObject({
  5840. phase: "completedSuccess",
  5841. canStop: false,
  5842. activeWorks: [],
  5843. });
  5844. log.push(
  5845. SessionEventType.TurnStarted,
  5846. {
  5847. turnNumber: 3,
  5848. input: "继续执行目标",
  5849. messageId: "goal-continuation-1",
  5850. inputSource: "goal-continuation",
  5851. inputVisibility: "model-only",
  5852. },
  5853. { turnId: "turn-goal-continuation" },
  5854. );
  5855. projection.applyEvent(log.events.at(-1)!);
  5856. const snapshot = projection.getSnapshot();
  5857. expect(snapshot.control).toMatchObject({
  5858. phase: "running",
  5859. canStop: true,
  5860. activeWorks: [{ kind: "goalContinuation" }],
  5861. });
  5862. expect(
  5863. snapshot.rows.window.find(
  5864. (row) => row.kind === "turnHeader" && row.turnId === "goal-continuation-1",
  5865. ),
  5866. ).toMatchObject({ executionKind: "agent", state: "running" });
  5867. expect(
  5868. snapshot.rows.window.filter(
  5869. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5870. ),
  5871. ).toHaveLength(1);
  5872. });
  5873. it("modelChange:仅思考深度变化不产 marker", () => {
  5874. const log = new EventLog();
  5875. log.push(SessionEventType.ModelSelected, {
  5876. modelSelection: { providerId: "default-deepseek", modelId: "deepseek-v4-flash" },
  5877. });
  5878. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "first" }, { turnId: "turn-1" });
  5879. const { projection } = runAll(log.events);
  5880. projection.applyEvent(
  5881. new EventLog().push(SessionEventType.ModelSelected, {
  5882. modelSelection: {
  5883. providerId: "default-deepseek",
  5884. modelId: "deepseek-v4-flash",
  5885. options: { reasoningLevel: "max" },
  5886. },
  5887. }),
  5888. );
  5889. projection.applyEvent(
  5890. new EventLog().push(
  5891. SessionEventType.TurnStarted,
  5892. { turnNumber: 2, input: "same model, deeper thought" },
  5893. { turnId: "turn-2" },
  5894. ),
  5895. );
  5896. expect(projection.getSnapshot().config).toMatchObject({
  5897. provider: "default-deepseek",
  5898. model: "deepseek-v4-flash",
  5899. thought: "max",
  5900. });
  5901. expect(
  5902. projection
  5903. .getSnapshot()
  5904. .rows.window.filter(
  5905. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5906. ),
  5907. ).toHaveLength(0);
  5908. });
  5909. // ── M4:rowId → messageId 侧表(forkAssistant/editUserQuery 桥接翻译,13 §E 组前置)──
  5910. it("E:assistant 行记录 assistantMessageId,getMessageIdForRow 可翻译", () => {
  5911. const log = new EventLog();
  5912. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  5913. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  5914. log.push(
  5915. SessionEventType.ModelStreaming,
  5916. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-assist-1" },
  5917. { turnId: "turn-1" },
  5918. );
  5919. log.push(
  5920. SessionEventType.ModelStreaming,
  5921. { kind: "text_delta", delta: "hello", done: false, assistantMessageId: "msg-assist-1" },
  5922. { turnId: "turn-1" },
  5923. );
  5924. log.push(
  5925. SessionEventType.ModelStreaming,
  5926. { kind: "text_end", delta: "", done: false },
  5927. { turnId: "turn-1" },
  5928. );
  5929. const { projection } = runAll(log.events);
  5930. const assistantRow = projection
  5931. .getSnapshot()
  5932. .rows.window.find((row) => row.kind === "assistantText");
  5933. expect(assistantRow).toBeDefined();
  5934. expect(projection.getMessageIdForRow(assistantRow!.rowId)).toBe("msg-assist-1");
  5935. // 非 assistant 行 / 未知 rowId → null(桥接层据此 reject,不静默兜底 fork 错点)。
  5936. expect(projection.getMessageIdForRow(9999)).toBeNull();
  5937. const turnHeaderRow = projection
  5938. .getSnapshot()
  5939. .rows.window.find((row) => row.kind === "turnHeader");
  5940. expect(projection.getMessageIdForRow(turnHeaderRow!.rowId)).toBeNull();
  5941. });
  5942. it("E:无 assistantMessageId 的流(老 provider)→ 行存在但翻译为 null", () => {
  5943. const log = new EventLog();
  5944. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  5945. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  5946. log.push(
  5947. SessionEventType.ModelStreaming,
  5948. { kind: "text_start", delta: "", done: false },
  5949. { turnId: "turn-1" },
  5950. );
  5951. log.push(
  5952. SessionEventType.ModelStreaming,
  5953. { kind: "text_delta", delta: "hello", done: false },
  5954. { turnId: "turn-1" },
  5955. );
  5956. const { projection } = runAll(log.events);
  5957. const assistantRow = projection
  5958. .getSnapshot()
  5959. .rows.window.find((row) => row.kind === "assistantText");
  5960. expect(assistantRow).toBeDefined();
  5961. expect(projection.getMessageIdForRow(assistantRow!.rowId)).toBeNull();
  5962. });
  5963. it("P0:user messageId 缺失时不得用同 turn assistant anchor 冒充 canEdit target", () => {
  5964. const log = new EventLog();
  5965. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  5966. log.push(
  5967. SessionEventType.TurnStarted,
  5968. { turnNumber: 1, input: "缺少持久 user id" },
  5969. { turnId: "turn-1" },
  5970. );
  5971. log.push(
  5972. SessionEventType.ModelStreaming,
  5973. {
  5974. kind: "text_start",
  5975. delta: "",
  5976. done: false,
  5977. assistantMessageId: "assistant-only-anchor",
  5978. },
  5979. { turnId: "turn-1" },
  5980. );
  5981. log.push(
  5982. SessionEventType.ModelStreaming,
  5983. { kind: "text_delta", delta: "回答", done: false },
  5984. { turnId: "turn-1" },
  5985. );
  5986. log.push(
  5987. SessionEventType.TurnComplete,
  5988. { response: "回答", tokenCount: 1, toolCallCount: 0, duration: 1, resultType: "success" },
  5989. { turnId: "turn-1" },
  5990. );
  5991. const { projection } = runAll(log.events);
  5992. const userRow = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput");
  5993. expect(userRow).toBeDefined();
  5994. expect(projection.getMessageIdForRow(userRow!.rowId)).toBeNull();
  5995. // turn rewind 仍能找到 assistant anchor,但 exact user target 不存在。
  5996. expect(projection.getTurnRewindAnchor(userRow!.rowId)).toBe("assistant-only-anchor");
  5997. expect(userRow!.actions?.canEdit).not.toBe(true);
  5998. expect(projection.isLatestEditableUserRow(userRow!.rowId)).toBe(false);
  5999. });
  6000. it("P1:legacy 身份 fallback 必须由 normalizer 留下可观测诊断", () => {
  6001. const log = new EventLog();
  6002. log.push(
  6003. SessionEventType.TurnStarted,
  6004. { turnNumber: 1, input: "legacy query" },
  6005. { turnId: "turn-legacy" },
  6006. );
  6007. const { projection } = runAll(log.events);
  6008. expect(projection.getNormalizationDiagnostics()).toEqual([
  6009. {
  6010. code: "normalizer.user.missingTranscriptMessageId",
  6011. eventId: "event-1",
  6012. },
  6013. ]);
  6014. });
  6015. it("P1/P2:live 与 cold 合成事件的 command target/actions 逐实体等价", () => {
  6016. const project = (turnId: string) => {
  6017. const log = new EventLog();
  6018. log.push(
  6019. SessionEventType.TurnStarted,
  6020. { turnNumber: 1, input: "same query", messageId: "message-user-1" },
  6021. { turnId },
  6022. );
  6023. log.push(
  6024. SessionEventType.ModelStreaming,
  6025. {
  6026. kind: "text_start",
  6027. delta: "",
  6028. done: false,
  6029. assistantMessageId: "message-assistant-1",
  6030. partId: "part-1",
  6031. },
  6032. { turnId },
  6033. );
  6034. log.push(
  6035. SessionEventType.ModelStreaming,
  6036. { kind: "text_delta", delta: "same answer", done: false, partId: "part-1" },
  6037. { turnId },
  6038. );
  6039. log.push(
  6040. SessionEventType.ModelStreaming,
  6041. { kind: "text_end", delta: "", done: false, partId: "part-1" },
  6042. { turnId },
  6043. );
  6044. log.push(
  6045. SessionEventType.TurnComplete,
  6046. {
  6047. response: "same answer",
  6048. tokenCount: 1,
  6049. toolCallCount: 0,
  6050. duration: 1,
  6051. resultType: "success",
  6052. },
  6053. { turnId },
  6054. );
  6055. return runAll(log.events).projection;
  6056. };
  6057. const live = project("runtime-turn-1");
  6058. const cold = project("hydrate-turn-1");
  6059. const semanticRows = (projection: ProductProjection) =>
  6060. projection
  6061. .getSnapshot()
  6062. .rows.window.filter((row) => row.kind === "userInput" || row.kind === "assistantText")
  6063. .map((row) => ({
  6064. kind: row.kind,
  6065. text: row.text,
  6066. productTurnId: row.turnId,
  6067. actions: row.actions,
  6068. entityId: projection.getEntityIdForRow(row.rowId),
  6069. target: projection.getMessageIdForRow(row.rowId),
  6070. }));
  6071. expect(semanticRows(cold)).toEqual(semanticRows(live));
  6072. expect(semanticRows(live).map((row) => row.productTurnId)).toEqual([
  6073. "message-user-1",
  6074. "message-user-1",
  6075. ]);
  6076. expect(live.getNormalizationDiagnostics()).toEqual([]);
  6077. expect(cold.getNormalizationDiagnostics()).toEqual([]);
  6078. });
  6079. it("P2:entity resolver 只允许当前 canEdit 的真实用户实体", () => {
  6080. const log = new EventLog();
  6081. for (const turnNumber of [1, 2]) {
  6082. const turnId = `turn-${turnNumber}`;
  6083. log.push(
  6084. SessionEventType.TurnStarted,
  6085. {
  6086. turnNumber,
  6087. input: `query ${turnNumber}`,
  6088. messageId: `message-user-${turnNumber}`,
  6089. },
  6090. { turnId },
  6091. );
  6092. log.push(
  6093. SessionEventType.TurnComplete,
  6094. {
  6095. response: "",
  6096. tokenCount: 0,
  6097. toolCallCount: 0,
  6098. duration: 1,
  6099. resultType: "success",
  6100. },
  6101. { turnId },
  6102. );
  6103. }
  6104. const { projection } = runAll(log.events);
  6105. const userRows = projection.getSnapshot().rows.window.filter((row) => row.kind === "userInput");
  6106. expect(userRows.map((row) => row.actions?.canEdit === true)).toEqual([false, true]);
  6107. expect(projection.resolveEditTargetByEntityId("message-user-1")).toBeNull();
  6108. expect(projection.resolveEditTargetByEntityId("message-user-2")).toMatchObject({
  6109. entityId: "message-user-2",
  6110. productTurnId: "message-user-2",
  6111. transcriptMessageId: "message-user-2",
  6112. });
  6113. });
  6114. it("Task3:row.actions 与 target resolver 同源并声明 edit disposition", () => {
  6115. const log = new EventLog();
  6116. log.push(
  6117. SessionEventType.TurnStarted,
  6118. { turnNumber: 1, input: "query", messageId: "message-user-1" },
  6119. { turnId: "turn-1" },
  6120. );
  6121. log.push(
  6122. SessionEventType.ModelStreaming,
  6123. {
  6124. kind: "text_start",
  6125. delta: "",
  6126. done: false,
  6127. assistantMessageId: "message-assistant-1",
  6128. },
  6129. { turnId: "turn-1" },
  6130. );
  6131. log.push(
  6132. SessionEventType.ModelStreaming,
  6133. { kind: "text_end", delta: "", done: false },
  6134. { turnId: "turn-1" },
  6135. );
  6136. log.push(
  6137. SessionEventType.TurnComplete,
  6138. {
  6139. response: "",
  6140. tokenCount: 0,
  6141. toolCallCount: 0,
  6142. duration: 1,
  6143. resultType: "success",
  6144. },
  6145. { turnId: "turn-1" },
  6146. );
  6147. const { projection } = runAll(log.events);
  6148. const userRow = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput")!;
  6149. const assistantRow = projection
  6150. .getSnapshot()
  6151. .rows.window.find((row) => row.kind === "assistantText")!;
  6152. const target = { rowId: userRow.rowId, entityId: "message-user-1" };
  6153. expect(userRow.actions).toMatchObject({
  6154. canEdit: true,
  6155. editDisposition: "rewind",
  6156. });
  6157. expect(assistantRow.actions).toMatchObject({
  6158. canFork: true,
  6159. canRetry: true,
  6160. });
  6161. expect(projection.resolveRowActionTarget(target, "editUserQuery")).toMatchObject({
  6162. ok: true,
  6163. action: "editUserQuery",
  6164. editTarget: { transcriptMessageId: "message-user-1" },
  6165. });
  6166. expect(
  6167. projection.resolveRowActionTarget(
  6168. { rowId: userRow.rowId, entityId: "reused-for-another-entity" },
  6169. "editUserQuery",
  6170. ),
  6171. ).toEqual({ ok: false, status: "stale", reasonCode: "proto.staleTarget" });
  6172. expect(projection.resolveRowActionTarget(target, "retryTurn")).toEqual({
  6173. ok: false,
  6174. status: "rejected",
  6175. reasonCode: "guard.actionUnavailable",
  6176. });
  6177. projection.applyEvent(
  6178. new EventLog().push(SessionEventType.CompactStarted, {
  6179. operationId: "compact-1",
  6180. messageId: "compact-message",
  6181. status: "started",
  6182. trigger: "manual",
  6183. display: "separator",
  6184. }),
  6185. );
  6186. const lockedRow = projection
  6187. .getSnapshot()
  6188. .rows.window.find((row) => row.rowId === userRow.rowId)!;
  6189. const lockedAssistantRow = projection
  6190. .getSnapshot()
  6191. .rows.window.find((row) => row.rowId === assistantRow.rowId)!;
  6192. expect(lockedRow.actions?.canEdit).toBeUndefined();
  6193. expect(lockedAssistantRow.actions?.canFork).toBeUndefined();
  6194. expect(lockedAssistantRow.actions?.canRetry).toBeUndefined();
  6195. expect(projection.getSnapshot().availability.sendQueuedNow).toEqual({
  6196. allowed: false,
  6197. reasonCode: "compactOperationLock",
  6198. });
  6199. projection.applyEvent(
  6200. new EventLog().push(SessionEventType.CompactCompleted, {
  6201. operationId: "compact-1",
  6202. messageId: "compact-message",
  6203. status: "completed",
  6204. trigger: "manual",
  6205. display: "separator",
  6206. tailStartMessageId: "message-user-1",
  6207. }),
  6208. );
  6209. const compactedRow = projection
  6210. .getSnapshot()
  6211. .rows.window.find((row) => row.rowId === userRow.rowId)!;
  6212. expect(compactedRow.actions).toMatchObject({
  6213. canEdit: true,
  6214. editDisposition: "rewind",
  6215. });
  6216. expect(projection.resolveRowActionTarget(target, "editUserQuery")).toMatchObject({
  6217. ok: true,
  6218. action: "editUserQuery",
  6219. editTarget: { coveredByStableCompact: true },
  6220. });
  6221. });
  6222. it("root review:primary/goal continuation/verifier running 时 retry 与 file rewind 同源禁用", () => {
  6223. const completedProjection = () => {
  6224. const log = new EventLog();
  6225. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6226. log.push(
  6227. SessionEventType.TurnStarted,
  6228. { turnNumber: 1, input: "改文件", messageId: "message-user-base" },
  6229. { turnId: "turn-base" },
  6230. );
  6231. log.push(
  6232. SessionEventType.ModelStreaming,
  6233. {
  6234. kind: "text_start",
  6235. delta: "",
  6236. done: false,
  6237. assistantMessageId: "message-assistant-base",
  6238. },
  6239. { turnId: "turn-base" },
  6240. );
  6241. log.push(
  6242. SessionEventType.ModelStreaming,
  6243. { kind: "text_delta", delta: "done", done: false },
  6244. { turnId: "turn-base" },
  6245. );
  6246. log.push(
  6247. SessionEventType.ModelComplete,
  6248. {
  6249. content: "done",
  6250. stopReason: "stop",
  6251. querySource: "main_turn",
  6252. contextWindow: 200_000,
  6253. usage: { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 },
  6254. fileChanges: {
  6255. files: 1,
  6256. additions: 2,
  6257. deletions: 1,
  6258. items: [{ path: "/work/a.ts", additions: 2, deletions: 1, writeCount: 1 }],
  6259. },
  6260. },
  6261. { turnId: "turn-base" },
  6262. );
  6263. log.push(
  6264. SessionEventType.TurnComplete,
  6265. { response: "done", tokenCount: 2, toolCallCount: 0, duration: 1, resultType: "success" },
  6266. { turnId: "turn-base" },
  6267. );
  6268. return runAll(log.events).projection;
  6269. };
  6270. const contexts = [
  6271. {
  6272. kind: "primaryTurn",
  6273. event: () =>
  6274. new EventLog().push(
  6275. SessionEventType.TurnStarted,
  6276. { turnNumber: 2, input: "next", messageId: "message-user-next" },
  6277. { turnId: "turn-next" },
  6278. ),
  6279. },
  6280. {
  6281. kind: "goalContinuation",
  6282. event: () =>
  6283. new EventLog().push(
  6284. SessionEventType.TurnStarted,
  6285. {
  6286. turnNumber: 2,
  6287. input: "continue",
  6288. inputSource: "goal-continuation",
  6289. inputVisibility: "model-only",
  6290. },
  6291. { turnId: "turn-goal-continuation" },
  6292. ),
  6293. },
  6294. {
  6295. kind: "goalVerifier",
  6296. event: () =>
  6297. new EventLog().push(SessionEventType.TargetCompletionVerification, {
  6298. targetId: "target-1",
  6299. status: "started",
  6300. verificationId: "verify-1",
  6301. goalIteration: 1,
  6302. }),
  6303. },
  6304. ] as const;
  6305. for (const context of contexts) {
  6306. const projection = completedProjection();
  6307. const base = projection.getSnapshot();
  6308. const header = base.rows.window.find((row) => row.kind === "turnHeader")!;
  6309. const assistant = base.rows.window.find((row) => row.kind === "assistantText")!;
  6310. const headerTarget = { rowId: header.rowId, entityId: header.entityId! };
  6311. const assistantTarget = { rowId: assistant.rowId, entityId: assistant.entityId! };
  6312. projection.applyEvent(context.event());
  6313. const running = projection.getSnapshot();
  6314. const lockedHeader = running.rows.window.find((row) => row.rowId === header.rowId)!;
  6315. const lockedAssistant = running.rows.window.find((row) => row.rowId === assistant.rowId)!;
  6316. expect(running.control.activeWorks.some((work) => work.kind === context.kind)).toBe(true);
  6317. expect(lockedHeader.actions?.canRewindFiles, context.kind).toBeUndefined();
  6318. expect(lockedAssistant.actions?.canRetry, context.kind).toBeUndefined();
  6319. expect(lockedAssistant.actions?.canFork, context.kind).toBe(true);
  6320. expect(projection.resolveRowActionTarget(headerTarget, "applyFileRewind")).toMatchObject({
  6321. ok: false,
  6322. reasonCode: "guard.actionUnavailable",
  6323. });
  6324. expect(projection.resolveRowActionTarget(assistantTarget, "retryTurn")).toMatchObject({
  6325. ok: false,
  6326. reasonCode: "guard.actionUnavailable",
  6327. });
  6328. expect(projection.resolveRowActionTarget(assistantTarget, "forkAssistant")).toMatchObject({
  6329. ok: true,
  6330. });
  6331. }
  6332. });
  6333. // ── M4:queue 单项编辑(同 id 重入 TurnSteerQueued → 原地更新保位)──
  6334. it("A/B:editQueueItem —— 同 queueItemId 重入更新文本且保位", () => {
  6335. const log = new EventLog();
  6336. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6337. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6338. // 入队两条
  6339. log.push(
  6340. SessionEventType.TurnSteerQueued,
  6341. {
  6342. pendingInputId: "q1",
  6343. input: "第一条",
  6344. inputPreview: "第一条",
  6345. inputSize: 9,
  6346. automationId: "automation-queued",
  6347. queueLength: 1,
  6348. targetTurnId: "t1",
  6349. intent: {
  6350. botGroupSource: {
  6351. provider: "feishu",
  6352. botId: "bot",
  6353. chatId: "group",
  6354. senderId: "member",
  6355. senderName: "Member",
  6356. messageId: "message",
  6357. },
  6358. sourceCommandId: "command-q1",
  6359. queueItemId: "q1",
  6360. clientId: "mobile-client",
  6361. kind: "sendText",
  6362. admissionSeq: 1,
  6363. admittedAt: 10,
  6364. requestedDelivery: "guide",
  6365. admittedDelivery: "queue",
  6366. fallbackReasonCode: "guide.attachmentsUnsupported",
  6367. attachmentRefs: [
  6368. { ref: "artifact://q1", fileName: "q1.txt", mime: "text/plain", bytes: 2 },
  6369. ],
  6370. },
  6371. },
  6372. { turnId: "t1" },
  6373. );
  6374. log.push(
  6375. SessionEventType.TurnSteerQueued,
  6376. {
  6377. pendingInputId: "q2",
  6378. input: "第二条",
  6379. inputPreview: "第二条",
  6380. inputSize: 9,
  6381. queueLength: 2,
  6382. targetTurnId: "t1",
  6383. },
  6384. { turnId: "t1" },
  6385. );
  6386. // 编辑第一条(同 id 重入)
  6387. log.push(
  6388. SessionEventType.TurnSteerQueued,
  6389. {
  6390. pendingInputId: "q1",
  6391. input: "第一条改",
  6392. inputPreview: "第一条改",
  6393. inputSize: 12,
  6394. queueLength: 2,
  6395. targetTurnId: "t1",
  6396. },
  6397. { turnId: "t1" },
  6398. );
  6399. const { projection } = runAll(log.events);
  6400. const items = projection.getSnapshot().queue.items;
  6401. // 仍 2 条,q1 在原位(index 0)且文本已更新。
  6402. expect(items.map((i) => i.queueItemId)).toEqual(["q1", "q2"]);
  6403. expect(items[0]).toMatchObject({
  6404. text: "第一条改",
  6405. automationId: "automation-queued",
  6406. botGroupSource: { senderId: "member", chatId: "group" },
  6407. sourceCommandId: "command-q1",
  6408. clientId: "mobile-client",
  6409. attachments: [{ ref: "artifact://q1" }],
  6410. delivery: {
  6411. requested: "guide",
  6412. admitted: "queue",
  6413. fallbackReasonCode: "guide.attachmentsUnsupported",
  6414. },
  6415. order: { admissionSeq: 1, queuePosition: 0 },
  6416. steer: { state: "fellBack", reasonCode: "guide.attachmentsUnsupported" },
  6417. });
  6418. expect(items[1]!.text).toBe("第二条");
  6419. });
  6420. // ── M4:queue 重排(TurnSteerReordered → 按新序重排 queue rows)──
  6421. it("A/B:reorderQueueItem —— 按 orderedPendingInputIds 重排 queue", () => {
  6422. const log = new EventLog();
  6423. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6424. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6425. for (const [id, text, len] of [
  6426. ["q1", "一", 3],
  6427. ["q2", "二", 3],
  6428. ["q3", "三", 3],
  6429. ] as const) {
  6430. log.push(
  6431. SessionEventType.TurnSteerQueued,
  6432. {
  6433. pendingInputId: id,
  6434. input: text,
  6435. inputPreview: text,
  6436. inputSize: len,
  6437. queueLength: 3,
  6438. targetTurnId: "t1",
  6439. },
  6440. { turnId: "t1" },
  6441. );
  6442. }
  6443. // 把 q3 移到 q1 之前:新序 q3, q1, q2。
  6444. log.push(
  6445. SessionEventType.TurnSteerReordered,
  6446. { orderedPendingInputIds: ["q3", "q1", "q2"], targetTurnId: "t1" },
  6447. { turnId: "t1" },
  6448. );
  6449. const { projection } = runAll(log.events);
  6450. expect(projection.getSnapshot().queue.items.map((i) => i.queueItemId)).toEqual([
  6451. "q3",
  6452. "q1",
  6453. "q2",
  6454. ]);
  6455. expect(projection.getSnapshot().queue.items.map((i) => i.order.queuePosition)).toEqual([
  6456. 0, 1, 2,
  6457. ]);
  6458. });
  6459. it("sendQueuedNow dispatch:reserved/promoting 只更新目标项且保留完整 intent", () => {
  6460. const log = new EventLog();
  6461. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6462. log.push(
  6463. SessionEventType.TurnSteerQueued,
  6464. {
  6465. pendingInputId: "q1",
  6466. input: "带附件输入",
  6467. inputPreview: "带附件输入",
  6468. inputSize: 18,
  6469. queueLength: 1,
  6470. targetTurnId: "t1",
  6471. intent: {
  6472. sourceCommandId: "source-q1",
  6473. queueItemId: "q1",
  6474. clientId: "mobile-client",
  6475. kind: "sendText",
  6476. admissionSeq: 1,
  6477. admittedAt: 10,
  6478. requestedDelivery: "queue",
  6479. admittedDelivery: "queue",
  6480. attachmentRefs: [
  6481. { ref: "artifact://q1", fileName: "q1.txt", mime: "text/plain", bytes: 2 },
  6482. ],
  6483. },
  6484. },
  6485. { turnId: "t1" },
  6486. );
  6487. log.push(SessionEventType.TurnSteerDispatchChanged, {
  6488. pendingInputId: "q1",
  6489. reservationId: "send-now-1",
  6490. state: "reserved",
  6491. targetTurnId: "t1",
  6492. });
  6493. log.push(SessionEventType.TurnSteerDispatchChanged, {
  6494. pendingInputId: "q1",
  6495. reservationId: "send-now-1",
  6496. state: "promoting",
  6497. targetTurnId: "t1",
  6498. });
  6499. const { projection } = runAll(log.events);
  6500. expect(projection.getSnapshot().queue.items[0]).toMatchObject({
  6501. sourceCommandId: "source-q1",
  6502. clientId: "mobile-client",
  6503. attachments: [{ ref: "artifact://q1" }],
  6504. dispatch: { state: "promoting", reservationId: "send-now-1" },
  6505. });
  6506. });
  6507. it("sendQueuedNow commit:SessionInputPromoted 是 queue 移除的 durable 提交信号", () => {
  6508. const log = new EventLog();
  6509. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6510. log.push(
  6511. SessionEventType.TurnSteerQueued,
  6512. {
  6513. pendingInputId: "q1",
  6514. input: "已持久化输入",
  6515. inputPreview: "已持久化输入",
  6516. inputSize: 21,
  6517. queueLength: 1,
  6518. targetTurnId: "t1",
  6519. intent: {
  6520. sourceCommandId: "source-q1",
  6521. queueItemId: "q1",
  6522. clientId: "desktop-client",
  6523. kind: "sendText",
  6524. admissionSeq: 1,
  6525. admittedAt: 10,
  6526. requestedDelivery: "queue",
  6527. admittedDelivery: "queue",
  6528. attachmentRefs: [],
  6529. },
  6530. },
  6531. { turnId: "t1" },
  6532. );
  6533. log.push(SessionEventType.TurnSteerDispatchChanged, {
  6534. pendingInputId: "q1",
  6535. reservationId: "send-now-1",
  6536. state: "promoting",
  6537. targetTurnId: "t1",
  6538. });
  6539. // startPromptTurn 已把 user message + session_input promotion 同事务提交。
  6540. // 即使后续 TurnSteerDiscarded(promoted) 丢失,投影也不能留下幽灵 queue item。
  6541. log.push(SessionEventType.SessionInputPromoted, {
  6542. pendingInputId: "q1",
  6543. sourceCommandId: "source-q1",
  6544. messageId: "message-q1",
  6545. });
  6546. const { projection } = runAll(log.events);
  6547. expect(projection.getSnapshot().queue.items).toEqual([]);
  6548. });
  6549. // ── M4:setAutoDrain(QueueAutoDrainChanged → queue.autoDrain + held 派生)──
  6550. it("A/B:setAutoDrain(false) → queue.autoDrain=false,held 时 completed+queue>0 走 choice", () => {
  6551. const log = new EventLog();
  6552. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6553. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6554. log.push(
  6555. SessionEventType.TurnSteerQueued,
  6556. {
  6557. pendingInputId: "q1",
  6558. input: "排队项",
  6559. inputPreview: "排队项",
  6560. inputSize: 9,
  6561. queueLength: 1,
  6562. targetTurnId: "t1",
  6563. },
  6564. { turnId: "t1" },
  6565. );
  6566. // 关闭 autoDrain(保留队列)
  6567. log.push(SessionEventType.QueueAutoDrainChanged, { autoDrain: false });
  6568. // turn 结束 → completed + queue>0 + autoDrain=false → 输入路由为 choice
  6569. log.push(
  6570. SessionEventType.TurnComplete,
  6571. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  6572. { turnId: "t1" },
  6573. );
  6574. const { projection } = runAll(log.events);
  6575. const snapshot = projection.getSnapshot();
  6576. expect(snapshot.queue.autoDrain).toBe(false);
  6577. expect(snapshot.queue.pauseReason).toBe("manual");
  6578. expect(snapshot.inputRouting.mode).toBe("choice");
  6579. expect(snapshot.inputRouting.reasonCode).toBe("heldQueueInputRequiresChoice");
  6580. });
  6581. it("B:Stop 保留队列时记录 stopped 原因;恢复后清除暂停原因", () => {
  6582. const log = new EventLog();
  6583. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6584. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6585. log.push(
  6586. SessionEventType.TurnSteerQueued,
  6587. {
  6588. pendingInputId: "q1",
  6589. input: "排队项",
  6590. inputPreview: "排队项",
  6591. inputSize: 9,
  6592. queueLength: 1,
  6593. targetTurnId: "t1",
  6594. },
  6595. { turnId: "t1" },
  6596. );
  6597. log.push(
  6598. SessionEventType.TurnComplete,
  6599. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "cancelled" },
  6600. { turnId: "t1" },
  6601. );
  6602. log.push(SessionEventType.QueueAutoDrainChanged, { autoDrain: true });
  6603. const projection = new ProductProjection("s1", "epoch-1");
  6604. for (const event of log.events.slice(0, -1)) projection.applyEvent(event);
  6605. expect(projection.getSnapshot().queue).toMatchObject({
  6606. autoDrain: false,
  6607. pauseReason: "stopped",
  6608. });
  6609. projection.applyEvent(log.events.at(-1)!);
  6610. expect(projection.getSnapshot().queue.autoDrain).toBe(true);
  6611. expect(projection.getSnapshot().queue.pauseReason).toBeUndefined();
  6612. });
  6613. it("M07a:sendQueuedNow 内部抢占不把 future queue 投影为 stopped", () => {
  6614. const log = new EventLog();
  6615. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6616. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6617. log.push(
  6618. SessionEventType.TurnSteerQueued,
  6619. {
  6620. pendingInputId: "q1",
  6621. input: "立即发送",
  6622. inputPreview: "立即发送",
  6623. inputSize: 12,
  6624. queueLength: 1,
  6625. targetTurnId: "t1",
  6626. },
  6627. { turnId: "t1" },
  6628. );
  6629. log.push(
  6630. SessionEventType.TurnComplete,
  6631. {
  6632. response: "",
  6633. tokenCount: 0,
  6634. toolCallCount: 0,
  6635. duration: 0,
  6636. resultType: "cancelled",
  6637. preserveQueueAutoDrainOnCancel: true,
  6638. },
  6639. { turnId: "t1" },
  6640. );
  6641. const { projection } = runAll(log.events);
  6642. const snapshot = projection.getSnapshot();
  6643. expect(snapshot.control.phase).toBe("completedInterrupted");
  6644. expect(snapshot.queue).toMatchObject({
  6645. autoDrain: true,
  6646. items: [expect.objectContaining({ queueItemId: "q1" })],
  6647. });
  6648. expect(snapshot.queue.pauseReason).toBeUndefined();
  6649. expect(snapshot.inputRouting.mode).toBe("startNow");
  6650. });
  6651. it("A/B:setAutoDrain 幂等 —— 同值不产 delta", () => {
  6652. const log = new EventLog();
  6653. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6654. // 初始 autoDrain=true,再置 true 应无变化。
  6655. log.push(SessionEventType.QueueAutoDrainChanged, { autoDrain: true });
  6656. const { projection } = runAll(log.events);
  6657. expect(projection.getSnapshot().queue.autoDrain).toBe(true);
  6658. });
  6659. // ── M4:setFollowupMode(FollowupModeChanged → running 时 enqueue vs guide)──
  6660. it("A/B:setFollowupMode(guide) → running 时输入路由为 guide", () => {
  6661. const log = new EventLog();
  6662. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6663. log.push(SessionEventType.FollowupModeChanged, { mode: "guide" });
  6664. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6665. const { projection } = runAll(log.events);
  6666. const snapshot = projection.getSnapshot();
  6667. expect(snapshot.config.followupMode).toBe("guide");
  6668. expect(snapshot.inputRouting.mode).toBe("guide");
  6669. });
  6670. it("A/B:followupMode 默认 queue —— running 时输入入队", () => {
  6671. const log = new EventLog();
  6672. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6673. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6674. const { projection } = runAll(log.events);
  6675. const snapshot = projection.getSnapshot();
  6676. expect(snapshot.config.followupMode).toBe("queue");
  6677. expect(snapshot.inputRouting.mode).toBe("enqueue");
  6678. });
  6679. // ── M5:switchCollaborationMode(SessionModeChanged → config.mode)──
  6680. it("A/B:SessionModeChanged —— config.mode 更新且 revision 前进;同值不动", () => {
  6681. const log = new EventLog();
  6682. log.push(SessionEventType.SessionCreated, { mode: "build", contextWindow: 200_000 });
  6683. log.push(SessionEventType.SessionModeChanged, {
  6684. mode: "plan",
  6685. previousMode: "build",
  6686. source: "command",
  6687. });
  6688. const { projection } = runAll(log.events);
  6689. const snapshot = projection.getSnapshot();
  6690. expect(snapshot.config.mode).toBe("plan");
  6691. const revisionAfterSwitch = snapshot.revision;
  6692. // 同值再切:无 delta,revision 不前进。
  6693. log.push(SessionEventType.SessionModeChanged, {
  6694. mode: "plan",
  6695. previousMode: "plan",
  6696. source: "command",
  6697. });
  6698. const { projection: projection2 } = runAll(log.events);
  6699. expect(projection2.getSnapshot().config.mode).toBe("plan");
  6700. expect(projection2.getSnapshot().revision).toBe(revisionAfterSwitch);
  6701. });
  6702. it("A/B:config.mode 初值 = build(draft 期无 SessionModeChanged 时的回落)", () => {
  6703. const log = new EventLog();
  6704. log.push(SessionEventType.SessionCreated, { mode: "build", contextWindow: 200_000 });
  6705. const { projection } = runAll(log.events);
  6706. expect(projection.getSnapshot().config.mode).toBe("build");
  6707. });
  6708. // ── M4:renameSession / 自动标题(SessionTitleUpdated → meta.title)──
  6709. it("A/B:SessionTitleUpdated —— generated 更新,custom 覆盖且 custom 后不被 generated 回退", () => {
  6710. const log = new EventLog();
  6711. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6712. // 初始 default
  6713. expect(runAll(log.events).projection.getSnapshot().meta.titleSource).toBe("default");
  6714. // 自动生成标题
  6715. log.push(SessionEventType.SessionTitleUpdated, {
  6716. previousTitle: "",
  6717. source: "generated",
  6718. title: "自动标题",
  6719. });
  6720. // 用户重命名(custom)
  6721. log.push(SessionEventType.SessionTitleUpdated, {
  6722. previousTitle: "自动标题",
  6723. source: "custom",
  6724. title: "我的会话",
  6725. });
  6726. // custom 后再来一次 generated —— 应被忽略(custom 粘性)
  6727. log.push(SessionEventType.SessionTitleUpdated, {
  6728. previousTitle: "我的会话",
  6729. source: "generated",
  6730. title: "又一个自动标题",
  6731. });
  6732. const meta = runAll(log.events).projection.getSnapshot().meta;
  6733. expect(meta.title).toBe("我的会话");
  6734. expect(meta.titleSource).toBe("custom");
  6735. });
  6736. it("A/B:SessionTitleUpdated —— first_input 归一为 generated", () => {
  6737. const log = new EventLog();
  6738. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6739. log.push(SessionEventType.SessionTitleUpdated, {
  6740. previousTitle: "",
  6741. source: "first_input",
  6742. title: "首条输入标题",
  6743. });
  6744. const meta = runAll(log.events).projection.getSnapshot().meta;
  6745. expect(meta.title).toBe("首条输入标题");
  6746. expect(meta.titleSource).toBe("generated");
  6747. });
  6748. // ── M4:switchModelConfig(ModelSelected → config 更新 + 中途切换 modelChange marker)──
  6749. it("A/B:ModelSelected 首次 → config 更新,无 marker(首次选型不算切换)", () => {
  6750. const log = new EventLog();
  6751. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6752. log.push(SessionEventType.ModelSelected, {
  6753. modelSelection: { providerId: "e2e-deepseek", modelId: "deepseek-v4-flash" },
  6754. supportedThoughtLevels: ["max", "high", "nothink"],
  6755. });
  6756. const { projection } = runAll(log.events);
  6757. const snapshot = projection.getSnapshot();
  6758. expect(snapshot.config.provider).toBe("e2e-deepseek");
  6759. expect(snapshot.config.model).toBe("deepseek-v4-flash");
  6760. expect(snapshot.config.thoughtLevels).toEqual(["max", "high", "nothink"]);
  6761. // 首次选型不产 modelChange marker。
  6762. expect(
  6763. snapshot.rows.window.some(
  6764. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  6765. ),
  6766. ).toBe(false);
  6767. });
  6768. it("ModelSelected 分离稀疏 Session Selection 与 effective reasoning 展示事实", () => {
  6769. const log = new EventLog();
  6770. log.push(SessionEventType.ModelSelected, {
  6771. modelSelection: { providerId: "provider-a", modelId: "model-a" },
  6772. effectiveReasoningLevel: "high",
  6773. supportedThoughtLevels: ["low", "high"],
  6774. });
  6775. const snapshot = runAll(log.events).projection.getSnapshot();
  6776. expect(snapshot.config.modelSelection).toEqual({
  6777. providerId: "provider-a",
  6778. modelId: "model-a",
  6779. });
  6780. expect(snapshot.config.thought).toBe("high");
  6781. });
  6782. it("A/B:ModelSelected 中途切换 → config 更新;marker 归 turn 开始(R-17 时机)", () => {
  6783. const log = new EventLog();
  6784. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6785. log.push(SessionEventType.ModelSelected, {
  6786. modelSelection: { providerId: "e2e-deepseek", modelId: "deepseek-v4-flash" },
  6787. supportedThoughtLevels: ["max", "high", "nothink"],
  6788. });
  6789. log.push(SessionEventType.ModelSelected, {
  6790. modelSelection: {
  6791. providerId: "e2e-deepseek",
  6792. modelId: "deepseek-v4-pro",
  6793. options: { reasoningLevel: "max" },
  6794. },
  6795. supportedThoughtLevels: ["max", "nothink"],
  6796. });
  6797. const { projection } = runAll(log.events);
  6798. const snapshot = projection.getSnapshot();
  6799. expect(snapshot.config.model).toBe("deepseek-v4-pro");
  6800. expect(snapshot.config.thought).toBe("max");
  6801. expect(snapshot.config.thoughtLevels).toEqual(["max", "nothink"]);
  6802. // R-17 时机修复(2026-07-07):切换动作本身不落 marker——尚未有 turn 使用过
  6803. // 任何模型(草稿态截图 bug:首条消息上方挂 [modelChange])。
  6804. expect(
  6805. snapshot.rows.window.some(
  6806. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  6807. ),
  6808. ).toBe(false);
  6809. });
  6810. it("I56:registry fallback 投影稳定事件与起止模型,显式切换不伪造来源", () => {
  6811. const log = new EventLog();
  6812. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6813. log.push(SessionEventType.ModelSelected, {
  6814. modelSelection: { providerId: "provider-a", modelId: "model-a" },
  6815. });
  6816. const fallbackEvent = log.push(SessionEventType.ModelSelected, {
  6817. modelSelection: {
  6818. providerId: "provider-b",
  6819. modelId: "model-b",
  6820. options: { reasoningLevel: "deep" },
  6821. },
  6822. previousModelSelection: { providerId: "provider-a", modelId: "model-a" },
  6823. origin: "registryFallback",
  6824. });
  6825. const { projection } = runAll(log.events);
  6826. expect(projection.getSnapshot().modelTransition).toEqual({
  6827. eventId: fallbackEvent.id,
  6828. origin: "registryFallback",
  6829. from: { provider: "provider-a", model: "model-a" },
  6830. to: { provider: "provider-b", model: "model-b" },
  6831. });
  6832. projection.applyEvent(
  6833. log.push(SessionEventType.ModelSelected, {
  6834. modelSelection: { providerId: "provider-c", modelId: "model-c" },
  6835. previousModelSelection: {
  6836. providerId: "provider-b",
  6837. modelId: "model-b",
  6838. options: { reasoningLevel: "deep" },
  6839. },
  6840. }),
  6841. );
  6842. expect(projection.getSnapshot().modelTransition?.eventId).toBe(fallbackEvent.id);
  6843. });
  6844. it("A/B:历史会话切换模型后立即刷新 context window 分母并保留已用量", () => {
  6845. const log = new EventLog();
  6846. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6847. log.push(
  6848. SessionEventType.TurnStarted,
  6849. { turnNumber: 1, input: "history" },
  6850. { turnId: "turn-1" },
  6851. );
  6852. log.push(
  6853. SessionEventType.ModelComplete,
  6854. {
  6855. content: "done",
  6856. stopReason: "end_turn",
  6857. querySource: "main_turn",
  6858. contextWindow: 200_000,
  6859. usage: { inputTokens: 120, outputTokens: 30 },
  6860. },
  6861. { turnId: "turn-1" },
  6862. );
  6863. const { projection } = runAll(log.events);
  6864. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6865. usedTokens: 150,
  6866. maxTokens: 200_000,
  6867. });
  6868. projection.applyEvent(
  6869. log.push(SessionEventType.ModelSelected, {
  6870. modelSelection: {
  6871. providerId: "deepseek",
  6872. modelId: "deepseek-v4-flash",
  6873. options: { reasoningLevel: "max" },
  6874. },
  6875. supportedThoughtLevels: ["max", "high", "nothink"],
  6876. }),
  6877. );
  6878. // 旧持久化事件没有 contextWindow,重放时保持既有分母,不能清零。
  6879. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6880. usedTokens: 150,
  6881. maxTokens: 200_000,
  6882. });
  6883. projection.applyEvent(
  6884. log.push(SessionEventType.ModelSelected, {
  6885. modelSelection: {
  6886. providerId: "deepseek",
  6887. modelId: "deepseek-v4-flash",
  6888. options: { reasoningLevel: "max" },
  6889. },
  6890. contextWindow: 1_000_000,
  6891. supportedThoughtLevels: ["max", "high", "nothink"],
  6892. }),
  6893. );
  6894. // 修复目标:模型切换事件本身就是 runtime 新能力的权威提交点;不等下一轮发送完成。
  6895. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6896. usedTokens: 150,
  6897. maxTokens: 1_000_000,
  6898. });
  6899. projection.applyEvent(
  6900. log.push(
  6901. SessionEventType.ModelComplete,
  6902. {
  6903. content: "next",
  6904. stopReason: "end_turn",
  6905. querySource: "main_turn",
  6906. usage: { inputTokens: 160, outputTokens: 40 },
  6907. },
  6908. { turnId: "turn-2" },
  6909. ),
  6910. );
  6911. // 后续旧 adapter 未携带 contextWindow 时,也必须回退到刚切换后的新窗口。
  6912. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6913. usedTokens: 200,
  6914. maxTokens: 1_000_000,
  6915. });
  6916. });
  6917. it("A/B:清除 context window 后持续隐藏分母并在容量恢复时保留最新已用量", () => {
  6918. const log = new EventLog();
  6919. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6920. log.push(
  6921. SessionEventType.ModelComplete,
  6922. {
  6923. content: "before clear",
  6924. stopReason: "end_turn",
  6925. querySource: "main_turn",
  6926. contextWindow: 200_000,
  6927. usage: { inputTokens: 120, outputTokens: 30 },
  6928. },
  6929. { turnId: "turn-1" },
  6930. );
  6931. const { projection } = runAll(log.events);
  6932. projection.applyEvent(
  6933. log.push(SessionEventType.ModelSelected, {
  6934. modelSelection: { providerId: "custom", modelId: "unknown-context-model" },
  6935. contextWindow: null,
  6936. }),
  6937. );
  6938. expect(projection.getSnapshot().usage.contextWindow).toBeNull();
  6939. projection.applyEvent(
  6940. log.push(
  6941. SessionEventType.ModelComplete,
  6942. {
  6943. content: "while unknown",
  6944. stopReason: "end_turn",
  6945. querySource: "main_turn",
  6946. usage: { inputTokens: 160, outputTokens: 40 },
  6947. },
  6948. { turnId: "turn-2" },
  6949. ),
  6950. );
  6951. expect(projection.getSnapshot().usage.contextWindow).toBeNull();
  6952. expect(projection.getSnapshot().usage.cumulative).toMatchObject({
  6953. inputTokens: 280,
  6954. outputTokens: 70,
  6955. });
  6956. projection.applyEvent(
  6957. log.push(SessionEventType.ModelSelected, {
  6958. modelSelection: { providerId: "custom", modelId: "unknown-context-model" },
  6959. contextWindow: 1_000_000,
  6960. }),
  6961. );
  6962. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6963. usedTokens: 200,
  6964. maxTokens: 1_000_000,
  6965. });
  6966. });
  6967. it("A/B:显式清除窗口后 hydration seed 只恢复用量而不覆盖容量", () => {
  6968. const log = new EventLog();
  6969. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6970. log.push(SessionEventType.ModelSelected, {
  6971. modelSelection: { providerId: "custom", modelId: "unknown-context-model" },
  6972. contextWindow: null,
  6973. });
  6974. const { projection } = runAll(log.events);
  6975. projection.seedUsage({
  6976. contextWindow: {
  6977. usedTokens: 999,
  6978. maxTokens: 200_000,
  6979. autoCompactThresholdTokens: null,
  6980. },
  6981. cumulative: {
  6982. inputTokens: 700,
  6983. outputTokens: 50,
  6984. cacheReadTokens: 20,
  6985. cacheWriteTokens: 10,
  6986. },
  6987. });
  6988. expect(projection.getSnapshot().usage.contextWindow).toBeNull();
  6989. expect(projection.getSnapshot().usage.cumulative).toEqual({
  6990. inputTokens: 700,
  6991. outputTokens: 50,
  6992. cacheReadTokens: 20,
  6993. cacheWriteTokens: 10,
  6994. });
  6995. projection.applyEvent(
  6996. log.push(SessionEventType.ModelSelected, {
  6997. modelSelection: { providerId: "custom", modelId: "unknown-context-model" },
  6998. contextWindow: 1_000_000,
  6999. }),
  7000. );
  7001. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  7002. usedTokens: 999,
  7003. maxTokens: 1_000_000,
  7004. });
  7005. });
  7006. it("Todo123: 未知容量种子保留用量,后续容量恢复不归零", () => {
  7007. const log = new EventLog();
  7008. log.push(SessionEventType.SessionCreated, { mode: "default" });
  7009. const { projection } = runAll(log.events);
  7010. projection.seedUsage({
  7011. contextWindow: { usedTokens: 29908, maxTokens: null, autoCompactThresholdTokens: null },
  7012. });
  7013. expect(projection.getSnapshot().usage.contextWindow).toBeNull();
  7014. projection.applyEvent(
  7015. log.push(SessionEventType.ModelSelected, {
  7016. modelSelection: { providerId: "glm", modelId: "GLM-5.3-Flash" },
  7017. contextWindow: 1_000_000,
  7018. }),
  7019. );
  7020. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  7021. usedTokens: 29908,
  7022. maxTokens: 1_000_000,
  7023. });
  7024. });
  7025. it("Todo123: 未知容量期间真实用量优先,迟到恢复种子不能覆盖", () => {
  7026. const log = new EventLog();
  7027. log.push(SessionEventType.SessionCreated, { mode: "default" });
  7028. log.push(SessionEventType.ModelSelected, {
  7029. modelSelection: { providerId: "glm", modelId: "GLM-5.3-Flash" },
  7030. contextWindow: null,
  7031. });
  7032. log.push(SessionEventType.ModelComplete, {
  7033. content: "",
  7034. stopReason: "end_turn",
  7035. querySource: "main_turn",
  7036. usage: { inputTokens: 700, outputTokens: 30 },
  7037. });
  7038. const { projection } = runAll(log.events);
  7039. projection.seedUsage({
  7040. contextWindow: { usedTokens: 29908, maxTokens: null, autoCompactThresholdTokens: null },
  7041. });
  7042. projection.applyEvent(
  7043. log.push(SessionEventType.ModelSelected, {
  7044. modelSelection: { providerId: "glm", modelId: "GLM-5.3-Flash" },
  7045. contextWindow: 1_000_000,
  7046. }),
  7047. );
  7048. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  7049. usedTokens: 730,
  7050. maxTokens: 1_000_000,
  7051. });
  7052. });
  7053. // ── M4:cancelBackgroundWork(BackgroundTask* → backgroundWorks 投影)──
  7054. it("A/B:BackgroundTaskStarted → backgroundWorks 出现 running 项,Completed(cancelled) → cancelled", () => {
  7055. const log = new EventLog();
  7056. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7057. log.push(SessionEventType.BackgroundTaskStarted, {
  7058. taskId: "bg-1",
  7059. toolName: "Bash",
  7060. command: "sleep 100",
  7061. description: "长任务",
  7062. status: "running",
  7063. });
  7064. let snapshot = runAll(log.events).projection.getSnapshot();
  7065. expect(snapshot.backgroundWorks).toHaveLength(1);
  7066. expect(snapshot.backgroundWorks[0]!.workId).toBe("bg-1");
  7067. expect(snapshot.backgroundWorks[0]!.kind).toBe("bash");
  7068. expect(snapshot.backgroundWorks[0]!.title).toBe("长任务");
  7069. expect(snapshot.backgroundWorks[0]!.status).toBe("running");
  7070. // 取消 → cancelled
  7071. log.push(SessionEventType.BackgroundTaskCompleted, {
  7072. taskId: "bg-1",
  7073. toolName: "Bash",
  7074. status: "cancelled",
  7075. });
  7076. snapshot = runAll(log.events).projection.getSnapshot();
  7077. expect(snapshot.backgroundWorks).toHaveLength(1);
  7078. expect(snapshot.backgroundWorks[0]!.status).toBe("cancelled");
  7079. });
  7080. it("A/B:真实 Agent 后台事件使用 runtime taskKind,且旧 Agent 事件兼容为 subagent", () => {
  7081. const log = new EventLog();
  7082. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7083. log.push(SessionEventType.BackgroundTaskStarted, {
  7084. taskId: "bg-2",
  7085. toolName: "Agent",
  7086. taskKind: "subagent",
  7087. childSessionId: "sess_child_bg_2",
  7088. description: "子代理",
  7089. status: "running",
  7090. cancellable: true,
  7091. });
  7092. let snapshot = runAll(log.events).projection.getSnapshot();
  7093. expect(snapshot.backgroundWorks[0]).toMatchObject({
  7094. kind: "subagent",
  7095. childSessionId: "sess_child_bg_2",
  7096. cancellable: true,
  7097. status: "running",
  7098. title: "子代理",
  7099. });
  7100. log.push(SessionEventType.BackgroundTaskCompleted, {
  7101. taskId: "bg-2",
  7102. toolName: "Agent",
  7103. taskKind: "subagent",
  7104. status: "completed",
  7105. cancellable: false,
  7106. });
  7107. snapshot = runAll(log.events).projection.getSnapshot();
  7108. expect(snapshot.backgroundWorks[0]).toMatchObject({
  7109. kind: "subagent",
  7110. childSessionId: "sess_child_bg_2",
  7111. cancellable: false,
  7112. status: "resultPending",
  7113. });
  7114. const lateIdentity = new EventLog();
  7115. lateIdentity.push(SessionEventType.SessionCreated, {
  7116. mode: "default",
  7117. contextWindow: 200_000,
  7118. });
  7119. lateIdentity.push(SessionEventType.BackgroundTaskStarted, {
  7120. taskId: "late-child-id",
  7121. toolName: "Agent",
  7122. taskKind: "subagent",
  7123. description: "晚到身份",
  7124. status: "running",
  7125. cancellable: true,
  7126. });
  7127. lateIdentity.push(SessionEventType.BackgroundTaskUpdated, {
  7128. taskId: "late-child-id",
  7129. toolName: "Agent",
  7130. taskKind: "subagent",
  7131. childSessionId: "sess_child_late",
  7132. description: "晚到身份",
  7133. status: "running",
  7134. cancellable: true,
  7135. });
  7136. expect(runAll(lateIdentity.events).projection.getSnapshot().backgroundWorks[0]).toMatchObject({
  7137. childSessionId: "sess_child_late",
  7138. status: "running",
  7139. });
  7140. const legacy = new EventLog();
  7141. legacy.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7142. legacy.push(SessionEventType.BackgroundTaskStarted, {
  7143. taskId: "legacy-agent",
  7144. toolName: "Agent",
  7145. description: "旧子代理",
  7146. status: "running",
  7147. });
  7148. legacy.push(SessionEventType.BackgroundTaskUpdated, {
  7149. taskId: "legacy-agent",
  7150. status: "running",
  7151. });
  7152. legacy.push(SessionEventType.BackgroundTaskCompleted, {
  7153. taskId: "legacy-agent",
  7154. status: "completed",
  7155. });
  7156. expect(runAll(legacy.events).projection.getSnapshot().backgroundWorks[0]).toMatchObject({
  7157. kind: "subagent",
  7158. status: "resultPending",
  7159. title: "旧子代理",
  7160. });
  7161. const explicit = new EventLog();
  7162. explicit.push(SessionEventType.SessionCreated, {
  7163. mode: "default",
  7164. contextWindow: 200_000,
  7165. });
  7166. explicit.push(SessionEventType.BackgroundTaskStarted, {
  7167. taskId: "explicit-bash",
  7168. // taskKind 是新事实;即使旧 toolName 数据矛盾也不得反向覆盖。
  7169. taskKind: "bash",
  7170. toolName: "Agent",
  7171. description: "显式进程",
  7172. status: "running",
  7173. });
  7174. expect(runAll(explicit.events).projection.getSnapshot().backgroundWorks[0]!.kind).toBe("bash");
  7175. });
  7176. // ── M4:RewindTriggered → row.removed(editUserQuery/retryTurn 的 live 截断)──
  7177. it("D/G:RewindTriggered(targetMessageId) 从目标 turn 首行整段移除", () => {
  7178. const log = new EventLog();
  7179. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7180. // turn1
  7181. log.push(
  7182. SessionEventType.TurnStarted,
  7183. { turnNumber: 1, input: "第一问", messageId: "msg-u1" },
  7184. { turnId: "t1" },
  7185. );
  7186. log.push(
  7187. SessionEventType.ModelStreaming,
  7188. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  7189. { turnId: "t1" },
  7190. );
  7191. log.push(
  7192. SessionEventType.ModelStreaming,
  7193. { kind: "text_delta", delta: "第一答", done: false, assistantMessageId: "msg-a1" },
  7194. { turnId: "t1" },
  7195. );
  7196. log.push(
  7197. SessionEventType.ModelStreaming,
  7198. { kind: "text_end", delta: "", done: false },
  7199. { turnId: "t1" },
  7200. );
  7201. log.push(
  7202. SessionEventType.TurnComplete,
  7203. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  7204. { turnId: "t1" },
  7205. );
  7206. // turn2
  7207. log.push(
  7208. SessionEventType.TurnStarted,
  7209. { turnNumber: 2, input: "第二问", messageId: "msg-u2" },
  7210. { turnId: "t2" },
  7211. );
  7212. log.push(
  7213. SessionEventType.ModelStreaming,
  7214. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a2" },
  7215. { turnId: "t2" },
  7216. );
  7217. log.push(
  7218. SessionEventType.ModelStreaming,
  7219. { kind: "text_delta", delta: "第二答", done: false, assistantMessageId: "msg-a2" },
  7220. { turnId: "t2" },
  7221. );
  7222. log.push(
  7223. SessionEventType.ModelStreaming,
  7224. { kind: "text_end", delta: "", done: false },
  7225. { turnId: "t2" },
  7226. );
  7227. log.push(
  7228. SessionEventType.TurnComplete,
  7229. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  7230. { turnId: "t2" },
  7231. );
  7232. // rewind 到 turn2 的 assistant 消息 → 整个 turn2 被移除。
  7233. // createdMessageId = applied 语义(unavailable/workspace 回滚不带,投影必须忽略)。
  7234. log.push(SessionEventType.RewindTriggered, {
  7235. targetMessageId: "msg-a2",
  7236. scope: "conversation",
  7237. createdMessageId: "msg-rewind-notice",
  7238. });
  7239. const { projection } = runAll(log.events);
  7240. const texts = projection
  7241. .getSnapshot()
  7242. .rows.window.filter((r) => r.kind === "userInput" || r.kind === "assistantText")
  7243. .map((r) => (r.kind === "userInput" || r.kind === "assistantText" ? r.text : ""));
  7244. // turn1 保留,turn2 整段被移除。
  7245. expect(texts).toEqual(["第一问", "第一答"]);
  7246. // 被移除的用户实体不可再解析为编辑目标。
  7247. expect(projection.resolveEditTargetByEntityId("msg-u2")).toBeNull();
  7248. expect(projection.resolveEditTargetByEntityId("msg-u1")).toMatchObject({
  7249. entityId: "msg-u1",
  7250. transcriptMessageId: "msg-u1",
  7251. });
  7252. });
  7253. it("PV4-10 回归:首轮 edit rewind 后分页首行切换到新 active branch", () => {
  7254. const log = new EventLog();
  7255. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7256. log.push(
  7257. SessionEventType.TurnStarted,
  7258. { turnNumber: 1, input: "你好", messageId: "msg-u1" },
  7259. { turnId: "t1" },
  7260. );
  7261. log.push(
  7262. SessionEventType.ModelStreaming,
  7263. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  7264. { turnId: "t1" },
  7265. );
  7266. log.push(
  7267. SessionEventType.ModelStreaming,
  7268. { kind: "text_delta", delta: "旧回答", done: false, assistantMessageId: "msg-a1" },
  7269. { turnId: "t1" },
  7270. );
  7271. log.push(
  7272. SessionEventType.ModelStreaming,
  7273. { kind: "text_end", delta: "", done: false },
  7274. { turnId: "t1" },
  7275. );
  7276. log.push(
  7277. SessionEventType.TurnComplete,
  7278. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  7279. { turnId: "t1" },
  7280. );
  7281. const original = runAll(log.events).projection.getSnapshot();
  7282. const originalMaxRowId = Math.max(...original.rows.window.map((row) => row.rowId));
  7283. log.push(SessionEventType.RewindTriggered, {
  7284. targetMessageId: "msg-u1",
  7285. scope: "conversation",
  7286. branchCutAfterMessageId: "msg-a1",
  7287. branchGeneration: 1,
  7288. });
  7289. const rewound = runAll(log.events).projection.getSnapshot();
  7290. expect(rewound.rows).toEqual({ window: [], totalCount: 0, firstRowId: null });
  7291. log.push(
  7292. SessionEventType.TurnStarted,
  7293. { turnNumber: 2, input: "你是谁", messageId: "msg-u2" },
  7294. { turnId: "t2" },
  7295. );
  7296. const rerun = runAll(log.events).projection.getSnapshot();
  7297. const newFirstRow = rerun.rows.window[0]!;
  7298. expect(newFirstRow.rowId).toBeGreaterThan(originalMaxRowId);
  7299. expect(rerun.rows.firstRowId).toBe(newFirstRow.rowId);
  7300. expect(rerun.rows.totalCount).toBe(rerun.rows.window.length);
  7301. });
  7302. it("D:getTurnRewindAnchor(user 行 rowId) → 同 turn 的 assistant messageId", () => {
  7303. const log = new EventLog();
  7304. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7305. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "问" }, { turnId: "t1" });
  7306. log.push(
  7307. SessionEventType.ModelStreaming,
  7308. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  7309. { turnId: "t1" },
  7310. );
  7311. log.push(
  7312. SessionEventType.ModelStreaming,
  7313. { kind: "text_delta", delta: "答", done: false, assistantMessageId: "msg-a1" },
  7314. { turnId: "t1" },
  7315. );
  7316. log.push(
  7317. SessionEventType.ModelStreaming,
  7318. { kind: "text_end", delta: "", done: false },
  7319. { turnId: "t1" },
  7320. );
  7321. const { projection } = runAll(log.events);
  7322. const userRow = projection.getSnapshot().rows.window.find((r) => r.kind === "userInput");
  7323. expect(userRow).toBeDefined();
  7324. // user 行自身无 messageId,但同 turn 的 assistant messageId 作 rewind 锚点。
  7325. expect(projection.getMessageIdForRow(userRow!.rowId)).toBeNull();
  7326. expect(projection.getTurnRewindAnchor(userRow!.rowId)).toBe("msg-a1");
  7327. });
  7328. it("D/G:RewindTriggered 目标 messageId 无法反查(user 行无 messageId)→ 不误删", () => {
  7329. const log = new EventLog();
  7330. basicTurnEvents(log);
  7331. const before = runAll(log.events).projection.getSnapshot().rows.window.length;
  7332. log.push(SessionEventType.RewindTriggered, {
  7333. targetMessageId: "unknown-msg",
  7334. scope: "conversation",
  7335. createdMessageId: "msg-rewind-notice",
  7336. });
  7337. const after = runAll(log.events).projection.getSnapshot().rows.window.length;
  7338. expect(after).toBe(before);
  7339. });
  7340. it("D/E09 回归:unavailable rewind(无 createdMessageId)与 workspace 回滚不得截断 live 行", () => {
  7341. // Bugfix 回归(2026-07-06 case catalog 战役):finishUnavailable 也发 RewindTriggered,
  7342. // 投影曾不加区分地截断 live 行——store/模型上下文却保留旧分支(假截断),
  7343. // fork child / 刷新 hydration 随后把旧分支复活(E09 失败形态)。
  7344. const log = new EventLog();
  7345. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7346. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "问" }, { turnId: "t1" });
  7347. log.push(
  7348. SessionEventType.ModelStreaming,
  7349. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  7350. { turnId: "t1" },
  7351. );
  7352. log.push(
  7353. SessionEventType.ModelStreaming,
  7354. { kind: "text_delta", delta: "答", done: false, assistantMessageId: "msg-a1" },
  7355. { turnId: "t1" },
  7356. );
  7357. log.push(
  7358. SessionEventType.ModelStreaming,
  7359. { kind: "text_end", delta: "", done: false },
  7360. { turnId: "t1" },
  7361. );
  7362. log.push(
  7363. SessionEventType.TurnComplete,
  7364. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  7365. { turnId: "t1" },
  7366. );
  7367. const beforeRows = runAll(log.events).projection.getSnapshot().rows.window.length;
  7368. expect(beforeRows).toBeGreaterThan(0);
  7369. // unavailable conversation rewind(无 createdMessageId)
  7370. log.push(SessionEventType.RewindTriggered, {
  7371. targetMessageId: "msg-a1",
  7372. scope: "conversation",
  7373. strategy: "unavailable",
  7374. reason: "target_message_is_not_user_prompt",
  7375. });
  7376. // workspace 文件回滚(带 createdMessageId 但 scope=workspace)
  7377. log.push(SessionEventType.RewindTriggered, {
  7378. targetMessageId: "msg-a1",
  7379. scope: "workspace",
  7380. createdMessageId: "msg-ws-notice",
  7381. });
  7382. const after = runAll(log.events).projection.getSnapshot().rows.window.length;
  7383. expect(after).toBe(beforeRows);
  7384. });
  7385. it("O10:ModelComplete.fileChanges 更新 turn header 摘要", () => {
  7386. const log = new EventLog();
  7387. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7388. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "改文件" }, { turnId: "t1" });
  7389. log.push(
  7390. SessionEventType.ModelComplete,
  7391. {
  7392. content: "done",
  7393. stopReason: "stop",
  7394. querySource: "main_turn",
  7395. contextWindow: 200_000,
  7396. usage: { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 },
  7397. fileChanges: {
  7398. files: 1,
  7399. additions: 2,
  7400. deletions: 1,
  7401. items: [{ path: "/work/src/demo.ts", additions: 2, deletions: 1, writeCount: 2 }],
  7402. },
  7403. },
  7404. { turnId: "t1" },
  7405. );
  7406. log.push(
  7407. SessionEventType.TurnComplete,
  7408. { response: "done", tokenCount: 2, toolCallCount: 0, duration: 1, resultType: "success" },
  7409. { turnId: "t1" },
  7410. );
  7411. const { projection } = runAll(log.events);
  7412. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  7413. expect(header).toMatchObject({
  7414. kind: "turnHeader",
  7415. fileChanges: {
  7416. additions: 2,
  7417. deletions: 1,
  7418. files: 1,
  7419. state: "active",
  7420. },
  7421. actions: { canRewindFiles: true },
  7422. });
  7423. const target = { rowId: header!.rowId, entityId: header!.entityId! };
  7424. expect(projection.resolveRowActionTarget(target, "applyFileRewind")).toMatchObject({
  7425. ok: true,
  7426. });
  7427. projection.applyEvent(
  7428. new EventLog().push(SessionEventType.CompactStarted, {
  7429. operationId: "compact-files",
  7430. messageId: "compact-files-message",
  7431. status: "started",
  7432. trigger: "manual",
  7433. display: "separator",
  7434. }),
  7435. );
  7436. const lockedHeader = projection
  7437. .getSnapshot()
  7438. .rows.window.find((row) => row.rowId === header!.rowId)!;
  7439. expect(lockedHeader.actions?.canRewindFiles).toBeUndefined();
  7440. expect(projection.resolveRowActionTarget(target, "applyFileRewind")).toEqual({
  7441. ok: false,
  7442. status: "rejected",
  7443. reasonCode: "guard.actionUnavailable",
  7444. });
  7445. });
  7446. it("O10:subagent ModelComplete 只更新 child turn 文件摘要,不覆盖 usage", () => {
  7447. const log = new EventLog();
  7448. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7449. log.push(
  7450. SessionEventType.TurnStarted,
  7451. { turnNumber: 1, input: "子会话改文件" },
  7452. { turnId: "t1" },
  7453. );
  7454. log.push(
  7455. SessionEventType.ModelComplete,
  7456. {
  7457. content: "done",
  7458. stopReason: "stop",
  7459. querySource: "subagent",
  7460. contextWindow: 999_999,
  7461. usage: { inputTokens: 100, outputTokens: 50, cacheReadTokens: 10, cacheWriteTokens: 5 },
  7462. fileChanges: {
  7463. files: 1,
  7464. additions: 1,
  7465. deletions: 0,
  7466. items: [{ path: "/work/src/child.ts", additions: 1, deletions: 0, writeCount: 1 }],
  7467. },
  7468. },
  7469. { turnId: "t1" },
  7470. );
  7471. log.push(
  7472. SessionEventType.TurnComplete,
  7473. { response: "done", tokenCount: 150, toolCallCount: 1, duration: 1, resultType: "success" },
  7474. { turnId: "t1" },
  7475. );
  7476. const { projection } = runAll(log.events);
  7477. const snapshot = projection.getSnapshot();
  7478. const header = snapshot.rows.window.find((row) => row.kind === "turnHeader");
  7479. expect(header).toMatchObject({
  7480. kind: "turnHeader",
  7481. fileChanges: {
  7482. additions: 1,
  7483. deletions: 0,
  7484. files: 1,
  7485. state: "active",
  7486. },
  7487. actions: { canRewindFiles: true },
  7488. });
  7489. expect(snapshot.usage.cumulative).toEqual({
  7490. inputTokens: 0,
  7491. outputTokens: 0,
  7492. cacheReadTokens: 0,
  7493. cacheWriteTokens: 0,
  7494. });
  7495. });
  7496. it("O10:普通 TurnStarted 的 user messageId 进入同轮文件摘要锚点", () => {
  7497. const log = new EventLog();
  7498. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7499. log.push(
  7500. SessionEventType.TurnStarted,
  7501. { turnNumber: 1, input: "改文件", messageId: "msg-user-1" },
  7502. { turnId: "t1" },
  7503. );
  7504. const { projection } = runAll(log.events);
  7505. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  7506. expect(header).toBeDefined();
  7507. expect(projection.getMessageIdsForTurnRow(header!.rowId)).toContain("msg-user-1");
  7508. });
  7509. it("O12:workspace 文件撤销只标记 fileChanges.reverted,不移除聊天行", () => {
  7510. const log = new EventLog();
  7511. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7512. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "改文件" }, { turnId: "t1" });
  7513. log.push(
  7514. SessionEventType.ModelStreaming,
  7515. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  7516. { turnId: "t1" },
  7517. );
  7518. log.push(
  7519. SessionEventType.ModelStreaming,
  7520. { kind: "text_delta", delta: "已改", done: false, assistantMessageId: "msg-a1" },
  7521. { turnId: "t1" },
  7522. );
  7523. log.push(
  7524. SessionEventType.ModelStreaming,
  7525. { kind: "text_end", delta: "", done: false },
  7526. { turnId: "t1" },
  7527. );
  7528. log.push(
  7529. SessionEventType.ModelComplete,
  7530. {
  7531. content: "已改",
  7532. stopReason: "stop",
  7533. querySource: "main_turn",
  7534. contextWindow: 200_000,
  7535. usage: { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 },
  7536. fileChanges: {
  7537. files: 1,
  7538. additions: 2,
  7539. deletions: 1,
  7540. items: [{ path: "/work/src/demo.ts", additions: 2, deletions: 1, writeCount: 1 }],
  7541. },
  7542. },
  7543. { turnId: "t1" },
  7544. );
  7545. log.push(
  7546. SessionEventType.TurnComplete,
  7547. { response: "已改", tokenCount: 1, toolCallCount: 1, duration: 10, resultType: "success" },
  7548. { turnId: "t1" },
  7549. );
  7550. const before = runAll(log.events).projection.getSnapshot().rows.window;
  7551. log.push(SessionEventType.RewindTriggered, {
  7552. targetMessageId: "msg-a1",
  7553. scope: "workspace",
  7554. reason: "file_summary_rewind",
  7555. });
  7556. const { projection } = runAll(log.events);
  7557. const rows = projection.getSnapshot().rows.window;
  7558. expect(rows).toHaveLength(before.length);
  7559. const header = rows.find((row) => row.kind === "turnHeader");
  7560. expect(header).toMatchObject({
  7561. kind: "turnHeader",
  7562. fileChanges: {
  7563. additions: 2,
  7564. deletions: 1,
  7565. files: 1,
  7566. state: "reverted",
  7567. },
  7568. });
  7569. expect(rows.some((row) => row.kind === "assistantText" && row.text === "已改")).toBe(true);
  7570. });
  7571. });
  7572. // ── M5④ 附件渲染:TurnStarted.attachments → userInput row.attachments ──
  7573. describe("userInput 附件投影(M5④)", () => {
  7574. it("TurnStarted 携带附件元信息 → row.attachments 保真映射且 schema 合法", () => {
  7575. const log = new EventLog();
  7576. log.push(SessionEventType.SessionCreated, {
  7577. mode: "default",
  7578. contextWindow: 200_000,
  7579. });
  7580. log.push(
  7581. SessionEventType.TurnStarted,
  7582. {
  7583. turnNumber: 1,
  7584. input: "看看这张图",
  7585. inputId: "command-start-now",
  7586. intent: {
  7587. sourceCommandId: "command-start-now",
  7588. queueItemId: "queue_command-start-now",
  7589. clientId: "desktop-client",
  7590. kind: "sendText",
  7591. admissionSeq: 3,
  7592. admittedAt: 100,
  7593. requestedDelivery: "startNow",
  7594. admittedDelivery: "startNow",
  7595. },
  7596. attachments: [
  7597. {
  7598. fileName: "screenshot.png",
  7599. mime: "image/png",
  7600. bytes: 12345,
  7601. ref: "/tmp/screenshot.png",
  7602. },
  7603. // 无稳定引用(data URL 内联):ref 缺省 → 投影生成行内占位。
  7604. { fileName: "notes.md", mime: "text/markdown", bytes: 42 },
  7605. ],
  7606. },
  7607. { turnId: "turn-1" },
  7608. );
  7609. const { projection } = runAll(log.events);
  7610. const snapshot = projection.getSnapshot();
  7611. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  7612. const userInput = snapshot.rows.window.find((row) => row.kind === "userInput");
  7613. expect(userInput).toBeDefined();
  7614. expect(userInput).toMatchObject({
  7615. sourceCommandId: "command-start-now",
  7616. clientId: "desktop-client",
  7617. });
  7618. const attachments = userInput?.kind === "userInput" ? userInput.attachments : undefined;
  7619. expect(attachments).toHaveLength(2);
  7620. expect(attachments?.[0]).toEqual({
  7621. ref: "/tmp/screenshot.png",
  7622. fileName: "screenshot.png",
  7623. mime: "image/png",
  7624. bytes: 12345,
  7625. });
  7626. expect(attachments?.[1]).toMatchObject({
  7627. fileName: "notes.md",
  7628. mime: "text/markdown",
  7629. bytes: 42,
  7630. });
  7631. expect(attachments?.[1]?.ref).toMatch(/^turn-attachment\//);
  7632. });
  7633. it("无附件的 TurnStarted:row 不带 attachments 键(缺省语义)", () => {
  7634. const log = new EventLog();
  7635. basicTurnEvents(log);
  7636. const { projection } = runAll(log.events);
  7637. const userInput = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput");
  7638. expect(userInput?.kind === "userInput" ? "attachments" in userInput : null).toBe(false);
  7639. });
  7640. });
  7641. // R-19(10 §4.2.3):config 种子——投影初值 = runtime 真值,种子不产 delta / 不 bump
  7642. // revision,事件触碰过的字段不接受种子覆盖("最终值以日志为准")。
  7643. // Bug 背景(2026-07-07 v4 桌面首测):初始 config 写死空 provider/model + mode=build,
  7644. // 导致新会话模型选择器显示空、持久化 mode=yolo 时 UI 停在 build 且点 yolo 静默 no-op。
  7645. describe("config 种子(R-19)", () => {
  7646. const SEED = {
  7647. provider: "prov-a",
  7648. model: "model-1",
  7649. thought: "high",
  7650. thoughtLevels: ["high", "max", "nothink"],
  7651. mode: "yolo",
  7652. };
  7653. it("种子填充空初值:config 就位、revision/seq 不动、schema 合法", () => {
  7654. const projection = new ProductProjection("session-1", "epoch-1");
  7655. projection.seedConfig(SEED);
  7656. const snapshot = projection.getSnapshot();
  7657. expect(snapshot.config).toMatchObject({
  7658. provider: "prov-a",
  7659. model: "model-1",
  7660. thought: "high",
  7661. thoughtLevels: ["high", "max", "nothink"],
  7662. mode: "yolo",
  7663. });
  7664. expect(snapshot.revision).toBe(0);
  7665. expect(snapshot.seq).toBe(0);
  7666. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  7667. });
  7668. it("种子后事件覆盖:ModelSelected / SessionModeChanged 的日志值优先", () => {
  7669. const projection = new ProductProjection("session-1", "epoch-1");
  7670. projection.seedConfig(SEED);
  7671. const log = new EventLog();
  7672. log.push(SessionEventType.ModelSelected, {
  7673. modelSelection: {
  7674. providerId: "prov-b",
  7675. modelId: "model-2",
  7676. options: { reasoningLevel: "low" },
  7677. },
  7678. supportedThoughtLevels: ["low", "high"],
  7679. });
  7680. log.push(SessionEventType.SessionModeChanged, {
  7681. mode: "plan",
  7682. previousMode: "yolo",
  7683. source: "command",
  7684. });
  7685. for (const event of log.events) projection.applyEvent(event);
  7686. expect(projection.getSnapshot().config).toMatchObject({
  7687. provider: "prov-b",
  7688. model: "model-2",
  7689. thought: "low",
  7690. thoughtLevels: ["low", "high"],
  7691. mode: "plan",
  7692. });
  7693. projection.seedConfig({ ...SEED, thoughtLevels: ["disabled"] });
  7694. expect(projection.getSnapshot().config.thoughtLevels).toEqual(["low", "high"]);
  7695. });
  7696. it("事件后种子不覆盖:冷恢复重放序在前时日志值保持权威", () => {
  7697. const projection = new ProductProjection("session-1", "epoch-1");
  7698. const log = new EventLog();
  7699. log.push(SessionEventType.ModelSelected, {
  7700. modelSelection: { providerId: "prov-b", modelId: "model-2" },
  7701. });
  7702. log.push(SessionEventType.SessionModeChanged, {
  7703. mode: "plan",
  7704. previousMode: "build",
  7705. source: "tool",
  7706. });
  7707. for (const event of log.events) projection.applyEvent(event);
  7708. projection.seedConfig(SEED);
  7709. expect(projection.getSnapshot().config).toMatchObject({
  7710. provider: "prov-b",
  7711. model: "model-2",
  7712. thoughtLevels: ["high", "max", "nothink"],
  7713. mode: "plan",
  7714. });
  7715. });
  7716. it("分区独立:只有 mode 被事件触碰时,模型区仍接受种子(反之亦然)", () => {
  7717. const projection = new ProductProjection("session-1", "epoch-1");
  7718. const log = new EventLog();
  7719. log.push(SessionEventType.SessionModeChanged, {
  7720. mode: "plan",
  7721. previousMode: "build",
  7722. source: "command",
  7723. });
  7724. for (const event of log.events) projection.applyEvent(event);
  7725. projection.seedConfig(SEED);
  7726. const config = projection.getSnapshot().config;
  7727. // mode 由日志裁决,模型区来自种子(历史会话恢复:resume 已把上次选型写回 runtime)。
  7728. expect(config.mode).toBe("plan");
  7729. expect(config).toMatchObject({
  7730. provider: "prov-a",
  7731. model: "model-1",
  7732. thought: "high",
  7733. thoughtLevels: ["high", "max", "nothink"],
  7734. });
  7735. });
  7736. it("相同种子幂等,明确留空的恢复结果清除旧模型", () => {
  7737. const projection = new ProductProjection("session-1", "epoch-1");
  7738. projection.seedConfig(SEED);
  7739. const first = projection.getSnapshot();
  7740. projection.seedConfig(SEED);
  7741. expect(projection.getSnapshot()).toBe(first);
  7742. // 恢复结果明确留空,不能继续显示历史消息留下的模型。
  7743. projection.seedConfig({ provider: "", model: "", mode: "" });
  7744. expect(projection.getSnapshot().config).toMatchObject({
  7745. provider: "",
  7746. model: "",
  7747. });
  7748. });
  7749. it("分享上下文导入种子只写只读来源元数据,不生成可见对话行", () => {
  7750. const projection = new ProductProjection("session-1", "epoch-1");
  7751. const before = projection.getSnapshot();
  7752. projection.seedSharedContextImport({ title: "筛选近一年收益前10%的偏股混合基金" });
  7753. const snapshot = projection.getSnapshot();
  7754. expect(snapshot.sharedContextImport).toEqual({
  7755. title: "筛选近一年收益前10%的偏股混合基金",
  7756. });
  7757. expect(snapshot.rows.window).toEqual([]);
  7758. expect(snapshot.revision).toBe(before.revision);
  7759. expect(snapshot.seq).toBe(before.seq);
  7760. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  7761. });
  7762. });
  7763. // ── 16-timeline-authority-plan P2:productTurn 切分 / goalVerify 身份与落位 ──
  7764. describe("P2 productTurn 切分(S1/S3/S5)", () => {
  7765. const drainScenario = (delivery: "queue" | "guide") => {
  7766. const log = new EventLog();
  7767. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7768. log.push(
  7769. SessionEventType.TurnStarted,
  7770. { turnNumber: 1, input: "问题一" },
  7771. { turnId: "turn-1" },
  7772. );
  7773. log.push(
  7774. SessionEventType.ModelStreaming,
  7775. { kind: "text_start", delta: "", done: false },
  7776. { turnId: "turn-1" },
  7777. );
  7778. log.push(
  7779. SessionEventType.ModelStreaming,
  7780. { kind: "text_delta", delta: "回答一", done: false },
  7781. { turnId: "turn-1" },
  7782. );
  7783. log.push(
  7784. SessionEventType.ModelStreaming,
  7785. { kind: "text_end", delta: "", done: false },
  7786. { turnId: "turn-1" },
  7787. );
  7788. log.push(
  7789. SessionEventType.TurnSteerQueued,
  7790. {
  7791. pendingInputId: "p-q2",
  7792. input: "问题二",
  7793. inputPreview: "问题二",
  7794. inputSize: 9,
  7795. delivery,
  7796. targetTurnId: "turn-1",
  7797. queueLength: 1,
  7798. },
  7799. { turnId: "turn-1" },
  7800. );
  7801. log.push(
  7802. SessionEventType.TurnSteerDrained,
  7803. {
  7804. pendingInputIds: ["p-q2"],
  7805. injectedMessageIds: ["msg-q2"],
  7806. drainedInputs: [
  7807. {
  7808. pendingInputId: "p-q2",
  7809. messageId: "msg-q2",
  7810. text: "问题二",
  7811. delivery,
  7812. intent: {
  7813. sourceCommandId: "command-q2",
  7814. queueItemId: "p-q2",
  7815. clientId: "desktop-continuous",
  7816. kind: delivery === "guide" ? "sendGoalCommand" : "sendText",
  7817. text: "问题二",
  7818. admissionSeq: 2,
  7819. admittedAt: 1_700_000_006_000,
  7820. requestedDelivery: "auto",
  7821. admittedDelivery: delivery,
  7822. fallbackReasonCode: "runtime.turnBusy",
  7823. attachmentRefs: [
  7824. {
  7825. ref: "artifact://q2",
  7826. fileName: "q2.txt",
  7827. mime: "text/plain",
  7828. bytes: 3,
  7829. },
  7830. ],
  7831. provenance: {
  7832. sourceCommandId: "command-q2-original",
  7833. queueItemId: "p-q2-original",
  7834. clientId: "desktop-continuous",
  7835. },
  7836. },
  7837. },
  7838. ],
  7839. targetTurnId: "turn-1",
  7840. },
  7841. { turnId: "turn-1" },
  7842. );
  7843. log.push(
  7844. SessionEventType.ModelStreaming,
  7845. { kind: "text_start", delta: "", done: false },
  7846. { turnId: "turn-1" },
  7847. );
  7848. log.push(
  7849. SessionEventType.ModelStreaming,
  7850. { kind: "text_delta", delta: "回答二", done: false },
  7851. { turnId: "turn-1" },
  7852. );
  7853. log.push(
  7854. SessionEventType.ModelStreaming,
  7855. { kind: "text_end", delta: "", done: false },
  7856. { turnId: "turn-1" },
  7857. );
  7858. log.push(
  7859. SessionEventType.TurnComplete,
  7860. { response: "", tokenCount: 0, toolCallCount: 0, duration: 9000, resultType: "success" },
  7861. { turnId: "turn-1" },
  7862. );
  7863. return runAll(log.events);
  7864. };
  7865. it("QD-node:queue drain 切新 productTurn,两段回复都可见、工时按边界拆分(Case A 根修)", () => {
  7866. const { projection } = drainScenario("queue");
  7867. const snapshot = projection.getSnapshot();
  7868. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  7869. const rows = snapshot.rows.window;
  7870. // 两个 turnHeader:首轮 legacy runtime id 与 promoted user messageId(稳定 productTurn)。
  7871. const headers = rows.filter((row) => row.kind === "turnHeader");
  7872. expect(headers.map((row) => row.turnId)).toEqual(["turn-1", "msg-q2"]);
  7873. // 第一段 header 在 drain 边界收口:activeMs = drain(7s) - start(2s)。
  7874. expect(headers[0]).toMatchObject({ state: "completedSuccess", activeMs: 5000 });
  7875. // 第二段 header 在 TurnComplete 收口:activeMs = complete(11s) - drain(7s),
  7876. // 不再是整段 runtime duration(9000)。
  7877. expect(headers[1]).toMatchObject({ state: "completedSuccess", activeMs: 4000 });
  7878. // 两段 assistant 正文都在,各归自己的 productTurn——A1 不再被折进上一轮 history。
  7879. const assistantRows = rows.filter((row) => row.kind === "assistantText");
  7880. expect(
  7881. assistantRows.map((row) => [row.turnId, row.kind === "assistantText" ? row.text : ""]),
  7882. ).toEqual([
  7883. ["turn-1", "回答一"],
  7884. ["msg-q2", "回答二"],
  7885. ]);
  7886. // drained user 行归新 productTurn,并原子登记 message/entity/edit target。
  7887. const drainedUser = rows.find((row) => row.kind === "userInput" && row.text === "问题二");
  7888. expect(drainedUser?.turnId).toBe("msg-q2");
  7889. expect(projection.getMessageIdForRow(drainedUser!.rowId)).toBe("msg-q2");
  7890. expect(projection.getEntityIdForRow(drainedUser!.rowId)).toBe("msg-q2");
  7891. expect(drainedUser?.actions).toMatchObject({ canEdit: true, editDisposition: "rewind" });
  7892. expect(
  7893. projection.resolveRowActionTarget(
  7894. { rowId: drainedUser!.rowId, entityId: drainedUser!.entityId },
  7895. "editUserQuery",
  7896. ),
  7897. ).toMatchObject({
  7898. ok: true,
  7899. editTarget: {
  7900. entityId: "msg-q2",
  7901. productTurnId: "msg-q2",
  7902. transcriptMessageId: "msg-q2",
  7903. intent: {
  7904. kind: "sendText",
  7905. text: "问题二",
  7906. sourceCommandId: "command-q2",
  7907. queueItemId: "p-q2",
  7908. clientId: "desktop-continuous",
  7909. admissionSeq: 2,
  7910. admittedAt: 1_700_000_006_000,
  7911. requestedDelivery: "auto",
  7912. admittedDelivery: "queue",
  7913. fallbackReasonCode: "runtime.turnBusy",
  7914. attachments: [
  7915. {
  7916. ref: "artifact://q2",
  7917. fileName: "q2.txt",
  7918. mime: "text/plain",
  7919. bytes: 3,
  7920. },
  7921. ],
  7922. provenance: {
  7923. sourceCommandId: "command-q2-original",
  7924. queueItemId: "p-q2-original",
  7925. clientId: "desktop-continuous",
  7926. },
  7927. },
  7928. },
  7929. });
  7930. const coldLog = new EventLog();
  7931. coldLog.push(
  7932. SessionEventType.TurnStarted,
  7933. { turnNumber: 2, input: "问题二", messageId: "msg-q2" },
  7934. { turnId: "hydrate-turn-2" },
  7935. );
  7936. const coldUser = runAll(coldLog.events)
  7937. .projection.getSnapshot()
  7938. .rows.window.find((row) => row.kind === "userInput");
  7939. // 同一 promoted user transcript 在 live drain 与 cold TurnStarted 中使用同一 productTurnId。
  7940. expect(coldUser?.turnId).toBe(drainedUser?.turnId);
  7941. expect(snapshot.queue.items).toEqual([]);
  7942. });
  7943. it("P06:guide steer 内联不切轮,但 accepted guide 开启独立可恢复工时段", () => {
  7944. const { projection } = drainScenario("guide");
  7945. const snapshot = projection.getSnapshot();
  7946. const rows = snapshot.rows.window;
  7947. const headers = rows.filter((row) => row.kind === "turnHeader");
  7948. expect(headers.map((row) => row.turnId)).toEqual(["turn-1"]);
  7949. expect(headers[0]).toMatchObject({
  7950. state: "completedSuccess",
  7951. activeMs: 9000,
  7952. workSegments: [
  7953. {
  7954. segmentId: "turn-1:initial",
  7955. startedAt: 1_700_000_002_000,
  7956. endedAt: 1_700_000_007_000,
  7957. activeMs: 5000,
  7958. },
  7959. {
  7960. segmentId: "msg-q2",
  7961. triggerEntityId: "msg-q2",
  7962. startedAt: 1_700_000_007_000,
  7963. endedAt: 1_700_000_011_000,
  7964. activeMs: 4000,
  7965. },
  7966. ],
  7967. });
  7968. const steerUser = rows.find((row) => row.kind === "userInput" && row.text === "问题二");
  7969. expect(steerUser?.turnId).toBe("turn-1");
  7970. expect(steerUser?.actions).toMatchObject({ canEdit: true, editDisposition: "rewind" });
  7971. expect(
  7972. projection.resolveRowActionTarget(
  7973. { rowId: steerUser!.rowId, entityId: steerUser!.entityId },
  7974. "editUserQuery",
  7975. ),
  7976. ).toMatchObject({
  7977. ok: true,
  7978. editTarget: {
  7979. entityId: "msg-q2",
  7980. productTurnId: "turn-1",
  7981. transcriptMessageId: "msg-q2",
  7982. intent: {
  7983. kind: "sendGoalCommand",
  7984. text: "问题二",
  7985. sourceCommandId: "command-q2",
  7986. queueItemId: "p-q2",
  7987. admittedDelivery: "guide",
  7988. },
  7989. },
  7990. });
  7991. // 内联位置:在 A1 之后、A2 之前。
  7992. const order = rows
  7993. .filter((row) => row.kind === "assistantText" || row.kind === "userInput")
  7994. .map((row) => (row.kind === "assistantText" || row.kind === "userInput" ? row.text : ""));
  7995. expect(order).toEqual(["问题一", "回答一", "问题二", "回答二"]);
  7996. });
  7997. it.each([
  7998. ["一个 drained 事件带两条 guide", true, false],
  7999. ["每条 guide 各一个 drained 事件(冷恢复形态)", false, false],
  8000. ["每条 guide 各一个 drained 事件且逐事件原子发布(live 形态)", false, true],
  8001. ])("M06f:%s时,相邻 guide 共用第一条开启的工作段", (_label, together, atomic) => {
  8002. const log = new EventLog();
  8003. const at = (seconds: number) => ({
  8004. turnId: "turn-1",
  8005. timestampMs: 1_700_000_000_000 + seconds * 1000,
  8006. });
  8007. const text = (delta: string, seconds: number) => {
  8008. log.push(
  8009. SessionEventType.ModelStreaming,
  8010. { kind: "text_start", delta: "", done: false },
  8011. at(seconds),
  8012. );
  8013. log.push(
  8014. SessionEventType.ModelStreaming,
  8015. { kind: "text_delta", delta, done: false },
  8016. at(seconds),
  8017. );
  8018. log.push(
  8019. SessionEventType.ModelStreaming,
  8020. { kind: "text_end", delta: "", done: false },
  8021. at(seconds),
  8022. );
  8023. };
  8024. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 }, at(1));
  8025. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "问题一" }, at(2));
  8026. text("回答一", 3);
  8027. const guides = ["g1", "g2"].map((id) => ({
  8028. pendingInputId: `p-${id}`,
  8029. messageId: `msg-${id}`,
  8030. text: `引导-${id}`,
  8031. delivery: "guide" as const,
  8032. }));
  8033. const drain = (items: typeof guides) =>
  8034. log.push(
  8035. SessionEventType.TurnSteerDrained,
  8036. {
  8037. pendingInputIds: items.map((item) => item.pendingInputId),
  8038. injectedMessageIds: items.map((item) => item.messageId),
  8039. drainedInputs: items,
  8040. targetTurnId: "turn-1",
  8041. },
  8042. at(7),
  8043. );
  8044. if (together) drain(guides);
  8045. else for (const guide of guides) drain([guide]);
  8046. text("回答二", 9);
  8047. log.push(
  8048. SessionEventType.TurnComplete,
  8049. { response: "", tokenCount: 0, toolCallCount: 0, duration: 9000, resultType: "success" },
  8050. at(11),
  8051. );
  8052. const projection = new ProductProjection("session-1", "epoch-1");
  8053. for (const event of log.events) {
  8054. if (atomic) projection.applyEventAtomically(event, () => true);
  8055. else projection.applyEvent(event);
  8056. }
  8057. const rows = projection.getSnapshot().rows.window;
  8058. expect(rows.find((row) => row.kind === "turnHeader")).toMatchObject({
  8059. workSegments: [
  8060. {
  8061. segmentId: "turn-1:initial",
  8062. startedAt: 1_700_000_002_000,
  8063. endedAt: 1_700_000_007_000,
  8064. activeMs: 5000,
  8065. },
  8066. {
  8067. segmentId: "msg-g1",
  8068. triggerEntityId: "msg-g1",
  8069. startedAt: 1_700_000_007_000,
  8070. endedAt: 1_700_000_011_000,
  8071. activeMs: 4000,
  8072. },
  8073. ],
  8074. });
  8075. expect(
  8076. rows
  8077. .filter((row) => row.kind === "userInput" || row.kind === "assistantText")
  8078. .map((row) => (row.kind === "userInput" || row.kind === "assistantText" ? row.text : "")),
  8079. ).toEqual(["问题一", "回答一", "引导-g1", "引导-g2", "回答二"]);
  8080. });
  8081. it("M06f:两次取出之间有一个没有可见行的模型 step 时,后一条 guide 开新工作段", () => {
  8082. const log = new EventLog();
  8083. const at = (seconds: number) => ({
  8084. turnId: "turn-1",
  8085. timestampMs: 1_700_000_000_000 + seconds * 1000,
  8086. });
  8087. const guide = (id: string, seconds: number) =>
  8088. log.push(
  8089. SessionEventType.TurnSteerDrained,
  8090. {
  8091. pendingInputIds: [`p-${id}`],
  8092. injectedMessageIds: [`msg-${id}`],
  8093. drainedInputs: [
  8094. {
  8095. pendingInputId: `p-${id}`,
  8096. messageId: `msg-${id}`,
  8097. text: `引导-${id}`,
  8098. delivery: "guide" as const,
  8099. },
  8100. ],
  8101. targetTurnId: "turn-1",
  8102. },
  8103. at(seconds),
  8104. );
  8105. const stream = (kind: string, delta: string, seconds: number) =>
  8106. log.push(SessionEventType.ModelStreaming, { kind, delta, done: false }, at(seconds));
  8107. const text = (delta: string, seconds: number) => {
  8108. stream("text_start", "", seconds);
  8109. stream("text_delta", delta, seconds);
  8110. stream("text_end", "", seconds);
  8111. };
  8112. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 }, at(1));
  8113. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "问题一" }, at(2));
  8114. text("回答一", 3);
  8115. guide("g1", 5);
  8116. // 这一步只有隐藏内容:没有任何可见行,但它是两次取出之间的模型 step。
  8117. stream("start", "", 6);
  8118. log.push(
  8119. SessionEventType.ModelComplete,
  8120. {
  8121. content: "",
  8122. stopReason: "end_turn",
  8123. querySource: "main_turn",
  8124. toolCallCount: 0,
  8125. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  8126. },
  8127. at(6),
  8128. );
  8129. guide("g2", 7);
  8130. text("回答二", 9);
  8131. log.push(
  8132. SessionEventType.TurnComplete,
  8133. { response: "", tokenCount: 0, toolCallCount: 0, duration: 9000, resultType: "success" },
  8134. at(11),
  8135. );
  8136. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  8137. expect(rows.find((row) => row.kind === "turnHeader")).toMatchObject({
  8138. workSegments: [
  8139. { segmentId: "turn-1:initial", startedAt: 1_700_000_002_000, endedAt: 1_700_000_005_000 },
  8140. {
  8141. segmentId: "msg-g1",
  8142. triggerEntityId: "msg-g1",
  8143. startedAt: 1_700_000_005_000,
  8144. endedAt: 1_700_000_007_000,
  8145. },
  8146. {
  8147. segmentId: "msg-g2",
  8148. triggerEntityId: "msg-g2",
  8149. startedAt: 1_700_000_007_000,
  8150. endedAt: 1_700_000_011_000,
  8151. },
  8152. ],
  8153. });
  8154. });
  8155. it("兼容:旧 runtime 事件(无 drainedInputs/delivery)回退 queue 查表,按 followupMode 兜底切轮", () => {
  8156. const log = new EventLog();
  8157. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  8158. log.push(
  8159. SessionEventType.TurnStarted,
  8160. { turnNumber: 1, input: "问题一" },
  8161. { turnId: "turn-1" },
  8162. );
  8163. log.push(
  8164. SessionEventType.TurnSteerQueued,
  8165. {
  8166. pendingInputId: "p-legacy",
  8167. input: "老事件文本",
  8168. inputPreview: "老事件文本",
  8169. inputSize: 15,
  8170. targetTurnId: "turn-1",
  8171. queueLength: 1,
  8172. },
  8173. { turnId: "turn-1" },
  8174. );
  8175. log.push(
  8176. SessionEventType.TurnSteerDrained,
  8177. {
  8178. pendingInputIds: ["p-legacy"],
  8179. injectedMessageIds: ["msg-legacy"],
  8180. targetTurnId: "turn-1",
  8181. },
  8182. { turnId: "turn-1" },
  8183. );
  8184. const { projection } = runAll(log.events);
  8185. const rows = projection.getSnapshot().rows.window;
  8186. const drained = rows.find((row) => row.kind === "userInput" && row.text === "老事件文本");
  8187. // followupMode 默认 queue → 切轮;旧事件虽无 drainedInputs,injectedMessageIds
  8188. // 仍是 promotion 后的持久 user 身份,因此 product turn 也稳定使用该 messageId。
  8189. expect(drained?.turnId).toBe("msg-legacy");
  8190. expect(projection.getMessageIdForRow(drained!.rowId)).toBe("msg-legacy");
  8191. });
  8192. it("PV4-10 防御:drain 缺持久 messageId 时不暴露无法执行的 edit action", () => {
  8193. const log = new EventLog();
  8194. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  8195. log.push(
  8196. SessionEventType.TurnStarted,
  8197. { turnNumber: 1, input: "问题一" },
  8198. { turnId: "turn-1" },
  8199. );
  8200. log.push(
  8201. SessionEventType.TurnSteerQueued,
  8202. {
  8203. pendingInputId: "p-no-message",
  8204. input: "缺少持久身份",
  8205. inputPreview: "缺少持久身份",
  8206. inputSize: 18,
  8207. targetTurnId: "turn-1",
  8208. queueLength: 1,
  8209. },
  8210. { turnId: "turn-1" },
  8211. );
  8212. log.push(
  8213. SessionEventType.TurnSteerDrained,
  8214. { pendingInputIds: ["p-no-message"], targetTurnId: "turn-1" },
  8215. { turnId: "turn-1" },
  8216. );
  8217. const { projection } = runAll(log.events);
  8218. const drained = projection
  8219. .getSnapshot()
  8220. .rows.window.find((row) => row.kind === "userInput" && row.text === "缺少持久身份");
  8221. expect(drained?.actions?.canEdit).not.toBe(true);
  8222. expect(
  8223. projection.resolveRowActionTarget(
  8224. { rowId: drained!.rowId, entityId: drained!.entityId },
  8225. "editUserQuery",
  8226. ),
  8227. ).toEqual({
  8228. ok: false,
  8229. status: "rejected",
  8230. reasonCode: "guard.actionUnavailable",
  8231. });
  8232. });
  8233. });
  8234. describe("P2 goalVerify 身份与落位(GV-identity / GV-terminal-only / GV-late-anchor)", () => {
  8235. it("同 targetId+iteration 的重试(新 verificationId)复用同一 marker,不长第二个", () => {
  8236. const log = new EventLog();
  8237. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  8238. log.push(SessionEventType.TargetCompletionVerification, {
  8239. targetId: "target-1",
  8240. status: "started",
  8241. verificationId: "attempt-1",
  8242. goalIteration: 1,
  8243. });
  8244. log.push(SessionEventType.TargetCompletionVerification, {
  8245. targetId: "target-1",
  8246. status: "started",
  8247. verificationId: "attempt-2",
  8248. goalIteration: 1,
  8249. });
  8250. log.push(SessionEventType.TargetCompletionVerification, {
  8251. targetId: "target-1",
  8252. status: "completed",
  8253. verificationId: "attempt-2",
  8254. goalIteration: 1,
  8255. verification: { passed: true, reason: "ok" },
  8256. });
  8257. const { projection } = runAll(log.events);
  8258. const markers = projection
  8259. .getSnapshot()
  8260. .rows.window.filter(
  8261. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  8262. );
  8263. expect(markers).toHaveLength(1);
  8264. expect(markers[0]).toMatchObject({ marker: { iteration: 1, outcome: "pass" } });
  8265. });
  8266. it("GV-terminal-only:终态先到(无 started、无 goal 状态)也能创建 boundary", () => {
  8267. const log = new EventLog();
  8268. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  8269. log.push(SessionEventType.TargetCompletionVerification, {
  8270. targetId: "target-1",
  8271. status: "completed",
  8272. verificationId: "only-terminal",
  8273. goalIteration: 3,
  8274. verification: { passed: false, reason: "还差测试" },
  8275. });
  8276. const { projection } = runAll(log.events);
  8277. const marker = projection
  8278. .getSnapshot()
  8279. .rows.window.find((row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify");
  8280. expect(marker).toMatchObject({
  8281. marker: { iteration: 3, outcome: "notSatisfied", detail: "还差测试" },
  8282. });
  8283. });
  8284. it("GV-late-anchor:verify 迟到到下一轮之后,按 anchorTurnId 锚回被验证的轮", () => {
  8285. const log = new EventLog();
  8286. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  8287. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "Q1" }, { turnId: "turn-1" });
  8288. log.push(
  8289. SessionEventType.TurnComplete,
  8290. { response: "", tokenCount: 0, toolCallCount: 0, duration: 100, resultType: "success" },
  8291. { turnId: "turn-1" },
  8292. );
  8293. log.push(SessionEventType.TurnStarted, { turnNumber: 2, input: "Q2" }, { turnId: "turn-2" });
  8294. // 迟到的 verify:事件本身归属 turn-2 期间,但 payload 锚定 turn-1。
  8295. log.push(SessionEventType.TargetCompletionVerification, {
  8296. targetId: "target-1",
  8297. status: "started",
  8298. verificationId: "late-1",
  8299. goalIteration: 1,
  8300. anchorTurnId: "turn-1",
  8301. });
  8302. const { projection } = runAll(log.events);
  8303. const marker = projection
  8304. .getSnapshot()
  8305. .rows.window.find((row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify");
  8306. // UI 按 turnId 分组:锚回 turn-1 而不是落进 turn-2 或 "turn-unknown"。
  8307. expect(marker?.turnId).toBe("turn-1");
  8308. });
  8309. });
  8310. describe("Desktop Hook invocation projection", () => {
  8311. it("keeps the shared Hook event enum aligned with Coding contracts", () => {
  8312. expect(new Set(hookInvocationRowSchema.shape.hookEventName.options)).toEqual(
  8313. new Set(Object.values(HookEventName)),
  8314. );
  8315. });
  8316. const descriptor = {
  8317. clientVisible: true as const,
  8318. sourceKind: "user" as const,
  8319. sourcePath: "/Users/example/.zcode/cli/config.json",
  8320. executionType: "process" as const,
  8321. executionMode: "foreground" as const,
  8322. commandDisplay: "node hooks/check.mjs",
  8323. timeoutMs: 5_000,
  8324. };
  8325. it("HK08/HK10 projects safe Hook summaries into the authoritative real turn", () => {
  8326. const log = new EventLog();
  8327. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1_000 });
  8328. log.push(
  8329. SessionEventType.HookRunStarted,
  8330. {
  8331. descriptor,
  8332. hookEventName: "SessionStart",
  8333. hookIndex: 0,
  8334. hookCount: 1,
  8335. hookInvocationId: "startup-hook",
  8336. hookRunId: "startup-run",
  8337. startedAt: 1_700_000_002_000,
  8338. },
  8339. { turnId: "runtime-turn-before-product-mapping" },
  8340. );
  8341. log.push(
  8342. SessionEventType.HookRunCompleted,
  8343. {
  8344. descriptor,
  8345. durationMs: 10,
  8346. hookEventName: "SessionStart",
  8347. hookIndex: 0,
  8348. hookCount: 1,
  8349. hookInvocationId: "startup-hook",
  8350. hookRunId: "startup-run",
  8351. outcome: "success",
  8352. startedAt: 1_700_000_002_000,
  8353. },
  8354. { turnId: "runtime-turn-before-product-mapping" },
  8355. );
  8356. const beforeTurn = runAll(log.events).projection.getSnapshot();
  8357. expect(beforeTurn.rows.window.some((row) => row.kind === "hookInvocation")).toBe(false);
  8358. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  8359. log.push(
  8360. SessionEventType.HookRunStarted,
  8361. {
  8362. descriptor,
  8363. hookEventName: "PreToolUse",
  8364. hookIndex: 0,
  8365. hookCount: 1,
  8366. hookInvocationId: "tool-hook",
  8367. hookRunId: "tool-run",
  8368. startedAt: 1_700_000_003_000,
  8369. toolCallId: "tool-1",
  8370. toolName: "Write",
  8371. },
  8372. { turnId: "turn-1" },
  8373. );
  8374. log.push(
  8375. SessionEventType.HookRunCompleted,
  8376. {
  8377. descriptor,
  8378. durationMs: 20,
  8379. hookEventName: "PreToolUse",
  8380. hookIndex: 0,
  8381. hookCount: 1,
  8382. hookInvocationId: "tool-hook",
  8383. hookRunId: "tool-run",
  8384. outcome: "success",
  8385. startedAt: 1_700_000_003_000,
  8386. toolCallId: "tool-1",
  8387. toolName: "Write",
  8388. },
  8389. { turnId: "turn-1" },
  8390. );
  8391. const { projection } = runAll(log.events);
  8392. const hookRows = projection
  8393. .getSnapshot()
  8394. .rows.window.filter((row) => row.kind === "hookInvocation");
  8395. expect(hookRows.map((row) => row.turnId)).toEqual(["turn-1", "turn-1"]);
  8396. expect(hookRows[0]).toMatchObject({
  8397. hookEventName: "SessionStart",
  8398. executions: [
  8399. expect.objectContaining({
  8400. didExecute: true,
  8401. displayName: "node · check.mjs",
  8402. sourceKind: "user",
  8403. }),
  8404. ],
  8405. });
  8406. expect(hookRows[1]).toMatchObject({
  8407. hookEventName: "PreToolUse",
  8408. anchorToolCallId: "tool-1",
  8409. executions: [
  8410. expect.objectContaining({
  8411. didExecute: true,
  8412. displayName: "node · check.mjs",
  8413. sourceKind: "user",
  8414. toolName: "Write",
  8415. }),
  8416. ],
  8417. });
  8418. expect(JSON.stringify(hookRows)).not.toMatch(/commandDisplay|sourcePath/u);
  8419. expect(projection.getSnapshot().rows.window.map((row) => row.turnId)).not.toContain(
  8420. "session-hooks:session-1",
  8421. );
  8422. });
  8423. it("HK09 distinguishes admission-only blocked from a Hook that executed and blocked", () => {
  8424. const log = new EventLog();
  8425. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8426. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  8427. log.push(
  8428. SessionEventType.HookRunBlocked,
  8429. {
  8430. descriptor,
  8431. hookEventName: "PreToolUse",
  8432. hookIndex: 0,
  8433. hookCount: 2,
  8434. hookInvocationId: "mixed-hook",
  8435. hookRunId: "admission-blocked",
  8436. outcome: "blocked",
  8437. startedAt: 1_700_000_003_000,
  8438. },
  8439. { turnId: "turn-1" },
  8440. );
  8441. log.push(
  8442. SessionEventType.HookRunStarted,
  8443. {
  8444. descriptor,
  8445. hookEventName: "PreToolUse",
  8446. hookIndex: 1,
  8447. hookCount: 2,
  8448. hookInvocationId: "mixed-hook",
  8449. hookRunId: "executed-block",
  8450. startedAt: 1_700_000_003_010,
  8451. },
  8452. { turnId: "turn-1" },
  8453. );
  8454. log.push(
  8455. SessionEventType.HookRunBlocked,
  8456. {
  8457. descriptor,
  8458. durationMs: 8,
  8459. hookEventName: "PreToolUse",
  8460. hookIndex: 1,
  8461. hookCount: 2,
  8462. hookInvocationId: "mixed-hook",
  8463. hookRunId: "executed-block",
  8464. blockReason: "blocked by workspace policy",
  8465. outcome: "blocked",
  8466. startedAt: 1_700_000_003_010,
  8467. },
  8468. { turnId: "turn-1" },
  8469. );
  8470. const row = runAll(log.events)
  8471. .projection.getSnapshot()
  8472. .rows.window.find((candidate) => candidate.kind === "hookInvocation");
  8473. expect(row).toMatchObject({
  8474. state: "completed",
  8475. executions: [
  8476. expect.objectContaining({ hookRunId: "admission-blocked", didExecute: false }),
  8477. expect.objectContaining({
  8478. hookRunId: "executed-block",
  8479. didExecute: true,
  8480. outcome: "blocked",
  8481. blockReason: "blocked by workspace policy",
  8482. }),
  8483. ],
  8484. });
  8485. });
  8486. it("HK-UP-02 projects an executed UserPromptSubmit block into the chat error", () => {
  8487. const log = new EventLog();
  8488. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1_000 });
  8489. log.push(
  8490. SessionEventType.TurnStarted,
  8491. { turnNumber: 1, input: "blocked prompt" },
  8492. { turnId: "turn-1" },
  8493. );
  8494. log.push(
  8495. SessionEventType.HookRunStarted,
  8496. {
  8497. descriptor,
  8498. hookEventName: "UserPromptSubmit",
  8499. hookIndex: 0,
  8500. hookCount: 1,
  8501. hookInvocationId: "prompt-hook",
  8502. hookRunId: "prompt-run",
  8503. startedAt: 1_700_000_003_000,
  8504. },
  8505. { turnId: "turn-1" },
  8506. );
  8507. log.push(
  8508. SessionEventType.HookRunBlocked,
  8509. {
  8510. descriptor,
  8511. durationMs: 12,
  8512. hookEventName: "UserPromptSubmit",
  8513. hookIndex: 0,
  8514. hookCount: 1,
  8515. hookInvocationId: "prompt-hook",
  8516. hookRunId: "prompt-run",
  8517. blockReason: "hooks_prompt_block",
  8518. errorMessage:
  8519. "python3: can't open file '/workspace/a.py': [Errno 2] No such file or directory",
  8520. stderrPreview:
  8521. "python3: can't open file '/workspace/a.py': [Errno 2] No such file or directory",
  8522. outcome: "blocked",
  8523. startedAt: 1_700_000_003_000,
  8524. },
  8525. { turnId: "turn-1" },
  8526. );
  8527. log.push(
  8528. SessionEventType.TurnComplete,
  8529. {
  8530. response: "HOOK_PROMPT_BLOCK_REASON",
  8531. tokenCount: 0,
  8532. toolCallCount: 0,
  8533. duration: 12,
  8534. resultType: "success",
  8535. },
  8536. { turnId: "turn-1" },
  8537. );
  8538. const { projection } = runAll(log.events);
  8539. const snapshot = projection.getSnapshot();
  8540. expect(snapshot.control.phase).toBe("completedSuccess");
  8541. expect(snapshot.control.lastError).toMatchObject({
  8542. code: "fault.runtime.hookBlocked",
  8543. message:
  8544. "hooks_prompt_block: python3: can't open file '/workspace/a.py': [Errno 2] No such file or directory",
  8545. detail:
  8546. "Hook block reason: hooks_prompt_block\nHook error: python3: can't open file '/workspace/a.py': [Errno 2] No such file or directory",
  8547. recoverable: false,
  8548. source: "runtime",
  8549. traceId: "trace-1",
  8550. attribution: { source: "runtime", reason: "hook_blocked" },
  8551. });
  8552. });
  8553. it.each([
  8554. [SessionEventType.HookRunCompleted, "success"],
  8555. [SessionEventType.HookRunFailed, "failed"],
  8556. ] as const)("HK09 keeps terminal-only %s as not executed", (terminalType, outcome) => {
  8557. const log = new EventLog();
  8558. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8559. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  8560. log.push(
  8561. terminalType,
  8562. {
  8563. descriptor,
  8564. durationMs: 20,
  8565. hookEventName: "PreToolUse",
  8566. hookIndex: 0,
  8567. hookCount: 1,
  8568. hookInvocationId: `terminal-only-${outcome}`,
  8569. hookRunId: `terminal-only-run-${outcome}`,
  8570. outcome,
  8571. startedAt: 1_700_000_003_000,
  8572. },
  8573. { turnId: "turn-1", timestampMs: 1_700_000_003_020 },
  8574. );
  8575. const row = runAll(log.events)
  8576. .projection.getSnapshot()
  8577. .rows.window.find((candidate) => candidate.kind === "hookInvocation");
  8578. expect(row).toMatchObject({
  8579. executions: [expect.objectContaining({ didExecute: false, outcome })],
  8580. });
  8581. });
  8582. it("HK13 updates a late async terminal in place without reopening the completed turn", () => {
  8583. const log = new EventLog();
  8584. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8585. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  8586. log.push(
  8587. SessionEventType.HookRunStarted,
  8588. {
  8589. descriptor: { ...descriptor, executionMode: "background" },
  8590. hookEventName: "UserPromptSubmit",
  8591. hookIndex: 0,
  8592. hookCount: 1,
  8593. hookInvocationId: "async-hook",
  8594. hookRunId: "async-run",
  8595. startedAt: 1_700_000_003_000,
  8596. },
  8597. { turnId: "turn-1", timestampMs: 1_700_000_003_000 },
  8598. );
  8599. log.push(
  8600. SessionEventType.TurnComplete,
  8601. { response: "done", tokenCount: 1, toolCallCount: 0, duration: 10, resultType: "success" },
  8602. { turnId: "turn-1", timestampMs: 1_700_000_003_010 },
  8603. );
  8604. log.push(
  8605. SessionEventType.HookRunCompleted,
  8606. {
  8607. descriptor: { ...descriptor, executionMode: "background" },
  8608. durationMs: 50,
  8609. hookEventName: "UserPromptSubmit",
  8610. hookIndex: 0,
  8611. hookCount: 1,
  8612. hookInvocationId: "async-hook",
  8613. hookRunId: "async-run",
  8614. outcome: "success",
  8615. startedAt: 1_700_000_003_000,
  8616. },
  8617. { turnId: "turn-1", timestampMs: 1_700_000_003_050 },
  8618. );
  8619. const { deltasPerEvent, projection } = runAll(log.events);
  8620. expect(deltasPerEvent[4]).toContainEqual(
  8621. expect.objectContaining({
  8622. op: "row.upserted",
  8623. row: expect.objectContaining({ hookInvocationId: "async-hook", state: "completed" }),
  8624. }),
  8625. );
  8626. expect(projection.getSnapshot().control.phase).toBe("completedSuccess");
  8627. expect(
  8628. projection
  8629. .getSnapshot()
  8630. .rows.window.filter(
  8631. (row) => row.kind === "hookInvocation" && row.hookInvocationId === "async-hook",
  8632. ),
  8633. ).toHaveLength(1);
  8634. });
  8635. it("HK13 closes an attached started-only execution on a real runtime resume", () => {
  8636. const log = new EventLog();
  8637. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8638. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  8639. log.push(
  8640. SessionEventType.HookRunStarted,
  8641. {
  8642. descriptor,
  8643. hookEventName: "PreToolUse",
  8644. hookIndex: 0,
  8645. hookCount: 1,
  8646. hookInvocationId: "started-only-hook",
  8647. hookRunId: "started-only-run",
  8648. startedAt: 1_700_000_002_000,
  8649. },
  8650. { turnId: "turn-1", timestampMs: 1_700_000_002_000 },
  8651. );
  8652. log.push(SessionEventType.SessionResumed, {}, { timestampMs: 1_700_000_003_000 });
  8653. const row = runAll(log.events)
  8654. .projection.getSnapshot()
  8655. .rows.window.find((candidate) => candidate.kind === "hookInvocation");
  8656. expect(row).toMatchObject({
  8657. state: "failed",
  8658. executions: [
  8659. {
  8660. didExecute: true,
  8661. state: "failed",
  8662. outcome: "cancelled",
  8663. durationMs: 1_000,
  8664. },
  8665. ],
  8666. });
  8667. });
  8668. it("HK17 does not flush a pending SessionStart summary onto a model-only compact turn", () => {
  8669. // Bug 根因:Runtime 的 runSessionStartHooks 先于 /compact 输入解析执行,首条输入即
  8670. // /compact 时 SessionStart Hook 真实执行且携带 compact 的 runtime turnId;投影层
  8671. // flush 只看「下一条 TurnStarted」,把摘要挂到了 model-only 维护 turn 上。
  8672. const log = new EventLog();
  8673. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  8674. log.push(
  8675. SessionEventType.HookRunStarted,
  8676. {
  8677. descriptor,
  8678. hookEventName: "SessionStart",
  8679. hookIndex: 0,
  8680. hookCount: 1,
  8681. hookInvocationId: "startup-hook",
  8682. hookRunId: "startup-run",
  8683. startedAt: 1_700_000_002_000,
  8684. },
  8685. { turnId: "turn-1", timestampMs: 1_700_000_002_000 },
  8686. );
  8687. log.push(
  8688. SessionEventType.HookRunCompleted,
  8689. {
  8690. descriptor,
  8691. durationMs: 10,
  8692. hookEventName: "SessionStart",
  8693. hookIndex: 0,
  8694. hookCount: 1,
  8695. hookInvocationId: "startup-hook",
  8696. hookRunId: "startup-run",
  8697. outcome: "success",
  8698. startedAt: 1_700_000_002_000,
  8699. },
  8700. { turnId: "turn-1", timestampMs: 1_700_000_002_010 },
  8701. );
  8702. // compact 维护 turn:inputVisibility=model-only,无 user bubble。
  8703. log.push(
  8704. SessionEventType.TurnStarted,
  8705. { turnNumber: 1, input: "/compact", inputVisibility: "model-only" },
  8706. { turnId: "turn-1", timestampMs: 1_700_000_003_000 },
  8707. );
  8708. log.push(
  8709. SessionEventType.CompactStarted,
  8710. {
  8711. operationId: "op-1",
  8712. messageId: "msg-compact",
  8713. status: "started",
  8714. trigger: "manual",
  8715. display: "separator",
  8716. },
  8717. { turnId: "turn-1", timestampMs: 1_700_000_003_050 },
  8718. );
  8719. log.push(
  8720. SessionEventType.CompactCompleted,
  8721. {
  8722. operationId: "op-1",
  8723. messageId: "msg-compact",
  8724. status: "completed",
  8725. trigger: "manual",
  8726. display: "separator",
  8727. },
  8728. { turnId: "turn-1", timestampMs: 1_700_000_004_000 },
  8729. );
  8730. log.push(
  8731. SessionEventType.TurnComplete,
  8732. {
  8733. response: "compacted",
  8734. tokenCount: 1,
  8735. toolCallCount: 0,
  8736. duration: 1_000,
  8737. resultType: "success",
  8738. },
  8739. { turnId: "turn-1", timestampMs: 1_700_000_004_050 },
  8740. );
  8741. const afterCompact = runAll(log.events).projection.getSnapshot();
  8742. // compact 维护 turn 不承载 SessionStart 摘要:不得出现挂在 turn-1 的 hook row。
  8743. expect(afterCompact.rows.window.filter((row) => row.kind === "hookInvocation")).toHaveLength(0);
  8744. // 下一条真实 user-visible turn 才是合法收口目标。
  8745. log.push(
  8746. SessionEventType.TurnStarted,
  8747. { turnNumber: 2, input: "next real prompt" },
  8748. { turnId: "turn-2", timestampMs: 1_700_000_005_000 },
  8749. );
  8750. const afterRealTurn = runAll(log.events).projection.getSnapshot();
  8751. const hookRows = afterRealTurn.rows.window.filter((row) => row.kind === "hookInvocation");
  8752. expect(hookRows).toHaveLength(1);
  8753. expect(hookRows[0]).toMatchObject({
  8754. hookEventName: "SessionStart",
  8755. turnId: "turn-2",
  8756. executions: [expect.objectContaining({ didExecute: true })],
  8757. });
  8758. });
  8759. it("HK17 keeps a SessionStart summary pending when a compact turn is the last turn", () => {
  8760. // 只有 /compact 且无后续输入:摘要保持 pending,不挂 compact marker,也不制造
  8761. // 可见时间线内容(session-hooks:* synthetic turn 禁止)。
  8762. const log = new EventLog();
  8763. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  8764. log.push(
  8765. SessionEventType.HookRunStarted,
  8766. {
  8767. descriptor,
  8768. hookEventName: "SessionStart",
  8769. hookIndex: 0,
  8770. hookCount: 1,
  8771. hookInvocationId: "startup-hook",
  8772. hookRunId: "startup-run",
  8773. startedAt: 1_700_000_002_000,
  8774. },
  8775. { turnId: "turn-1", timestampMs: 1_700_000_002_000 },
  8776. );
  8777. log.push(
  8778. SessionEventType.HookRunCompleted,
  8779. {
  8780. descriptor,
  8781. durationMs: 10,
  8782. hookEventName: "SessionStart",
  8783. hookIndex: 0,
  8784. hookCount: 1,
  8785. hookInvocationId: "startup-hook",
  8786. hookRunId: "startup-run",
  8787. outcome: "success",
  8788. startedAt: 1_700_000_002_000,
  8789. },
  8790. { turnId: "turn-1", timestampMs: 1_700_000_002_010 },
  8791. );
  8792. log.push(
  8793. SessionEventType.TurnStarted,
  8794. { turnNumber: 1, input: "/compact", inputVisibility: "model-only" },
  8795. { turnId: "turn-1", timestampMs: 1_700_000_003_000 },
  8796. );
  8797. log.push(
  8798. SessionEventType.TurnComplete,
  8799. {
  8800. response: "compacted",
  8801. tokenCount: 1,
  8802. toolCallCount: 0,
  8803. duration: 1_000,
  8804. resultType: "success",
  8805. },
  8806. { turnId: "turn-1", timestampMs: 1_700_000_004_000 },
  8807. );
  8808. const snapshot = runAll(log.events).projection.getSnapshot();
  8809. expect(snapshot.rows.window.filter((row) => row.kind === "hookInvocation")).toHaveLength(0);
  8810. expect(snapshot.rows.window.map((row) => row.turnId)).not.toContain("session-hooks:session-1");
  8811. });
  8812. it("HK17 keeps tool Hooks of a model-only real agent turn attached to that turn", () => {
  8813. // 回归背景(2026-08-28 review):model-only ≠ 维护 turn。background_task 通知轮
  8814. // (runtime-command-queue)、subagent_message 轮、goal continuation 轮都是
  8815. // inputVisibility="model-only" 但会真实跑工具的 agent 轮。HK17 首版把直挂 gate
  8816. // 无差别地按 currentTurnStartedModelOnly 拦截,导致这些轮的 PreToolUse/PostToolUse
  8817. // 被 pending 吞掉、错误 flush 到下一个不相关用户轮。维护 turn 排除只属于
  8818. // SessionStart;工具 Hook 必须按 event.turnId 直挂原轮,与 cold merge 对齐。
  8819. const log = new EventLog();
  8820. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8821. log.push(
  8822. SessionEventType.TurnStarted,
  8823. {
  8824. turnNumber: 1,
  8825. input: "background task completed, continue",
  8826. inputVisibility: "model-only",
  8827. },
  8828. { turnId: "turn-bg", timestampMs: 1_700_000_001_000 },
  8829. );
  8830. log.push(
  8831. SessionEventType.HookRunStarted,
  8832. {
  8833. descriptor,
  8834. hookEventName: "PreToolUse",
  8835. hookIndex: 0,
  8836. hookCount: 1,
  8837. hookInvocationId: "bg-tool-hook",
  8838. hookRunId: "bg-tool-run",
  8839. startedAt: 1_700_000_002_000,
  8840. toolCallId: "tool-bg",
  8841. toolName: "Write",
  8842. },
  8843. { turnId: "turn-bg", timestampMs: 1_700_000_002_000 },
  8844. );
  8845. log.push(
  8846. SessionEventType.HookRunCompleted,
  8847. {
  8848. descriptor,
  8849. durationMs: 15,
  8850. hookEventName: "PreToolUse",
  8851. hookIndex: 0,
  8852. hookCount: 1,
  8853. hookInvocationId: "bg-tool-hook",
  8854. hookRunId: "bg-tool-run",
  8855. outcome: "success",
  8856. startedAt: 1_700_000_002_000,
  8857. toolCallId: "tool-bg",
  8858. toolName: "Write",
  8859. },
  8860. { turnId: "turn-bg", timestampMs: 1_700_000_002_015 },
  8861. );
  8862. log.push(
  8863. SessionEventType.TurnStarted,
  8864. { turnNumber: 2, input: "unrelated user question" },
  8865. { turnId: "turn-user", timestampMs: 1_700_000_003_000 },
  8866. );
  8867. const hookRows = runAll(log.events)
  8868. .projection.getSnapshot()
  8869. .rows.window.filter((row) => row.kind === "hookInvocation");
  8870. expect(hookRows).toHaveLength(1);
  8871. // 工具 Hook 留在 model-only 真实 agent 轮,不被 pending 迁移到用户轮。
  8872. expect(hookRows[0]).toMatchObject({
  8873. hookEventName: "PreToolUse",
  8874. turnId: "turn-bg",
  8875. anchorToolCallId: "tool-bg",
  8876. executions: [expect.objectContaining({ didExecute: true })],
  8877. });
  8878. });
  8879. it.each([
  8880. {
  8881. caseName: "TurnError",
  8882. terminal: (log: EventLog, turnId: string, at: number) =>
  8883. log.push(
  8884. SessionEventType.TurnError,
  8885. { error: { type: "ProviderError", message: "rate limited" }, turnPhase: "model" },
  8886. { turnId, timestampMs: at },
  8887. ),
  8888. },
  8889. {
  8890. caseName: "TurnComplete(cancelled)",
  8891. terminal: (log: EventLog, turnId: string, at: number) =>
  8892. log.push(
  8893. SessionEventType.TurnComplete,
  8894. {
  8895. response: "",
  8896. tokenCount: 0,
  8897. toolCallCount: 0,
  8898. duration: 100,
  8899. resultType: "cancelled",
  8900. },
  8901. { turnId, timestampMs: at },
  8902. ),
  8903. },
  8904. ])(
  8905. "HK17 keeps a pending SessionStart summary off an abnormally terminated model-only turn ($caseName)",
  8906. ({ terminal }) => {
  8907. // SG-01:currentTurnId / currentTurnStartedModelOnly 是 reducer 内部侧表,
  8908. // 异常终态是最容易遗漏的生命周期边界。TurnError 非 controlOnly 路径不清侧表、
  8909. // TurnComplete(cancelled) 清侧表,两条收口路径必须等价:pending SessionStart
  8910. // 不泄漏到异常 turn、不直挂死 turn、只归位下一条真实用户 turn。
  8911. const sessionStartLifecycle = (log: EventLog, invocationId: string, at: number) => {
  8912. log.push(
  8913. SessionEventType.HookRunStarted,
  8914. {
  8915. descriptor,
  8916. hookEventName: "SessionStart",
  8917. hookIndex: 0,
  8918. hookCount: 1,
  8919. hookInvocationId: invocationId,
  8920. hookRunId: `${invocationId}-run`,
  8921. startedAt: at,
  8922. },
  8923. { turnId: "turn-mt", timestampMs: at },
  8924. );
  8925. log.push(
  8926. SessionEventType.HookRunCompleted,
  8927. {
  8928. descriptor,
  8929. durationMs: 5,
  8930. hookEventName: "SessionStart",
  8931. hookIndex: 0,
  8932. hookCount: 1,
  8933. hookInvocationId: invocationId,
  8934. hookRunId: `${invocationId}-run`,
  8935. outcome: "success",
  8936. startedAt: at,
  8937. },
  8938. { turnId: "turn-mt", timestampMs: at + 5 },
  8939. );
  8940. };
  8941. const log = new EventLog();
  8942. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  8943. // model-only goal continuation 轮(executionKind 缺省为 agent,异常走非 controlOnly)。
  8944. log.push(
  8945. SessionEventType.TurnStarted,
  8946. { turnNumber: 1, input: "continue goal", inputVisibility: "model-only" },
  8947. { turnId: "turn-mt", timestampMs: 1_700_000_001_000 },
  8948. );
  8949. sessionStartLifecycle(log, "startup-hook", 1_700_000_002_000);
  8950. terminal(log, "turn-mt", 1_700_000_003_000);
  8951. // 异常收口瞬间:pending 保留,不挂异常 turn,也不泄漏成可见 row。
  8952. const afterTerminal = runAll(log.events).projection.getSnapshot();
  8953. expect(afterTerminal.rows.window.filter((row) => row.kind === "hookInvocation")).toHaveLength(
  8954. 0,
  8955. );
  8956. expect(afterTerminal.rows.window.map((row) => row.turnId)).not.toContain(
  8957. "session-hooks:session-1",
  8958. );
  8959. // 终态后紧接的下一个 SessionStart(resume epoch)同样必须 pending,
  8960. // 不得直挂已终止的死 turn。
  8961. sessionStartLifecycle(log, "resume-hook", 1_700_000_004_000);
  8962. const afterResumeHook = runAll(log.events).projection.getSnapshot();
  8963. expect(
  8964. afterResumeHook.rows.window.filter((row) => row.kind === "hookInvocation"),
  8965. ).toHaveLength(0);
  8966. // 下一条真实用户 turn 收口两条 pending 摘要,且只出现在该轮。
  8967. log.push(
  8968. SessionEventType.TurnStarted,
  8969. { turnNumber: 2, input: "real question" },
  8970. { turnId: "turn-real", timestampMs: 1_700_000_005_000 },
  8971. );
  8972. const finalRows = runAll(log.events)
  8973. .projection.getSnapshot()
  8974. .rows.window.filter((row) => row.kind === "hookInvocation");
  8975. expect(finalRows.map((row) => [row.hookInvocationId, row.turnId])).toEqual([
  8976. ["startup-hook", "turn-real"],
  8977. ["resume-hook", "turn-real"],
  8978. ]);
  8979. },
  8980. );
  8981. it.each([
  8982. [SessionEventType.HookRunCompleted, { durationMs: 20, outcome: "success" }],
  8983. [SessionEventType.HookRunFailed, { durationMs: 20, outcome: "failed" }],
  8984. ] as const)(
  8985. "HK14 ignores late %s after its Hook branch was rewound",
  8986. (terminalType, terminal) => {
  8987. const log = new EventLog();
  8988. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8989. log.push(
  8990. SessionEventType.TurnStarted,
  8991. { turnNumber: 1, input: "run", messageId: "user-1" },
  8992. { turnId: "turn-1" },
  8993. );
  8994. log.push(
  8995. SessionEventType.ModelStreaming,
  8996. { kind: "text_start", delta: "", done: false, assistantMessageId: "assistant-1" },
  8997. { turnId: "turn-1" },
  8998. );
  8999. log.push(
  9000. SessionEventType.HookRunStarted,
  9001. {
  9002. descriptor,
  9003. hookEventName: "PreToolUse",
  9004. hookIndex: 0,
  9005. hookCount: 1,
  9006. hookInvocationId: "rewound-hook",
  9007. hookRunId: "rewound-run",
  9008. startedAt: 1_700_000_003_000,
  9009. },
  9010. { turnId: "turn-1", timestampMs: 1_700_000_003_000 },
  9011. );
  9012. log.push(SessionEventType.RewindTriggered, {
  9013. targetMessageId: "assistant-1",
  9014. scope: "conversation",
  9015. createdMessageId: "rewind-notice",
  9016. });
  9017. log.push(
  9018. terminalType,
  9019. {
  9020. descriptor,
  9021. hookEventName: "PreToolUse",
  9022. hookIndex: 0,
  9023. hookCount: 1,
  9024. hookInvocationId: "rewound-hook",
  9025. hookRunId: "rewound-run",
  9026. startedAt: 1_700_000_003_000,
  9027. ...terminal,
  9028. },
  9029. { turnId: "turn-1", timestampMs: 1_700_000_003_020 },
  9030. );
  9031. const { deltasPerEvent, projection } = runAll(log.events);
  9032. expect(deltasPerEvent[4]).toContainEqual({
  9033. op: "row.removed",
  9034. fromRowId: expect.any(Number),
  9035. });
  9036. expect(
  9037. projection
  9038. .getSnapshot()
  9039. .rows.window.some(
  9040. (row) => row.kind === "hookInvocation" && row.hookInvocationId === "rewound-hook",
  9041. ),
  9042. ).toBe(false);
  9043. expect(deltasPerEvent[5]).not.toContainEqual(
  9044. expect.objectContaining({
  9045. op: "row.appended",
  9046. row: expect.objectContaining({ hookInvocationId: "rewound-hook" }),
  9047. }),
  9048. );
  9049. },
  9050. );
  9051. it("projects workspace Hook review only as Settings-centered pending interaction", () => {
  9052. const log = new EventLog();
  9053. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9054. const request = {
  9055. kind: "workspaceHookReview",
  9056. reviewFlowId: "flow-1",
  9057. generation: 1,
  9058. interactionId: "interaction-1",
  9059. sessionId: "session-1",
  9060. taskId: "session-1",
  9061. runId: "run-1",
  9062. workspaceIdentity: "local:/workspace",
  9063. workspaceLabel: "workspace",
  9064. bundleDigest: "a".repeat(64),
  9065. createdAt: 1_700_000_001_000,
  9066. deadlineAt: 1_700_000_601_000,
  9067. sourceFiles: [
  9068. {
  9069. path: "/workspace/.zcode/config.json",
  9070. displayPath: ".zcode/config.json",
  9071. editable: true,
  9072. },
  9073. ],
  9074. summary: { eventCount: 1, hookCount: 1, pendingCount: 1 },
  9075. items: [
  9076. {
  9077. reviewItemId: "item-0",
  9078. event: "SessionStart",
  9079. matcher: "startup",
  9080. type: "command",
  9081. displayName: "SessionStart · startup",
  9082. displayCommand: "echo project",
  9083. sourcePath: ".zcode/config.json",
  9084. resolvedTimeoutMs: 60_000,
  9085. resolvedMaxOutputBytes: 32_768,
  9086. executionMode: "foreground",
  9087. configuredEnabled: true,
  9088. editable: true,
  9089. trustState: "pending_trust",
  9090. },
  9091. ],
  9092. warningCode: "workspace_hooks_execute_code",
  9093. } as const;
  9094. log.push(SessionEventType.WorkspaceHookReviewRequested, { request });
  9095. const { projection } = runAll(log.events);
  9096. expect(projection.getSnapshot().pendingInteractions).toEqual([
  9097. {
  9098. interactionId: "interaction-1",
  9099. kind: "workspaceHookReview",
  9100. anchorRowId: null,
  9101. createdAt: request.createdAt,
  9102. payload: request,
  9103. },
  9104. ]);
  9105. log.push(SessionEventType.WorkspaceHookReviewSettled, {
  9106. interactionId: "interaction-1",
  9107. state: "resolved",
  9108. });
  9109. projection.applyEvent(log.events.at(-1)!);
  9110. expect(projection.getSnapshot().pendingInteractions).toEqual([]);
  9111. });
  9112. it("superseded review generation removes only the stale interaction", () => {
  9113. const log = new EventLog();
  9114. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9115. const base = {
  9116. kind: "workspaceHookReview",
  9117. reviewFlowId: "flow-1",
  9118. sessionId: "session-1",
  9119. taskId: "session-1",
  9120. runId: "run-1",
  9121. workspaceIdentity: "local:/workspace",
  9122. workspaceLabel: "workspace",
  9123. createdAt: 1_700_000_001_000,
  9124. deadlineAt: 1_700_000_601_000,
  9125. sourceFiles: [],
  9126. summary: { eventCount: 0, hookCount: 0, pendingCount: 0 },
  9127. items: [],
  9128. warningCode: "workspace_hooks_execute_code",
  9129. } as const;
  9130. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  9131. request: {
  9132. ...base,
  9133. generation: 1,
  9134. interactionId: "interaction-1",
  9135. bundleDigest: "a".repeat(64),
  9136. },
  9137. });
  9138. log.push(SessionEventType.WorkspaceHookReviewSuperseded, {
  9139. interactionId: "interaction-1",
  9140. supersededByInteractionId: "interaction-2",
  9141. });
  9142. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  9143. request: {
  9144. ...base,
  9145. generation: 2,
  9146. interactionId: "interaction-2",
  9147. bundleDigest: "b".repeat(64),
  9148. },
  9149. });
  9150. const { projection } = runAll(log.events);
  9151. expect(projection.getSnapshot().pendingInteractions.map((item) => item.interactionId)).toEqual([
  9152. "interaction-2",
  9153. ]);
  9154. });
  9155. it("treats SessionResumed and the next requested review as a new runtime authority", () => {
  9156. const log = new EventLog();
  9157. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9158. const base = {
  9159. kind: "workspaceHookReview",
  9160. sessionId: "session-1",
  9161. taskId: "session-1",
  9162. runId: "run-1",
  9163. workspaceIdentity: "local:/workspace",
  9164. workspaceLabel: "workspace",
  9165. createdAt: 1_700_000_001_000,
  9166. deadlineAt: 1_700_000_601_000,
  9167. sourceFiles: [],
  9168. summary: { eventCount: 0, hookCount: 0, pendingCount: 0 },
  9169. items: [],
  9170. warningCode: "workspace_hooks_execute_code",
  9171. } as const;
  9172. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  9173. request: {
  9174. ...base,
  9175. reviewFlowId: "old-runtime-flow",
  9176. generation: 7,
  9177. interactionId: "old-runtime-interaction",
  9178. bundleDigest: "a".repeat(64),
  9179. },
  9180. });
  9181. log.push(SessionEventType.SessionResumed, {});
  9182. const { projection } = runAll(log.events);
  9183. expect(projection.getSnapshot().pendingInteractions).toEqual([]);
  9184. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  9185. request: {
  9186. ...base,
  9187. reviewFlowId: "new-runtime-flow",
  9188. generation: 1,
  9189. interactionId: "new-runtime-interaction",
  9190. bundleDigest: "b".repeat(64),
  9191. createdAt: 1_700_000_002_000,
  9192. deadlineAt: 1_700_000_602_000,
  9193. },
  9194. });
  9195. projection.applyEvent(log.events.at(-1)!);
  9196. expect(projection.getSnapshot().pendingInteractions.map((item) => item.interactionId)).toEqual([
  9197. "new-runtime-interaction",
  9198. ]);
  9199. });
  9200. it("ignores a different review flow until SessionResumed establishes a new runtime epoch", () => {
  9201. const log = new EventLog();
  9202. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9203. const base = {
  9204. kind: "workspaceHookReview",
  9205. generation: 1,
  9206. sessionId: "session-1",
  9207. taskId: "session-1",
  9208. runId: "run-1",
  9209. workspaceIdentity: "local:/workspace",
  9210. workspaceLabel: "workspace",
  9211. createdAt: 1_700_000_001_000,
  9212. deadlineAt: 1_700_000_601_000,
  9213. sourceFiles: [],
  9214. summary: { eventCount: 0, hookCount: 0, pendingCount: 0 },
  9215. items: [],
  9216. warningCode: "workspace_hooks_execute_code",
  9217. } as const;
  9218. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  9219. request: {
  9220. ...base,
  9221. reviewFlowId: "old-flow",
  9222. interactionId: "old-interaction",
  9223. bundleDigest: "a".repeat(64),
  9224. },
  9225. });
  9226. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  9227. request: {
  9228. ...base,
  9229. reviewFlowId: "new-flow",
  9230. interactionId: "new-interaction",
  9231. bundleDigest: "b".repeat(64),
  9232. createdAt: 1_700_000_002_000,
  9233. deadlineAt: 1_700_000_602_000,
  9234. },
  9235. });
  9236. const { projection } = runAll(log.events);
  9237. expect(projection.getSnapshot().pendingInteractions.map((item) => item.interactionId)).toEqual([
  9238. "old-interaction",
  9239. ]);
  9240. });
  9241. it("ignores equal-generation workspace Hook review requests with a conflicting interaction", () => {
  9242. const log = new EventLog();
  9243. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9244. const base = {
  9245. kind: "workspaceHookReview",
  9246. reviewFlowId: "flow-1",
  9247. generation: 3,
  9248. sessionId: "session-1",
  9249. taskId: "session-1",
  9250. runId: "run-1",
  9251. workspaceIdentity: "local:/workspace",
  9252. workspaceLabel: "workspace",
  9253. createdAt: 1_700_000_001_000,
  9254. deadlineAt: 1_700_000_601_000,
  9255. sourceFiles: [],
  9256. summary: { eventCount: 0, hookCount: 0, pendingCount: 0 },
  9257. items: [],
  9258. warningCode: "workspace_hooks_execute_code",
  9259. } as const;
  9260. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  9261. request: {
  9262. ...base,
  9263. interactionId: "interaction-authority",
  9264. bundleDigest: "a".repeat(64),
  9265. },
  9266. });
  9267. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  9268. request: {
  9269. ...base,
  9270. interactionId: "interaction-conflict",
  9271. bundleDigest: "b".repeat(64),
  9272. },
  9273. });
  9274. const { projection } = runAll(log.events);
  9275. expect(projection.getSnapshot().pendingInteractions.map((item) => item.interactionId)).toEqual([
  9276. "interaction-authority",
  9277. ]);
  9278. });
  9279. it("does not project hidden internal or legacy lifecycle events", () => {
  9280. const log = new EventLog();
  9281. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9282. log.push(SessionEventType.HookRunStarted, {
  9283. descriptor: {
  9284. ...descriptor,
  9285. clientVisible: false,
  9286. sourceKind: "internal",
  9287. },
  9288. hookEventName: "SessionStart",
  9289. hookIndex: 0,
  9290. hookCount: 0,
  9291. hookInvocationId: "mailbox-hook",
  9292. hookRunId: "mailbox-run",
  9293. startedAt: 1_700_000_002_000,
  9294. });
  9295. log.push(SessionEventType.HookRunStarted, {
  9296. hookEventName: "SessionStart",
  9297. hookIndex: 0,
  9298. hookRunId: "legacy-run",
  9299. });
  9300. const { projection } = runAll(log.events);
  9301. expect(projection.getSnapshot().rows.window).not.toContainEqual(
  9302. expect.objectContaining({ kind: "hookInvocation" }),
  9303. );
  9304. });
  9305. });
  9306. describe("软门禁(D2): workspaceHookAdmission snapshot 投影", () => {
  9307. it("WorkspaceHookAdmissionUpdated pendingCount>0 写入 snapshot.workspaceHookAdmission", () => {
  9308. const log = new EventLog();
  9309. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9310. log.push(SessionEventType.WorkspaceHookAdmissionUpdated, {
  9311. pendingCount: 2,
  9312. bundleDigest: "a".repeat(64),
  9313. workspaceIdentity: "local:/workspace",
  9314. });
  9315. const { projection } = runAll(log.events);
  9316. expect(projection.getSnapshot().workspaceHookAdmission).toEqual({
  9317. pendingCount: 2,
  9318. bundleDigest: "a".repeat(64),
  9319. workspaceIdentity: "local:/workspace",
  9320. });
  9321. });
  9322. it("WorkspaceHookAdmissionUpdated pendingCount===0 → 置 null(提示条消失)", () => {
  9323. const log = new EventLog();
  9324. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9325. // 先有 pending
  9326. log.push(SessionEventType.WorkspaceHookAdmissionUpdated, {
  9327. pendingCount: 1,
  9328. bundleDigest: "a".repeat(64),
  9329. });
  9330. // settle 后清零
  9331. log.push(SessionEventType.WorkspaceHookAdmissionUpdated, {
  9332. pendingCount: 0,
  9333. bundleDigest: "a".repeat(64),
  9334. });
  9335. const { projection } = runAll(log.events);
  9336. expect(projection.getSnapshot().workspaceHookAdmission).toBeNull();
  9337. });
  9338. it("SessionResumed epoch 清理 → workspaceHookAdmission 置 null(resume 后 activate 重新上报)", () => {
  9339. const log = new EventLog();
  9340. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9341. log.push(SessionEventType.WorkspaceHookAdmissionUpdated, {
  9342. pendingCount: 3,
  9343. bundleDigest: "a".repeat(64),
  9344. workspaceIdentity: "local:/workspace",
  9345. });
  9346. log.push(SessionEventType.SessionResumed, {});
  9347. const { projection } = runAll(log.events);
  9348. expect(projection.getSnapshot().workspaceHookAdmission).toBeNull();
  9349. });
  9350. it("workspaceIdentity 可选:缺失时 snapshot 字段不含 workspaceIdentity", () => {
  9351. const log = new EventLog();
  9352. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9353. log.push(SessionEventType.WorkspaceHookAdmissionUpdated, {
  9354. pendingCount: 1,
  9355. bundleDigest: "b".repeat(64),
  9356. });
  9357. const { projection } = runAll(log.events);
  9358. expect(projection.getSnapshot().workspaceHookAdmission).toEqual({
  9359. pendingCount: 1,
  9360. bundleDigest: "b".repeat(64),
  9361. });
  9362. expect(projection.getSnapshot().workspaceHookAdmission).not.toHaveProperty("workspaceIdentity");
  9363. });
  9364. });
  9365. // ── CreateWorkflow 运行确认(docs/dynamic-workflow/launch.md)──
  9366. describe("workflow 运行确认的 ask 预览", () => {
  9367. const causalityGraph = {
  9368. steps: [
  9369. {
  9370. id: "ask#1",
  9371. kind: "ask" as const,
  9372. label: "a",
  9373. line: 2,
  9374. column: 11,
  9375. lane: "actor#1",
  9376. },
  9377. ],
  9378. lanes: [{ id: "actor#1", name: "a" }],
  9379. // 第二层是子代理导向:每阶段一张参与者卡 + 交接边(docs/dynamic-workflow/presentation.md)。
  9380. participants: [
  9381. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] },
  9382. ],
  9383. handoffs: [],
  9384. sink: ["ask#1"],
  9385. };
  9386. function permissionRequestedLog(display?: unknown, toolName = "CreateWorkflow"): EventLog {
  9387. const turnId = "turn-1";
  9388. const log = new EventLog();
  9389. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  9390. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run it" }, { turnId });
  9391. log.push(
  9392. SessionEventType.ToolCallScheduled,
  9393. {
  9394. toolCallId: "tc-1",
  9395. toolName,
  9396. input: { script: "return 1;" },
  9397. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  9398. },
  9399. { turnId },
  9400. );
  9401. log.push(
  9402. SessionEventType.PermissionRequested,
  9403. {
  9404. requestId: "req-1",
  9405. toolCallId: "tc-1",
  9406. toolName,
  9407. riskLevel: "low",
  9408. reason: "createWorkflow.runConfirmation: user must confirm running the analyzed script",
  9409. input: { script: "return 1;" },
  9410. // CreateWorkflow 自 2026-09-11(第 7 轮)起声明会话作用域的免确认;Bash 用例只借
  9411. // 这条日志的形状,策略对它无意义(投影不看工具声明,只看事件上的策略)。
  9412. optionsPolicy: "session-always-allow",
  9413. ...(display === undefined ? {} : { display }),
  9414. },
  9415. { turnId },
  9416. );
  9417. return log;
  9418. }
  9419. it("把事件上的 display 投到 pendingInteraction,并按 optionsPolicy 把 always allow 换成会话免确认", () => {
  9420. const log = permissionRequestedLog({
  9421. kind: "create_workflow",
  9422. ok: true,
  9423. errorCount: 0,
  9424. diagnostics: [],
  9425. causalityGraph,
  9426. });
  9427. const snapshot = runAll(log.events).projection.getSnapshot();
  9428. const toolRow = snapshot.rows.window.find((row) => row.kind === "toolCall");
  9429. expect(toolRow).toMatchObject({
  9430. status: "pendingApproval",
  9431. approvalInteractionId: "req-1",
  9432. });
  9433. expect(snapshot.pendingInteractions).toHaveLength(1);
  9434. const payload = snapshot.pendingInteractions[0]?.payload;
  9435. expect(payload).toMatchObject({
  9436. kind: "permission",
  9437. display: { kind: "create_workflow", ok: true, causalityGraph },
  9438. });
  9439. // 产品裁决:项目级 always allow 被 optionsPolicy 裁掉,第 7 轮换成会话作用域的
  9440. // 免确认;第 4 轮在 v4 追加 Refine(拒绝并附修改意见),列表 = Run / Session / Deny / Refine。
  9441. expect(
  9442. payload?.kind === "permission" && payload.options.map((option) => option.optionId),
  9443. ).toEqual(["allowOnce", "allowSession", "deny", "workflowRefine"]);
  9444. const sessionOption =
  9445. payload?.kind === "permission"
  9446. ? payload.options.find((option) => option.optionId === "allowSession")
  9447. : undefined;
  9448. // wire 上的 kind 是闭集:会话选项映为 allowAlways(GUI 按 name 本地化);optionId 原样,
  9449. // broker 靠它精确命中。response 不带 permissionUpdates(strict schema,见 spec 第 7 轮)。
  9450. expect(sessionOption).toMatchObject({
  9451. kind: "allowAlways",
  9452. label: "Always allow in this session",
  9453. response: { decision: "allow" },
  9454. });
  9455. expect(sessionOption?.response).not.toHaveProperty("permissionUpdates");
  9456. expect(conversationSnapshotSchema.safeParse(snapshot).success).toBe(true);
  9457. const refineOption =
  9458. payload?.kind === "permission"
  9459. ? payload.options.find((option) => option.optionId === "workflowRefine")
  9460. : undefined;
  9461. // 静态 response 是普通 deny:不认识该选项的消费面(bot 直出、无 freeText 应答)
  9462. // 退化为拒绝;反馈升级只发生在 interaction-broker 的 freeText 特判。
  9463. expect(refineOption).toMatchObject({
  9464. kind: "custom",
  9465. label: "Refine",
  9466. response: { decision: "deny" },
  9467. });
  9468. });
  9469. it("Refine 选项只属于 CreateWorkflow:其他工具的权限 ask 不投放", () => {
  9470. const snapshot = runAll(
  9471. permissionRequestedLog(undefined, "Bash").events,
  9472. ).projection.getSnapshot();
  9473. const payload = snapshot.pendingInteractions[0]?.payload;
  9474. expect(payload?.kind).toBe("permission");
  9475. expect(
  9476. payload?.kind === "permission" && payload.options.map((option) => option.optionId),
  9477. ).toEqual(["allowOnce", "allowSession", "deny"]);
  9478. });
  9479. it("no-always-allow 策略(SaveWorkflow)仍只留 Run / Deny", () => {
  9480. const turnId = "turn-1";
  9481. const log = new EventLog();
  9482. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  9483. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "save it" }, { turnId });
  9484. log.push(
  9485. SessionEventType.PermissionRequested,
  9486. {
  9487. requestId: "req-1",
  9488. toolCallId: "tc-1",
  9489. toolName: "SaveWorkflow",
  9490. riskLevel: "low",
  9491. reason: "saveWorkflow.confirmation",
  9492. input: { name: "x", script: "return 1;" },
  9493. optionsPolicy: "no-always-allow",
  9494. },
  9495. { turnId },
  9496. );
  9497. const payload = runAll(log.events).projection.getSnapshot().pendingInteractions[0]?.payload;
  9498. expect(
  9499. payload?.kind === "permission" && payload.options.map((option) => option.optionId),
  9500. ).toEqual(["allowOnce", "deny"]);
  9501. });
  9502. it("没有 display 时保持纯文本 ask,pendingApproval 行为不变", () => {
  9503. const snapshot = runAll(permissionRequestedLog().events).projection.getSnapshot();
  9504. const payload = snapshot.pendingInteractions[0]?.payload;
  9505. expect(payload?.kind).toBe("permission");
  9506. expect(payload && "display" in payload).toBe(false);
  9507. expect(snapshot.rows.window.find((row) => row.kind === "toolCall")).toMatchObject({
  9508. status: "pendingApproval",
  9509. });
  9510. });
  9511. it("协议无法承载的 display kind 不进 ask 载荷", () => {
  9512. // file_diff 不在 v4 display 联合里;直接透传会让快照 schema 解析失败。
  9513. const log = permissionRequestedLog({
  9514. kind: "file_diff",
  9515. filePath: "/workspace/a.ts",
  9516. additions: 1,
  9517. deletions: 0,
  9518. structuredPatch: [],
  9519. });
  9520. const snapshot = runAll(log.events).projection.getSnapshot();
  9521. const payload = snapshot.pendingInteractions[0]?.payload;
  9522. expect(payload && "display" in payload).toBe(false);
  9523. expect(conversationSnapshotSchema.safeParse(snapshot).success).toBe(true);
  9524. });
  9525. });
  9526. // ── dwf 实时运行态:引擎事件 → 会话事件 → workflowRuns 状态键 ──
  9527. // 见 docs/dynamic-workflow/presentation.md「The run state the pane draws」「workflowRuns 形状与界」「终态权威 patch」。
  9528. describe("ProductProjection workflowRuns(dwf 进度投影)", () => {
  9529. const RUN_ID = "dwfrun-1";
  9530. function progress(
  9531. log: EventLog,
  9532. eventType: string,
  9533. payload: Record<string, unknown>,
  9534. extra: Record<string, unknown> = {},
  9535. ): SessionEvent {
  9536. return log.push(SessionEventType.DynamicWorkflowRunProgress, {
  9537. runId: RUN_ID,
  9538. toolCallId: "tc-1",
  9539. // sequence 是 journal sequence(appendEvent 从 0 起单调分配)。
  9540. sequence: (progressSequence[RUN_ID] = (progressSequence[RUN_ID] ?? -1) + 1),
  9541. eventType,
  9542. payload,
  9543. ...extra,
  9544. });
  9545. }
  9546. const progressSequence: Record<string, number> = {};
  9547. function startedLog(caps: Record<string, unknown> = { maxConcurrency: 4 }): EventLog {
  9548. progressSequence[RUN_ID] = -1;
  9549. const log = new EventLog();
  9550. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  9551. progress(log, "run-started", { runId: RUN_ID, caps });
  9552. return log;
  9553. }
  9554. function runsOf(log: EventLog) {
  9555. return runAll(log.events).projection.getSnapshot().workflowRuns;
  9556. }
  9557. it("run-started 建条目:状态 running,用量归零,快照过 strict schema", () => {
  9558. const log = startedLog({ maxConcurrency: 2 });
  9559. const snapshot = runAll(log.events).projection.getSnapshot();
  9560. expect(snapshot.workflowRuns).toMatchObject({
  9561. revision: 1,
  9562. runs: [
  9563. {
  9564. runId: RUN_ID,
  9565. toolCallId: "tc-1",
  9566. status: "running",
  9567. usage: { spentTokens: 0, nodesUsed: 0 },
  9568. actors: [],
  9569. nodes: [],
  9570. lastEventSequence: 0,
  9571. },
  9572. ],
  9573. });
  9574. expect(conversationSnapshotSchema.safeParse(snapshot).success).toBe(true);
  9575. });
  9576. it("节点相位按 (siteId, ordinal) upsert,不新增条目", () => {
  9577. const log = startedLog();
  9578. progress(log, "node-queued", {
  9579. instance: { siteId: "ask#1", ordinal: 1 },
  9580. kind: "ask",
  9581. actor: { siteId: "actor#1", ordinal: 1 },
  9582. actorSeq: 1,
  9583. });
  9584. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9585. progress(log, "node-repairing", {
  9586. instance: { siteId: "ask#1", ordinal: 1 },
  9587. attempt: 1,
  9588. violations: [],
  9589. });
  9590. progress(log, "node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" });
  9591. const runs = runsOf(log);
  9592. expect(runs?.runs[0]?.nodes).toEqual([
  9593. {
  9594. siteId: "ask#1",
  9595. ordinal: 1,
  9596. kind: "ask",
  9597. phase: "settled",
  9598. outcome: "ok",
  9599. actorSiteId: "actor#1",
  9600. actorOrdinal: 1,
  9601. },
  9602. ]);
  9603. });
  9604. it("cached 命中只发 node-settled(无 node-queued),kind 因此缺省而条目仍成立", () => {
  9605. const log = startedLog();
  9606. progress(log, "node-settled", {
  9607. instance: { siteId: "world-read#1", ordinal: 1 },
  9608. outcome: "ok",
  9609. cached: true,
  9610. });
  9611. expect(runsOf(log)?.runs[0]?.nodes).toEqual([
  9612. { siteId: "world-read#1", ordinal: 1, phase: "settled", outcome: "ok", cached: true },
  9613. ]);
  9614. });
  9615. it("actor-created 建 actor,其状态由自己的节点派生(三态:waiting / running / completed,决策 39)", () => {
  9616. const log = startedLog();
  9617. progress(
  9618. log,
  9619. "actor-created",
  9620. { actor: { siteId: "actor#1", ordinal: 1 }, name: "planner" },
  9621. { actorSessionId: "sess_dwf-1-actor.1" },
  9622. );
  9623. expect(runsOf(log)?.runs[0]?.actors).toEqual([
  9624. {
  9625. siteId: "actor#1",
  9626. ordinal: 1,
  9627. name: "planner",
  9628. sessionId: "sess_dwf-1-actor.1",
  9629. // 尚无节点且 run 未终态 → waiting("还没派到活"),不是 completed。
  9630. status: "waiting",
  9631. },
  9632. ]);
  9633. progress(log, "node-queued", {
  9634. instance: { siteId: "ask#1", ordinal: 1 },
  9635. kind: "ask",
  9636. actor: { siteId: "actor#1", ordinal: 1 },
  9637. });
  9638. // dispatched 只是会话就绪、请求尚未准入(docs/dynamic-workflow/concurrency.md「Protocol state」):仍是 waiting。
  9639. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9640. expect(runsOf(log)?.runs[0]?.actors[0]?.status).toBe("waiting");
  9641. // 模型请求真的发出去了 → running。
  9642. progress(log, "node-executing", { instance: { siteId: "ask#1", ordinal: 1 } });
  9643. expect(runsOf(log)?.runs[0]?.actors[0]?.status).toBe("running");
  9644. progress(log, "node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" });
  9645. expect(runsOf(log)?.runs[0]?.actors[0]?.status).toBe("completed");
  9646. });
  9647. it("用量:spentTokens 直接取 usage-updated 载荷,nodesUsed 按实例首次派发计数", () => {
  9648. // docs/dynamic-workflow/authoring.md:事件自带已花总量(不再是剩余量 + 派生字段),
  9649. // 步数由派发事件计数(不再从上限反算——没有上限了)。同一实例重复派发不重复计数。
  9650. const log = startedLog({ maxConcurrency: 4 });
  9651. progress(log, "usage-updated", { spentTokens: 1_234 });
  9652. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9653. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9654. progress(log, "node-dispatched", { instance: { siteId: "ask#2", ordinal: 1 } });
  9655. expect(runsOf(log)?.runs[0]?.usage).toEqual({
  9656. spentTokens: 1_234,
  9657. nodesUsed: 2,
  9658. });
  9659. });
  9660. /**
  9661. * 终态事件产**一条** `workflowRun.updated`,把这条 run 的结算事实(status / error)一次落地。
  9662. *
  9663. * 这里刻意不再断言「终态 patch 是整键替换、丢光中间态也能收口」:改成键级增量之后,丢失的
  9664. * 中间 op 不再被下一条事件顺带补回来——那份自愈让位给了帧的 seq 连续性判定与 snapshot 重同步
  9665. * (客户端 fromSeq 对不上就整份重取)。终态事实照旧在这一条 op 里,一条也没少。
  9666. */
  9667. it("run-settled 产一条该 run 的键级增量:结算事实一次落地", () => {
  9668. const log = startedLog();
  9669. progress(log, "node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" });
  9670. const settled = progress(log, "run-settled", {
  9671. status: "errored",
  9672. error: { code: "ReportCapExceeded", message: "报告条数超过上限" },
  9673. });
  9674. const { projection, deltasPerEvent } = runAll(log.events);
  9675. const terminalDeltas = deltasPerEvent[log.events.indexOf(settled)]!;
  9676. expect(terminalDeltas).toHaveLength(1);
  9677. const updated = terminalDeltas[0]!;
  9678. expect(updated.op).toBe("workflowRun.updated");
  9679. const op = updated as {
  9680. op: "workflowRun.updated";
  9681. runId: string;
  9682. revision: number;
  9683. run?: { status?: string; error?: string };
  9684. nodes?: unknown[];
  9685. };
  9686. expect(op.runId).toBe(RUN_ID);
  9687. expect(op.run).toMatchObject({ status: "errored", error: "报告条数超过上限" });
  9688. // 节点这一步没动,所以这条增量里一条节点都不带——线上的字节与**改动量**成正比。
  9689. expect(op.nodes).toBeUndefined();
  9690. expect(op.revision).toBe(projection.getSnapshot().workflowRuns?.revision);
  9691. const run = projection.getSnapshot().workflowRuns?.runs[0];
  9692. expect(run?.status).toBe("errored");
  9693. expect(run?.nodes).toHaveLength(1);
  9694. });
  9695. it("resume:同 runId 再收 run-started 时清掉上一世的 error(进程内 cancel→resume)", () => {
  9696. // run-started 分支原样展开旧条目:cancel → resume 不经重启时,run 以 running 重现
  9697. // 却还挂着上一世的结算错误——一个正在跑的 run 同时展示失败文案。
  9698. const log = startedLog();
  9699. progress(log, "run-settled", {
  9700. status: "stopped",
  9701. stopReason: "interrupted",
  9702. error: { code: "Interrupted", message: "owning process exited" },
  9703. });
  9704. progress(log, "run-started", { runId: RUN_ID, caps: { maxConcurrency: 4 } });
  9705. const runs = runsOf(log)?.runs ?? [];
  9706. expect(runs).toHaveLength(1);
  9707. expect(runs[0]).toMatchObject({ runId: RUN_ID, status: "running" });
  9708. expect(runs[0]?.error).toBeUndefined();
  9709. expect(runs[0]?.resultPreview).toBeUndefined();
  9710. });
  9711. it("revision 单调,lastEventSequence 随 journal sequence 抬升", () => {
  9712. const log = startedLog();
  9713. progress(log, "node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" });
  9714. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9715. const { snapshots } = runAll(log.events);
  9716. const revisions = snapshots
  9717. .map((snapshot) => snapshot.workflowRuns?.revision)
  9718. .filter((revision): revision is number => revision !== undefined);
  9719. expect(revisions).toEqual([1, 2, 3]);
  9720. expect(snapshots.at(-1)?.workflowRuns?.runs[0]?.lastEventSequence).toBe(2);
  9721. });
  9722. it("四个数组的界:nodes 超上限置 truncated 且不再增长,被拒实例进计数器", () => {
  9723. const rejected = 5;
  9724. const log = startedLog();
  9725. for (let ordinal = 1; ordinal <= WORKFLOW_RUNS_LIMITS.maxNodes + rejected; ordinal += 1) {
  9726. progress(log, "node-queued", { instance: { siteId: "ask#1", ordinal }, kind: "ask" });
  9727. }
  9728. const run = runsOf(log)?.runs[0];
  9729. expect(run?.nodes).toHaveLength(WORKFLOW_RUNS_LIMITS.maxNodes);
  9730. expect(run?.truncated).toBe(true);
  9731. // `truncated` 只说得出「有东西没进来」;到底少了几步要靠计数器,否则读面上的步数
  9732. // 会比真实步数小,而且小多少没人说得清。
  9733. expect(run?.usage.nodesUnlisted).toBe(rejected);
  9734. expect(run?.usage.nodesUnlistedSettled).toBeUndefined();
  9735. // 读面唯一允许的步数读法 = 表内 + 表外。
  9736. expect(workflowRunStepCounts(run!)).toEqual({
  9737. total: WORKFLOW_RUNS_LIMITS.maxNodes + rejected,
  9738. settled: 0,
  9739. });
  9740. // 已在表内的实例仍可继续更新相位(超界只拒绝**新**实例)。
  9741. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9742. expect(runsOf(log)?.runs[0]?.nodes[0]?.phase).toBe("dispatched");
  9743. // 表外实例的结算同样要数得出来:它一条节点行都没有,只能落在第二个计数器上。
  9744. progress(log, "node-settled", {
  9745. instance: { siteId: "ask#1", ordinal: WORKFLOW_RUNS_LIMITS.maxNodes + 1 },
  9746. outcome: "ok",
  9747. });
  9748. const settledRun = runsOf(log)!.runs[0]!;
  9749. expect(settledRun.usage.nodesUnlistedSettled).toBe(1);
  9750. expect(workflowRunStepCounts(settledRun)).toEqual({
  9751. total: WORKFLOW_RUNS_LIMITS.maxNodes + rejected,
  9752. settled: 1,
  9753. });
  9754. });
  9755. /**
  9756. * 一条引擎事件 → **一条**该 run 的键级增量,且只带动过的那条节点。
  9757. *
  9758. * 这一条是整次改造的验收点:旧编码在这里会重发整张表(此处 16 条节点),线上的字节因此与
  9759. * 状态大小成正比而不是与改动量成正比——O(N) 字节/事件、O(N²)/run,节点上界与宽 fan-out
  9760. * 撞界丢实例都是这笔账的下游。
  9761. */
  9762. it("一条事件只发动过的那条节点,别的 run 一个字节都不带", () => {
  9763. const log = startedLog();
  9764. for (let ordinal = 1; ordinal <= 16; ordinal += 1) {
  9765. progress(log, "node-queued", { instance: { siteId: "ask#1", ordinal }, kind: "ask" });
  9766. }
  9767. // 第二条 run:它这一步没变化,所以不该出现在增量里。
  9768. log.push(SessionEventType.DynamicWorkflowRunProgress, {
  9769. runId: "dwfrun-other",
  9770. sequence: 0,
  9771. eventType: "run-started",
  9772. payload: { runId: "dwfrun-other", caps: { maxConcurrency: 1 } },
  9773. });
  9774. const dispatched = progress(log, "node-dispatched", {
  9775. instance: { siteId: "ask#1", ordinal: 7 },
  9776. });
  9777. const { deltasPerEvent, projection } = runAll(log.events);
  9778. const deltas = deltasPerEvent[log.events.indexOf(dispatched)]!;
  9779. expect(deltas).toHaveLength(1);
  9780. const op = deltas[0] as {
  9781. op: string;
  9782. runId: string;
  9783. nodes?: { siteId: string; ordinal: number; phase: string; kind?: string }[];
  9784. run?: Record<string, unknown>;
  9785. actors?: unknown[];
  9786. };
  9787. expect(op.op).toBe("workflowRun.updated");
  9788. expect(op.runId).toBe(RUN_ID);
  9789. expect(op.nodes).toEqual([{ siteId: "ask#1", ordinal: 7, kind: "ask", phase: "dispatched" }]);
  9790. expect(op.actors).toBeUndefined();
  9791. // header 只带真的动过的键(水位与派发计数),不含 nodes/actors 之外的整表。
  9792. expect(Object.keys(op.run ?? {}).toSorted()).toEqual(["lastEventSequence", "usage"]);
  9793. // 增量应用回去之后,权威状态仍是归约本身的产物(契约:逐字节一致)。
  9794. const authoritative = projection.getSnapshot().workflowRuns!;
  9795. expect(authoritative.runs.map((run) => run.runId)).toEqual([RUN_ID, "dwfrun-other"]);
  9796. expect(authoritative.runs[0]!.nodes).toHaveLength(16);
  9797. expect(authoritative.runs[0]!.nodes[6]).toEqual({
  9798. siteId: "ask#1",
  9799. ordinal: 7,
  9800. kind: "ask",
  9801. phase: "dispatched",
  9802. });
  9803. });
  9804. it("run 被条数界淘汰时发 workflowRun.removed(只有生产者淘汰,而且必须说出来)", () => {
  9805. const log = new EventLog();
  9806. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  9807. for (let index = 0; index <= WORKFLOW_RUNS_LIMITS.maxRuns; index += 1) {
  9808. log.push(SessionEventType.DynamicWorkflowRunProgress, {
  9809. runId: `dwfrun-${index}`,
  9810. sequence: 0,
  9811. eventType: "run-started",
  9812. payload: { runId: `dwfrun-${index}`, caps: { maxConcurrency: 1 } },
  9813. });
  9814. }
  9815. const { deltasPerEvent } = runAll(log.events);
  9816. // 第 9 条 run 出生的那一条事件同时淘汰了第 1 条:淘汰先发,出生随后。
  9817. const evicting = deltasPerEvent.at(-1)!;
  9818. expect(evicting.map((delta) => delta.op)).toEqual([
  9819. "workflowRun.removed",
  9820. "workflowRun.updated",
  9821. ]);
  9822. expect((evicting[0] as { runId: string }).runId).toBe("dwfrun-0");
  9823. expect((evicting[1] as { runId: string }).runId).toBe(`dwfrun-${WORKFLOW_RUNS_LIMITS.maxRuns}`);
  9824. });
  9825. it("runs ≤ 8 且按最旧淘汰", () => {
  9826. const log = new EventLog();
  9827. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  9828. for (let index = 0; index < WORKFLOW_RUNS_LIMITS.maxRuns + 3; index += 1) {
  9829. log.push(SessionEventType.DynamicWorkflowRunProgress, {
  9830. runId: `dwfrun-${index}`,
  9831. sequence: 0,
  9832. eventType: "run-started",
  9833. payload: { runId: `dwfrun-${index}`, caps: { maxConcurrency: 1 } },
  9834. });
  9835. }
  9836. const runs = runAll(log.events).projection.getSnapshot().workflowRuns?.runs ?? [];
  9837. expect(runs.map((run) => run.runId)).toEqual([
  9838. "dwfrun-3",
  9839. "dwfrun-4",
  9840. "dwfrun-5",
  9841. "dwfrun-6",
  9842. "dwfrun-7",
  9843. "dwfrun-8",
  9844. "dwfrun-9",
  9845. "dwfrun-10",
  9846. ]);
  9847. });
  9848. it("log 与 usage 事件不进图:它们没有 site id,只进事件日志", () => {
  9849. const log = startedLog();
  9850. progress(log, "log", { message: "开始" });
  9851. const run = runsOf(log)?.runs[0];
  9852. expect(run?.nodes).toEqual([]);
  9853. expect(run?.actors).toEqual([]);
  9854. // 但它仍抬升 lastEventSequence——事件日志需要知道有新内容可取。
  9855. expect(run?.lastEventSequence).toBe(1);
  9856. });
  9857. // R-10:两个 profile 的终态必须逐字节一致,所以 workflowRuns 的增量一条都不能被 profile 过滤
  9858. // 掉(`profiles.ts` 只滤 row.delta)。桌面 continuous 与手机 replayable 收到的是同一串 op。
  9859. it("键级增量不受 delivery profile 门控(记录在案的偏离)", () => {
  9860. const log = startedLog();
  9861. const dispatched = progress(log, "node-dispatched", {
  9862. instance: { siteId: "ask#1", ordinal: 1 },
  9863. });
  9864. const { deltasPerEvent } = runAll(log.events);
  9865. const deltas = deltasPerEvent[log.events.indexOf(dispatched)]!;
  9866. expect(deltas.some((delta) => delta.op === "workflowRun.updated")).toBe(true);
  9867. for (const profile of Object.values(DELIVERY_PROFILES) as DeliveryProfile[]) {
  9868. expect(filterConversationDeltasForProfile(deltas, profile)).toEqual(deltas);
  9869. }
  9870. });
  9871. it("同一 run 的重复事件幂等:内容不变不产 delta", () => {
  9872. const log = startedLog();
  9873. progress(log, "node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" });
  9874. const { projection } = runAll(log.events);
  9875. const before = projection.getSnapshot().workflowRuns?.revision;
  9876. // 同一条事件重放(同 sequence、同内容)。
  9877. const replay = log.events.at(-1)!;
  9878. expect(projection.applyEvent(replay)).toEqual([]);
  9879. expect(projection.getSnapshot().workflowRuns?.revision).toBe(before);
  9880. });
  9881. // ── report 事件 → reports[](docs/dynamic-workflow/presentation.md「The run pane」)──
  9882. // 数据面是详情页 Results 区的全部输入;Results 区本身在 packages/ui 的 jsdom 用例里钉。
  9883. it("report 事件按顺序追加进 reports[]:string 原样,object 走 pretty JSON", () => {
  9884. const log = startedLog();
  9885. progress(log, "report", {
  9886. instance: { siteId: "report#1", ordinal: 1 },
  9887. item: "3 stale imports",
  9888. });
  9889. progress(log, "report", {
  9890. instance: { siteId: "report#2", ordinal: 1 },
  9891. item: { file: "a.ts", severity: "warn" },
  9892. });
  9893. const snapshot = runAll(log.events).projection.getSnapshot();
  9894. expect(snapshot.workflowRuns?.runs[0]?.reports).toEqual([
  9895. { siteId: "report#1", ordinal: 1, preview: "3 stale imports" },
  9896. {
  9897. siteId: "report#2",
  9898. ordinal: 1,
  9899. preview: '{\n "file": "a.ts",\n "severity": "warn"\n}',
  9900. },
  9901. ]);
  9902. expect(conversationSnapshotSchema.safeParse(snapshot).success).toBe(true);
  9903. });
  9904. it("零条 report 时 reports 键整个缺席(Results 区据此整区不渲染)", () => {
  9905. const log = startedLog();
  9906. progress(log, "node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" });
  9907. expect(runsOf(log)?.runs[0]).not.toHaveProperty("reports");
  9908. });
  9909. /**
  9910. * 这一条是 report 与 node 分类的凭证:report 有 site 身份、进 journal、有自己的 RunEvent,
  9911. * 但它**不是 step**。混进 nodes[] 的代价是可观测的——紧凑卡与任务岛的 `settled/observed`
  9912. * 步数读的就是 nodes,一个报得勤的工作流会显得步数虚高,状态叠加也会多亮一格。
  9913. */
  9914. it("report 不进 nodes[]/actors,也不动 nodesUsed;但抬升 lastEventSequence", () => {
  9915. const log = startedLog({ maxConcurrency: 4 });
  9916. progress(log, "node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" });
  9917. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9918. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: "a finding" });
  9919. const run = runsOf(log)?.runs[0];
  9920. expect(run?.nodes.map((node) => node.siteId)).toEqual(["ask#1"]);
  9921. expect(run?.actors).toEqual([]);
  9922. expect(run?.usage.nodesUsed).toBe(1);
  9923. expect(run?.reports).toHaveLength(1);
  9924. // 事件日志要知道有新内容可取,所以水位照常抬升。
  9925. expect(run?.lastEventSequence).toBe(3);
  9926. });
  9927. it("失败结算之后 reports 原样留着:捞回半途产物正是 report 存在的理由", () => {
  9928. const log = startedLog();
  9929. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: "finding 1" });
  9930. progress(log, "run-settled", {
  9931. status: "errored",
  9932. error: { code: "DriverError", message: "boom" },
  9933. });
  9934. const run = runsOf(log)?.runs[0];
  9935. expect(run?.status).toBe("errored");
  9936. expect(run?.reports).toEqual([{ siteId: "report#1", ordinal: 1, preview: "finding 1" }]);
  9937. });
  9938. it("同一 report 事件重放(同 sequence 同内容)不产 delta、不重复条目", () => {
  9939. const log = startedLog();
  9940. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: "once" });
  9941. const { projection } = runAll(log.events);
  9942. const before = projection.getSnapshot().workflowRuns?.revision;
  9943. expect(projection.applyEvent(log.events.at(-1)!)).toEqual([]);
  9944. expect(projection.getSnapshot().workflowRuns?.revision).toBe(before);
  9945. expect(projection.getSnapshot().workflowRuns?.runs[0]?.reports).toHaveLength(1);
  9946. });
  9947. /**
  9948. * 去重键是实例(siteId × ordinal),不是事件 sequence——脚本 replay 时每个 report 调用都会
  9949. * 重跑。所以一条**新 sequence** 却带已见实例的事件只抬水位,绝不把同一条产物列两次。
  9950. */
  9951. it("新 sequence 带已见实例键:水位抬升,条目不重复", () => {
  9952. const log = startedLog();
  9953. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: "once" });
  9954. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: "once" });
  9955. const run = runsOf(log)?.runs[0];
  9956. expect(run?.reports).toEqual([{ siteId: "report#1", ordinal: 1, preview: "once" }]);
  9957. expect(run?.lastEventSequence).toBe(2);
  9958. });
  9959. it("reports 触到 64 条上限:拒绝新条目并置 truncated,已有条目照常更新", () => {
  9960. const log = startedLog();
  9961. for (let ordinal = 1; ordinal <= WORKFLOW_RUNS_LIMITS.maxReports + 3; ordinal += 1) {
  9962. progress(log, "report", {
  9963. instance: { siteId: "report#1", ordinal },
  9964. item: `finding ${ordinal}`,
  9965. });
  9966. }
  9967. const run = runsOf(log)?.runs[0];
  9968. expect(run?.reports).toHaveLength(WORKFLOW_RUNS_LIMITS.maxReports);
  9969. expect(run?.truncated).toBe(true);
  9970. // 先到的条目不被后来的挤掉(淘汰会让读者以为早期发现丢了;界的语义是拒新)。
  9971. expect(run?.reports?.[0]?.preview).toBe("finding 1");
  9972. // 触界之后其余键照常更新:结算与水位都不受影响。
  9973. progress(log, "run-settled", { status: "completed" });
  9974. const settled = runsOf(log)?.runs[0];
  9975. expect(settled?.status).toBe("completed");
  9976. expect(settled?.reports).toHaveLength(WORKFLOW_RUNS_LIMITS.maxReports);
  9977. });
  9978. it("单条预览超界即截断(带省略号),仍过 strict schema", () => {
  9979. const log = startedLog();
  9980. // 载荷有界化已经把单个字符串削到 2048,所以真正会超界的是「键多的对象展开成 pretty JSON」。
  9981. const wide: Record<string, string> = {};
  9982. for (let index = 0; index < 64; index += 1) wide[`key${index}`] = "x".repeat(64);
  9983. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: wide });
  9984. const snapshot = runAll(log.events).projection.getSnapshot();
  9985. const preview = snapshot.workflowRuns?.runs[0]?.reports?.[0]?.preview ?? "";
  9986. expect(preview.length).toBe(WORKFLOW_RUNS_LIMITS.maxReportPreviewLength);
  9987. expect(preview.endsWith("…")).toBe(true);
  9988. expect(conversationSnapshotSchema.safeParse(snapshot).success).toBe(true);
  9989. });
  9990. it("instance 缺失的 report 事件被忽略(不造无身份条目),但仍抬水位", () => {
  9991. const log = startedLog();
  9992. progress(log, "report", { item: "orphan" });
  9993. const run = runsOf(log)?.runs[0];
  9994. expect(run).not.toHaveProperty("reports");
  9995. expect(run?.lastEventSequence).toBe(1);
  9996. });
  9997. });
  9998. // 中枢直接启动已保存工作流(docs/dynamic-workflow/launch.md):controlOnly 启动轮的活投影。
  9999. // TurnStarted(workflow_launch) → turnHeader/userInput 双行 origin=workflowLaunch + 同一份元数据,
  10000. // 无助手行;TurnComplete 收口后 header 变 completed(controlOnly 不下发 running/工时)。
  10001. describe("workflow-direct-launch 启动轮投影", () => {
  10002. const workflowLaunch = {
  10003. runId: "dwfrun-9",
  10004. toolCallId: "launch-abc",
  10005. name: "deep-research",
  10006. scope: "global" as const,
  10007. path: "/home/u/.zcode/workflows/deep-research.ts",
  10008. args: { topic: "adaptive concurrency" },
  10009. description: "Deep-dive a topic",
  10010. };
  10011. function launchEvents(): SessionEvent[] {
  10012. const log = new EventLog();
  10013. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  10014. log.push(
  10015. SessionEventType.TurnStarted,
  10016. {
  10017. turnNumber: 1,
  10018. input: 'Started the saved workflow "deep-research" (global) as run dwfrun-9.',
  10019. messageId: "message-launch-1",
  10020. executionKind: "controlOnly",
  10021. inputSource: "workflow_launch",
  10022. workflowLaunch,
  10023. },
  10024. { turnId: "turn-launch" },
  10025. );
  10026. log.push(
  10027. SessionEventType.TurnComplete,
  10028. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  10029. { turnId: "turn-launch" },
  10030. );
  10031. return log.events;
  10032. }
  10033. it("双行 origin=workflowLaunch 且都带启动元数据,无助手行", () => {
  10034. const snapshot = runAll(launchEvents()).projection.getSnapshot();
  10035. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  10036. const rows = snapshot.rows.window;
  10037. expect(rows.map((row) => row.kind)).toEqual(["turnHeader", "userInput"]);
  10038. const header = rows.find((row) => row.kind === "turnHeader");
  10039. expect(header).toMatchObject({
  10040. origin: "workflowLaunch",
  10041. executionKind: "controlOnly",
  10042. state: "completedSuccess",
  10043. workflowLaunch,
  10044. });
  10045. const userInput = rows.find((row) => row.kind === "userInput");
  10046. expect(userInput).toMatchObject({
  10047. origin: "workflowLaunch",
  10048. text: 'Started the saved workflow "deep-research" (global) as run dwfrun-9.',
  10049. workflowLaunch,
  10050. });
  10051. // controlOnly:不残留 running / activeWorks(旧 UI 会把 0ms 误显示成「已工作 1 秒」)。
  10052. expect(snapshot.control.activeWorks).toEqual([]);
  10053. });
  10054. it("启动轮收口让会话离开 draft:phase 成终态,sessions-index 摘要不再被当 draft 丢弃", () => {
  10055. // 2026-09-14 实机:只有一条 controlOnly 启动轮的会话活投影恒为 draft,task-index syncer 丢弃 draft
  10056. // 摘要,侧栏要等重启(store 种子给出终态 phase)才出现。冷热必须同形。
  10057. const events = launchEvents();
  10058. const { projection } = runAll(events.slice(0, 2));
  10059. expect(projection.getSnapshot().control.phase).toBe("draft");
  10060. projection.applyEvent(events[2]!);
  10061. const control = projection.getSnapshot().control;
  10062. expect(control.phase).toBe("completedSuccess");
  10063. expect(control.sessionEnded).toBe(true);
  10064. expect(control.canStop).toBe(false);
  10065. expect(control.activeWorks).toEqual([]);
  10066. });
  10067. it("非 draft 会话上的 controlOnly 轮照旧不碰 session control", () => {
  10068. const log = new EventLog();
  10069. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  10070. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  10071. log.push(
  10072. SessionEventType.TurnComplete,
  10073. { response: "", tokenCount: 0, toolCallCount: 0, duration: 5, resultType: "cancelled" },
  10074. { turnId: "turn-1" },
  10075. );
  10076. log.push(
  10077. SessionEventType.TurnStarted,
  10078. { turnNumber: 2, input: "/goal x", executionKind: "controlOnly" },
  10079. { turnId: "turn-2" },
  10080. );
  10081. log.push(
  10082. SessionEventType.TurnComplete,
  10083. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  10084. { turnId: "turn-2" },
  10085. );
  10086. const snapshot = runAll(log.events).projection.getSnapshot();
  10087. // 上一轮的中断终态保留,控制轮的 success 不改写它。
  10088. expect(snapshot.control.phase).toBe("completedInterrupted");
  10089. });
  10090. });
  10091. // docs/dynamic-workflow/transcript-and-notifications.md:TurnStarted 上的 epilogueStart 原样落到
  10092. // userInput 行;缺席时行上没有这个键(老转录逐字不变)。
  10093. describe("userInput 行的 epilogueStart(热路径)", () => {
  10094. it("透传 TurnStarted.epilogueStart;缺席不写键", () => {
  10095. const log = new EventLog();
  10096. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  10097. log.push(
  10098. SessionEventType.TurnStarted,
  10099. { turnNumber: 1, input: "Summarize\n\n---\nStandard", epilogueStart: 9 },
  10100. { turnId: "turn-1" },
  10101. );
  10102. log.push(SessionEventType.TurnStarted, { turnNumber: 2, input: "plain" }, { turnId: "turn-2" });
  10103. const { projection } = runAll(log.events);
  10104. const rows = projection.getSnapshot().rows.window.filter((row) => row.kind === "userInput");
  10105. expect(rows[0]).toMatchObject({ text: "Summarize\n\n---\nStandard", epilogueStart: 9 });
  10106. expect(rows[1]).not.toHaveProperty("epilogueStart");
  10107. });
  10108. });