product-projection.test.ts 349 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245
  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 } 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. // ── B 组:stop / 迟到终态 ──
  1352. it("B:cancelled turn —— streaming 行收口为 interrupted,phase=completedInterrupted", () => {
  1353. const log = new EventLog();
  1354. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1355. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  1356. log.push(
  1357. SessionEventType.ModelStreaming,
  1358. { kind: "text_start", delta: "", done: false },
  1359. { turnId: "turn-1" },
  1360. );
  1361. log.push(
  1362. SessionEventType.ModelStreaming,
  1363. { kind: "text_delta", delta: "partial", done: false },
  1364. { turnId: "turn-1" },
  1365. );
  1366. log.push(
  1367. SessionEventType.TurnComplete,
  1368. { response: "", tokenCount: 0, toolCallCount: 0, duration: 1000, resultType: "cancelled" },
  1369. { turnId: "turn-1" },
  1370. );
  1371. const { projection } = runAll(log.events);
  1372. const snapshot = projection.getSnapshot();
  1373. expect(snapshot.control.phase).toBe("completedInterrupted");
  1374. const assistant = snapshot.rows.window.find((row) => row.kind === "assistantText");
  1375. expect(assistant).toMatchObject({ text: "partial", state: "interrupted" });
  1376. const header = snapshot.rows.window.find((row) => row.kind === "turnHeader");
  1377. expect(header).toMatchObject({ state: "completedInterrupted" });
  1378. });
  1379. it("B/结构性2:stop 后迟到的流式/工具终态被拒收,投影逐字节不变", () => {
  1380. const log = new EventLog();
  1381. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1382. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  1383. log.push(
  1384. SessionEventType.TurnComplete,
  1385. { response: "", tokenCount: 0, toolCallCount: 0, duration: 100, resultType: "cancelled" },
  1386. { turnId: "turn-1" },
  1387. );
  1388. const { projection } = runAll(log.events);
  1389. const before = structuredClone(projection.getSnapshot());
  1390. const late = new EventLog();
  1391. late.push(
  1392. SessionEventType.ModelStreaming,
  1393. { kind: "text_delta", delta: "ghost", done: false },
  1394. { turnId: "turn-1" },
  1395. );
  1396. late.push(
  1397. SessionEventType.ToolCallResult,
  1398. { toolCallId: "tc-1", result: { success: true, content: "ghost" }, duration: 1 },
  1399. { turnId: "turn-1" },
  1400. );
  1401. for (const event of late.events) {
  1402. expect(projection.applyEvent(event)).toEqual([]);
  1403. }
  1404. expect({ ...projection.getSnapshot(), seq: before.seq }).toEqual(before);
  1405. });
  1406. // ── O/Q 组:tool call 状态机与权限交互 ──
  1407. it("CUA:PID 工具按事件顺序固化最近一次成功 list_apps 快照", () => {
  1408. const turnId = "turn-cua-app-snapshot";
  1409. const log = new EventLog();
  1410. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1411. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "操作应用" }, { turnId });
  1412. const listApps = (id: string, name: string, success = true) => {
  1413. log.push(
  1414. SessionEventType.ToolCallScheduled,
  1415. {
  1416. toolCallId: id,
  1417. toolName: "mcp__computer-use__list_apps",
  1418. input: {},
  1419. schedule: { parallelGroups: [[id]], executionOrder: [id] },
  1420. },
  1421. { turnId },
  1422. );
  1423. log.push(
  1424. SessionEventType.ToolCallResult,
  1425. {
  1426. toolCallId: id,
  1427. result: {
  1428. success,
  1429. content: success
  1430. ? JSON.stringify([{ pid: 42, name, bundle_id: `com.example.${name}` }])
  1431. : "failed",
  1432. ...(!success ? { error: { type: "toolFailed", message: "failed" } } : {}),
  1433. },
  1434. duration: 1,
  1435. },
  1436. { turnId },
  1437. );
  1438. };
  1439. const scheduleKey = (
  1440. id: string,
  1441. toolName = "mcp__computer-use__key",
  1442. appRef: unknown = { pid: 42 },
  1443. ) =>
  1444. log.push(
  1445. SessionEventType.ToolCallScheduled,
  1446. {
  1447. toolCallId: id,
  1448. toolName,
  1449. input: { app_ref: appRef, key: "TAB" },
  1450. schedule: { parallelGroups: [[id]], executionOrder: [id] },
  1451. },
  1452. { turnId },
  1453. );
  1454. listApps("list-1", "One");
  1455. scheduleKey("key-1");
  1456. listApps("list-failed", "Ignored", false);
  1457. scheduleKey("key-after-failure");
  1458. listApps("list-2", "Two");
  1459. scheduleKey("key-2");
  1460. scheduleKey("bundle-only", "mcp__computer-use__get_app_state", {
  1461. bundle_id: "com.example.Two",
  1462. });
  1463. scheduleKey("serialized-pid", "mcp__computer-use__get_app_state", '{"pid":42}');
  1464. scheduleKey("lookalike", "mcp__other__computer-use__key");
  1465. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  1466. const appOf = (id: string) => {
  1467. const row = rows.find(
  1468. (candidate) => candidate.kind === "toolCall" && candidate.toolCallId === id,
  1469. );
  1470. return row?.kind === "toolCall" ? row.cuaApp : undefined;
  1471. };
  1472. expect(appOf("key-1")).toEqual({ pid: 42, name: "One", bundleId: "com.example.One" });
  1473. expect(appOf("key-after-failure")).toEqual({
  1474. pid: 42,
  1475. name: "One",
  1476. bundleId: "com.example.One",
  1477. });
  1478. expect(appOf("key-2")).toEqual({ pid: 42, name: "Two", bundleId: "com.example.Two" });
  1479. expect(appOf("bundle-only")).toEqual({
  1480. pid: 42,
  1481. name: "Two",
  1482. bundleId: "com.example.Two",
  1483. });
  1484. expect(appOf("serialized-pid")).toEqual({
  1485. pid: 42,
  1486. name: "Two",
  1487. bundleId: "com.example.Two",
  1488. });
  1489. expect(appOf("lookalike")).toBeUndefined();
  1490. });
  1491. it("CUA:原子实时投影提交后保留 list_apps 快照", () => {
  1492. const turnId = "turn-cua-atomic-snapshot";
  1493. const log = new EventLog();
  1494. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1495. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "操作飞书" }, { turnId });
  1496. log.push(
  1497. SessionEventType.ToolCallScheduled,
  1498. {
  1499. toolCallId: "list-apps",
  1500. toolName: "mcp__computer-use__list_apps",
  1501. input: {},
  1502. schedule: { parallelGroups: [["list-apps"]], executionOrder: ["list-apps"] },
  1503. },
  1504. { turnId },
  1505. );
  1506. log.push(
  1507. SessionEventType.ToolCallResult,
  1508. {
  1509. toolCallId: "list-apps",
  1510. result: {
  1511. success: true,
  1512. content: JSON.stringify([{ pid: 691, name: "Feishu", bundle_id: "com.electron.lark" }]),
  1513. },
  1514. duration: 1,
  1515. },
  1516. { turnId },
  1517. );
  1518. log.push(
  1519. SessionEventType.ToolCallScheduled,
  1520. {
  1521. toolCallId: "get-app-state",
  1522. toolName: "mcp__computer-use__get_app_state",
  1523. input: { app_ref: '{"pid":691}', title: "查看飞书当前界面" },
  1524. schedule: {
  1525. parallelGroups: [["get-app-state"]],
  1526. executionOrder: ["get-app-state"],
  1527. },
  1528. },
  1529. { turnId },
  1530. );
  1531. const projection = new ProductProjection("session-1", "epoch-1");
  1532. for (const event of log.events) {
  1533. expect(projection.applyEventAtomically(event, () => true)).not.toBeNull();
  1534. }
  1535. const row = projection
  1536. .getSnapshot()
  1537. .rows.window.find(
  1538. (candidate) => candidate.kind === "toolCall" && candidate.toolCallId === "get-app-state",
  1539. );
  1540. expect(row?.kind === "toolCall" ? row.cuaApp : undefined).toEqual({
  1541. pid: 691,
  1542. name: "Feishu",
  1543. bundleId: "com.electron.lark",
  1544. });
  1545. });
  1546. it("BTA01:保留 turn-end Node REPL 图片 display 到 live tool row", () => {
  1547. const turnId = "turn-browser-shot";
  1548. const toolCallId = "tool-browser-shot";
  1549. const log = new EventLog();
  1550. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1551. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "打开页面" }, { turnId });
  1552. log.push(
  1553. SessionEventType.ToolCallScheduled,
  1554. {
  1555. toolCallId,
  1556. toolName: "mcp__node_repl__js",
  1557. input: { source: "browser_turn_end" },
  1558. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1559. },
  1560. { turnId },
  1561. );
  1562. log.push(
  1563. SessionEventType.ToolCallResult,
  1564. {
  1565. toolCallId,
  1566. result: {
  1567. success: true,
  1568. content: "",
  1569. display: {
  1570. kind: "node_repl_images",
  1571. source: "browser_turn_end",
  1572. images: [{ base64: "AAAA", mimeType: "image/png" }],
  1573. },
  1574. },
  1575. duration: 0,
  1576. },
  1577. { turnId },
  1578. );
  1579. const snapshot = runAll(log.events).projection.getSnapshot();
  1580. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  1581. expect(
  1582. snapshot.rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  1583. ).toMatchObject({
  1584. status: "success",
  1585. display: { kind: "node_repl_images", source: "browser_turn_end" },
  1586. });
  1587. });
  1588. it("CUA:保留实时工具结果的截图 display 到 output", () => {
  1589. const turnId = "turn-cua-screenshot";
  1590. const toolCallId = "tool-cua-screenshot";
  1591. const log = new EventLog();
  1592. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1593. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "截图" }, { turnId });
  1594. log.push(
  1595. SessionEventType.ToolCallScheduled,
  1596. {
  1597. toolCallId,
  1598. toolName: "mcp__computer-use__computer-use",
  1599. input: { action: "screenshot" },
  1600. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1601. },
  1602. { turnId },
  1603. );
  1604. log.push(
  1605. SessionEventType.ToolCallResult,
  1606. {
  1607. toolCallId,
  1608. result: {
  1609. success: true,
  1610. content: "[Attached image/jpeg: MCP image]",
  1611. display: {
  1612. kind: "cua",
  1613. schemaVersion: 1,
  1614. toolName: "computer-use",
  1615. status: "success",
  1616. input: '{"action":"screenshot"}',
  1617. media: [{ mimeType: "image/jpeg", data: "AAAA" }],
  1618. },
  1619. },
  1620. duration: 10,
  1621. },
  1622. { turnId },
  1623. );
  1624. expect(
  1625. runAll(log.events)
  1626. .projection.getSnapshot()
  1627. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  1628. ).toMatchObject({
  1629. status: "success",
  1630. output: {
  1631. text: "[Attached image/jpeg: MCP image]",
  1632. display: {
  1633. kind: "cua",
  1634. media: [{ mimeType: "image/jpeg", data: "AAAA" }],
  1635. },
  1636. },
  1637. });
  1638. });
  1639. it.each([
  1640. {
  1641. toolName: "TaskOutput",
  1642. display: {
  1643. kind: "task_output",
  1644. retrievalStatus: "not_ready",
  1645. taskStatus: "running",
  1646. output: "partial output",
  1647. } as const,
  1648. },
  1649. {
  1650. toolName: "RespondToCoordinator",
  1651. display: {
  1652. kind: "respond_to_coordinator",
  1653. status: "success",
  1654. } as const,
  1655. },
  1656. {
  1657. toolName: "CreateWorkflow",
  1658. display: {
  1659. kind: "create_workflow",
  1660. ok: true,
  1661. errorCount: 0,
  1662. diagnostics: [],
  1663. causalityGraph: {
  1664. steps: [
  1665. {
  1666. id: "ask#1",
  1667. kind: "ask",
  1668. label: "scout",
  1669. line: 3,
  1670. column: 20,
  1671. lane: "actor#1",
  1672. },
  1673. ],
  1674. lanes: [{ id: "actor#1", name: "scout", line: 3, column: 11 }],
  1675. // 第二层是子代理导向:每阶段一张参与者卡 + 交接边(docs/dynamic-workflow/presentation.md)。
  1676. participants: [
  1677. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] },
  1678. ],
  1679. handoffs: [],
  1680. sink: ["ask#1"],
  1681. },
  1682. } as const,
  1683. },
  1684. // 观察类工作流工具的五个 display kind(spec:docs/dynamic-workflow/launch.md「Run introspection tools」
  1685. // 「工具卡 display」、同文件「The model catalog」)——whitelist 不放行就整块被剥,UI 只能退回文本投影。
  1686. {
  1687. toolName: "GetWorkflowRun",
  1688. display: {
  1689. kind: "get_workflow_run",
  1690. runId: "wf_demo",
  1691. label: "demo",
  1692. status: "running",
  1693. usage: {
  1694. spentTokens: 1_000,
  1695. nodesObserved: 3,
  1696. nodesRunning: 1,
  1697. nodesCompleted: 2,
  1698. nodesFailed: 0,
  1699. },
  1700. actors: [{ siteId: "agent#1", ordinal: 1, name: "scout" }],
  1701. logTail: [{ sequence: 1, message: "started" }],
  1702. } as const,
  1703. },
  1704. {
  1705. toolName: "ListWorkflowRuns",
  1706. display: {
  1707. kind: "list_workflow_runs",
  1708. runs: [
  1709. {
  1710. runId: "wf_demo",
  1711. label: "demo",
  1712. labelSource: "name",
  1713. status: "completed",
  1714. ownedByThisSession: true,
  1715. createdAt: 1,
  1716. updatedAt: 2,
  1717. spentTokens: 42,
  1718. },
  1719. ],
  1720. } as const,
  1721. },
  1722. {
  1723. toolName: "EvalWorkflowSnippet",
  1724. display: {
  1725. kind: "eval_workflow_snippet",
  1726. ok: true,
  1727. diagnostics: [],
  1728. logs: ["glob matched 3 files"],
  1729. response: "3",
  1730. durationMs: 120,
  1731. } as const,
  1732. },
  1733. {
  1734. toolName: "ResumeWorkflowRun",
  1735. display: {
  1736. kind: "resume_workflow_run",
  1737. runId: "wf_demo",
  1738. } as const,
  1739. },
  1740. // 模型目录卡(spec:docs/dynamic-workflow/launch.md「The model catalog」):白名单漏了它,
  1741. // UI 只能退回那段以 providerId 开头的 `<models>` 文本。
  1742. {
  1743. toolName: "ListModels",
  1744. display: {
  1745. kind: "list_models",
  1746. current: "account:bigmodel-team-coding-plan/GLM-5.3-Flash",
  1747. models: [
  1748. {
  1749. id: "account:bigmodel-team-coding-plan/GLM-5.3-Flash",
  1750. providerId: "account:bigmodel-team-coding-plan",
  1751. modelId: "GLM-5.3-Flash",
  1752. providerLabel: "BigModel",
  1753. reasoningLevels: ["low", "medium", "high"],
  1754. defaultReasoningLevel: "high",
  1755. contextWindow: 128_000,
  1756. },
  1757. ],
  1758. } as const,
  1759. },
  1760. {
  1761. toolName: "ListSavedWorkflows",
  1762. display: {
  1763. kind: "saved_workflow_list",
  1764. workflows: [
  1765. {
  1766. name: "nightly-sync",
  1767. scope: "project",
  1768. path: ".zcode/workflows/nightly-sync.dwf.ts",
  1769. argNames: ["question"],
  1770. },
  1771. ],
  1772. } as const,
  1773. },
  1774. ])("保留 $toolName display 到 live tool row", ({ toolName, display }) => {
  1775. const turnId = `turn-${toolName}`;
  1776. const toolCallId = `tool-${toolName}`;
  1777. const log = new EventLog();
  1778. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1779. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run tool" }, { turnId });
  1780. log.push(
  1781. SessionEventType.ToolCallScheduled,
  1782. {
  1783. toolCallId,
  1784. toolName,
  1785. input: {},
  1786. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1787. },
  1788. { turnId },
  1789. );
  1790. log.push(
  1791. SessionEventType.ToolCallResult,
  1792. {
  1793. toolCallId,
  1794. result: {
  1795. success: true,
  1796. content: "provider content remains independent",
  1797. display,
  1798. },
  1799. duration: 0,
  1800. },
  1801. { turnId },
  1802. );
  1803. expect(
  1804. runAll(log.events)
  1805. .projection.getSnapshot()
  1806. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  1807. ).toMatchObject({
  1808. status: "success",
  1809. display,
  1810. output: { text: "provider content remains independent" },
  1811. });
  1812. });
  1813. it("不把未声明支持的 display kind 顺带开放到 V4 row", () => {
  1814. const turnId = "turn-file-diff-display";
  1815. const toolCallId = "tool-file-diff-display";
  1816. const log = new EventLog();
  1817. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1818. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "edit file" }, { turnId });
  1819. log.push(
  1820. SessionEventType.ToolCallScheduled,
  1821. {
  1822. toolCallId,
  1823. toolName: "Edit",
  1824. input: {},
  1825. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1826. },
  1827. { turnId },
  1828. );
  1829. log.push(
  1830. SessionEventType.ToolCallResult,
  1831. {
  1832. toolCallId,
  1833. result: {
  1834. success: true,
  1835. content: "updated",
  1836. display: {
  1837. kind: "file_diff",
  1838. filePath: "/workspace/app.ts",
  1839. additions: 1,
  1840. deletions: 0,
  1841. structuredPatch: [],
  1842. truncated: false,
  1843. },
  1844. },
  1845. duration: 0,
  1846. },
  1847. { turnId },
  1848. );
  1849. const row = runAll(log.events)
  1850. .projection.getSnapshot()
  1851. .rows.window.find((candidate) => candidate.kind === "toolCall");
  1852. expect(row).not.toHaveProperty("display");
  1853. });
  1854. it("不把 mirrored RespondToCoordinator 物化到父会话", () => {
  1855. const turnId = "turn-mirrored-response";
  1856. const toolCallId = "tool_subagent_agent-1_response";
  1857. const mirrored = {
  1858. agentId: "agent-1",
  1859. agentType: "general-purpose",
  1860. childSessionId: "session-child-1",
  1861. childToolCallId: "response",
  1862. parentToolCallId: "parent-agent-call",
  1863. source: "subagent",
  1864. };
  1865. const log = new EventLog();
  1866. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1867. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run child" }, { turnId });
  1868. log.push(
  1869. SessionEventType.ToolCallScheduled,
  1870. {
  1871. ...mirrored,
  1872. toolCallId,
  1873. toolName: "RespondToCoordinator",
  1874. input: { summary: "reply", message: "details" },
  1875. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1876. },
  1877. { turnId },
  1878. );
  1879. log.push(
  1880. SessionEventType.ToolCallResult,
  1881. {
  1882. ...mirrored,
  1883. toolCallId,
  1884. result: {
  1885. success: true,
  1886. content: "Response response-1 was queued for the coordinator.",
  1887. display: { kind: "respond_to_coordinator", status: "success" },
  1888. },
  1889. duration: 0,
  1890. },
  1891. { turnId },
  1892. );
  1893. expect(
  1894. runAll(log.events)
  1895. .projection.getSnapshot()
  1896. .rows.window.filter((row) => row.kind === "toolCall"),
  1897. ).toEqual([]);
  1898. });
  1899. it("MCP discovery 展示元数据进入 live tool row,不依赖合成工具名解析", () => {
  1900. const turnId = "turn-mcp-presentation";
  1901. const toolCallId = "tool-mcp-presentation";
  1902. const log = new EventLog();
  1903. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1904. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "查询 issue" }, { turnId });
  1905. log.push(
  1906. SessionEventType.ToolCallScheduled,
  1907. {
  1908. toolCallId,
  1909. toolName: "custom-provider-visible-name",
  1910. input: { query: "is:open" },
  1911. display: {
  1912. kind: "mcp_tool",
  1913. serverName: "company-github-prod",
  1914. toolName: "issue_query_v2",
  1915. description: "Query issues visible to the current user.",
  1916. },
  1917. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1918. },
  1919. { turnId },
  1920. );
  1921. const pendingRow = runAll(log.events.slice(0, 3))
  1922. .projection.getSnapshot()
  1923. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId);
  1924. expect(pendingRow).toMatchObject({
  1925. status: "inputStreaming",
  1926. display: { kind: "mcp_tool", toolName: "issue_query_v2" },
  1927. });
  1928. log.push(
  1929. SessionEventType.ToolCallResult,
  1930. {
  1931. toolCallId,
  1932. result: {
  1933. success: true,
  1934. content: "12 issues",
  1935. display: {
  1936. kind: "mcp_tool",
  1937. serverName: "company-github-prod",
  1938. toolName: "issue_query_v2",
  1939. description: "Query issues visible to the current user.",
  1940. },
  1941. },
  1942. duration: 12,
  1943. },
  1944. { turnId },
  1945. );
  1946. expect(
  1947. runAll(log.events)
  1948. .projection.getSnapshot()
  1949. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  1950. ).toMatchObject({
  1951. toolName: "custom-provider-visible-name",
  1952. status: "success",
  1953. display: {
  1954. kind: "mcp_tool",
  1955. serverName: "company-github-prod",
  1956. toolName: "issue_query_v2",
  1957. },
  1958. });
  1959. });
  1960. it("MCP display 在 running、failed 与 stopped 生命周期更新中保持不变", () => {
  1961. const display = {
  1962. kind: "mcp_tool" as const,
  1963. serverName: "firebase",
  1964. toolName: "get_environment",
  1965. };
  1966. const createLog = () => {
  1967. const log = new EventLog();
  1968. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1969. log.push(
  1970. SessionEventType.TurnStarted,
  1971. { turnNumber: 1, input: "inspect" },
  1972. { turnId: "turn-mcp-lifecycle" },
  1973. );
  1974. log.push(
  1975. SessionEventType.ToolCallScheduled,
  1976. {
  1977. toolCallId: "mcp-lifecycle",
  1978. toolName: "opaque-name",
  1979. input: {},
  1980. display,
  1981. schedule: { parallelGroups: [["mcp-lifecycle"]], executionOrder: ["mcp-lifecycle"] },
  1982. },
  1983. { turnId: "turn-mcp-lifecycle" },
  1984. );
  1985. log.push(
  1986. SessionEventType.ToolCallStarted,
  1987. { toolCallId: "mcp-lifecycle", toolName: "opaque-name", startedAt: new Date() },
  1988. { turnId: "turn-mcp-lifecycle" },
  1989. );
  1990. return log;
  1991. };
  1992. const failedLog = createLog();
  1993. failedLog.push(
  1994. SessionEventType.ToolCallError,
  1995. { toolCallId: "mcp-lifecycle", error: { type: "tool_failed", message: "boom" } },
  1996. { turnId: "turn-mcp-lifecycle" },
  1997. );
  1998. const failedRow = runAll(failedLog.events).projection.getSnapshot().rows.window.at(-1);
  1999. expect(failedRow).toMatchObject({ status: "error", display });
  2000. const stoppedLog = createLog();
  2001. stoppedLog.push(
  2002. SessionEventType.TurnComplete,
  2003. { response: "", tokenCount: 0, toolCallCount: 1, duration: 1, resultType: "cancelled" },
  2004. { turnId: "turn-mcp-lifecycle" },
  2005. );
  2006. const stoppedRow = runAll(stoppedLog.events).projection.getSnapshot().rows.window.at(-1);
  2007. expect(stoppedRow).toMatchObject({ status: "cancelled", display });
  2008. });
  2009. it("工具主动取消错误直接投影为 cancelled,不等待 turn complete 纠正", () => {
  2010. const turnId = "turn-tool-cancelled";
  2011. const log = new EventLog();
  2012. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2013. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run long bash" }, { turnId });
  2014. log.push(
  2015. SessionEventType.ToolCallScheduled,
  2016. {
  2017. toolCallId: "bash-cancelled",
  2018. toolName: "Bash",
  2019. input: { command: "sleep 60" },
  2020. schedule: { parallelGroups: [["bash-cancelled"]], executionOrder: ["bash-cancelled"] },
  2021. },
  2022. { turnId },
  2023. );
  2024. log.push(
  2025. SessionEventType.ToolCallStarted,
  2026. { toolCallId: "bash-cancelled", toolName: "Bash", startedAt: new Date() },
  2027. { turnId },
  2028. );
  2029. log.push(
  2030. SessionEventType.ToolCallError,
  2031. {
  2032. toolCallId: "bash-cancelled",
  2033. error: {
  2034. code: "TOOL_CANCELLED",
  2035. type: "tool_cancelled",
  2036. message: "Bash was cancelled and the child process was asked to stop",
  2037. },
  2038. },
  2039. { turnId },
  2040. );
  2041. const row = runAll(log.events).projection.getSnapshot().rows.window.at(-1);
  2042. expect(row).toMatchObject({ kind: "toolCall", status: "cancelled" });
  2043. });
  2044. it("O/Q:tool 输入流式 → 权限等待 → 放行执行 → 成功终态", () => {
  2045. const turnId = "turn-1";
  2046. const log = new EventLog();
  2047. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2048. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run ls" }, { turnId });
  2049. log.push(
  2050. SessionEventType.ModelStreaming,
  2051. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-1", toolName: "bash" },
  2052. { turnId },
  2053. );
  2054. log.push(
  2055. SessionEventType.ModelStreaming,
  2056. { kind: "tool_input_delta", delta: '{"command":"ls"}', done: false, toolCallId: "tc-1" },
  2057. { turnId },
  2058. );
  2059. log.push(
  2060. SessionEventType.ToolCallScheduled,
  2061. {
  2062. toolCallId: "tc-1",
  2063. toolName: "bash",
  2064. input: { command: "ls" },
  2065. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  2066. },
  2067. { turnId },
  2068. );
  2069. log.push(
  2070. SessionEventType.PermissionRequested,
  2071. {
  2072. requestId: "req-1",
  2073. toolCallId: "tc-1",
  2074. toolName: "bash",
  2075. riskLevel: "medium",
  2076. reason: "Run shell command",
  2077. input: { command: "ls" },
  2078. suggestedPermissionUpdates: [
  2079. {
  2080. behavior: "allow",
  2081. rules: [{ ruleContent: "pnpm run lint:*", toolName: "Bash" }],
  2082. type: "addRules",
  2083. },
  2084. ],
  2085. },
  2086. { turnId },
  2087. );
  2088. const { projection } = runAll(log.events);
  2089. const pending = projection.getSnapshot();
  2090. const toolRow = pending.rows.window.find((row) => row.kind === "toolCall");
  2091. expect(toolRow).toMatchObject({
  2092. status: "pendingApproval",
  2093. inputText: '{"command":"ls"}',
  2094. approvalInteractionId: "req-1",
  2095. });
  2096. expect(pending.pendingInteractions).toHaveLength(1);
  2097. expect(pending.pendingInteractions[0]).toMatchObject({
  2098. kind: "permission",
  2099. anchorRowId: toolRow?.rowId,
  2100. });
  2101. expect(pending.pendingInteractions[0]?.payload).toMatchObject({
  2102. freeText: true,
  2103. options: [
  2104. { optionId: "allowOnce", response: { decision: "allow" } },
  2105. {
  2106. optionId: "allowAlways",
  2107. response: {
  2108. decision: "allow",
  2109. permissionUpdates: [
  2110. {
  2111. behavior: "allow",
  2112. rules: [{ ruleContent: "pnpm run lint:*", toolName: "Bash" }],
  2113. type: "addRules",
  2114. },
  2115. ],
  2116. },
  2117. },
  2118. { optionId: "deny", response: { decision: "deny" } },
  2119. ],
  2120. });
  2121. const resume = new EventLog();
  2122. // EventLog seq 从 1 重新计数不影响断言主体(seq 水位单独断言于 A 组)。
  2123. resume.push(
  2124. SessionEventType.PermissionResolved,
  2125. { requestId: "req-1", toolCallId: "tc-1", decision: "allow" },
  2126. { turnId },
  2127. );
  2128. resume.push(
  2129. SessionEventType.ToolCallStarted,
  2130. { toolCallId: "tc-1", toolName: "bash", startedAt: new Date() },
  2131. { turnId },
  2132. );
  2133. resume.push(
  2134. SessionEventType.ToolCallResult,
  2135. { toolCallId: "tc-1", result: { success: true, content: "file-a\nfile-b" }, duration: 42 },
  2136. { turnId },
  2137. );
  2138. for (const event of resume.events) projection.applyEvent(event);
  2139. const done = projection.getSnapshot();
  2140. expect(done.pendingInteractions).toHaveLength(0);
  2141. const doneRow = done.rows.window.find((row) => row.kind === "toolCall");
  2142. expect(doneRow).toMatchObject({
  2143. status: "success",
  2144. output: { text: "file-a\nfile-b" },
  2145. });
  2146. expect(
  2147. doneRow && "approvalInteractionId" in doneRow && doneRow.approvalInteractionId,
  2148. ).toBeFalsy();
  2149. });
  2150. it.each([
  2151. { label: "空字符串", streamName: "" },
  2152. { label: "纯空白", streamName: " \t " },
  2153. ])("O/ETN:$label 工具名只参与恢复,不物化可见工具行", ({ streamName }) => {
  2154. const turnId = "turn-empty-tool-name";
  2155. const toolCallId = "call-empty-tool-name";
  2156. const log = new EventLog();
  2157. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2158. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "continue" }, { turnId });
  2159. log.push(
  2160. SessionEventType.ModelStreaming,
  2161. {
  2162. kind: "tool_input_start",
  2163. delta: "",
  2164. done: false,
  2165. toolCallId,
  2166. toolName: streamName,
  2167. },
  2168. { turnId },
  2169. );
  2170. log.push(
  2171. SessionEventType.ModelStreaming,
  2172. {
  2173. kind: "tool_input_delta",
  2174. delta: '{"value":1}',
  2175. done: false,
  2176. toolCallId,
  2177. },
  2178. { turnId },
  2179. );
  2180. log.push(
  2181. SessionEventType.ModelStreaming,
  2182. {
  2183. kind: "tool_call",
  2184. delta: "",
  2185. done: true,
  2186. input: { value: 1 },
  2187. toolCallId,
  2188. toolName: streamName,
  2189. },
  2190. { turnId },
  2191. );
  2192. log.push(
  2193. SessionEventType.ToolCallError,
  2194. {
  2195. toolCallId,
  2196. error: {
  2197. type: "fault.runtime.toolFailed",
  2198. message: "Model returned an invalid tool call: tool name is empty.",
  2199. },
  2200. },
  2201. { turnId },
  2202. );
  2203. log.push(
  2204. SessionEventType.ModelStreaming,
  2205. { kind: "text_start", delta: "", done: false },
  2206. { turnId },
  2207. );
  2208. log.push(
  2209. SessionEventType.ModelStreaming,
  2210. { kind: "text_delta", delta: "continued", done: false },
  2211. { turnId },
  2212. );
  2213. log.push(
  2214. SessionEventType.ModelStreaming,
  2215. { kind: "text_end", delta: "", done: false },
  2216. { turnId },
  2217. );
  2218. log.push(
  2219. SessionEventType.TurnComplete,
  2220. {
  2221. response: "continued",
  2222. tokenCount: 1,
  2223. toolCallCount: 1,
  2224. duration: 10,
  2225. resultType: "success",
  2226. },
  2227. { turnId },
  2228. );
  2229. const { deltasPerEvent, projection, snapshots } = runAll(log.events);
  2230. expect(projection.getSnapshot().rows.window.filter((row) => row.kind === "toolCall")).toEqual(
  2231. [],
  2232. );
  2233. expect(
  2234. projection.getSnapshot().rows.window.find((row) => row.kind === "assistantText"),
  2235. ).toMatchObject({ text: "continued", state: "complete" });
  2236. expect(
  2237. deltasPerEvent
  2238. .flat()
  2239. .some(
  2240. (delta) =>
  2241. (delta.op === "row.appended" || delta.op === "row.upserted") &&
  2242. delta.row.kind === "toolCall",
  2243. ),
  2244. ).toBe(false);
  2245. const direct = applyConversationDeltas(snapshots[0]!, deltasPerEvent.flat());
  2246. for (const profile of [DELIVERY_PROFILES.continuous, DELIVERY_PROFILES.replayable]) {
  2247. const delivered = coalesceConversationDeltas(
  2248. filterConversationDeltasForProfile(deltasPerEvent.flat(), profile),
  2249. );
  2250. expect(applyConversationDeltas(snapshots[0]!, delivered)).toEqual(direct);
  2251. }
  2252. });
  2253. it("O/ETN:合法 empty_tool_name 工具保留 live 与 replayable 可见生命周期", () => {
  2254. const turnId = "turn-legitimate-empty-tool-name";
  2255. const toolCallId = "call-legitimate-empty-tool-name";
  2256. const log = new EventLog();
  2257. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2258. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run tool" }, { turnId });
  2259. log.push(
  2260. SessionEventType.ModelStreaming,
  2261. {
  2262. kind: "tool_input_start",
  2263. delta: "",
  2264. done: false,
  2265. toolCallId,
  2266. toolName: "empty_tool_name",
  2267. },
  2268. { turnId },
  2269. );
  2270. log.push(
  2271. SessionEventType.ModelStreaming,
  2272. {
  2273. kind: "tool_input_delta",
  2274. delta: '{"value":1}',
  2275. done: false,
  2276. toolCallId,
  2277. },
  2278. { turnId },
  2279. );
  2280. log.push(
  2281. SessionEventType.ModelStreaming,
  2282. {
  2283. kind: "tool_call",
  2284. delta: "",
  2285. done: true,
  2286. input: { value: 1 },
  2287. toolCallId,
  2288. toolName: "empty_tool_name",
  2289. },
  2290. { turnId },
  2291. );
  2292. log.push(
  2293. SessionEventType.ToolCallScheduled,
  2294. {
  2295. toolCallId,
  2296. toolName: "empty_tool_name",
  2297. input: { value: 1 },
  2298. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  2299. },
  2300. { turnId },
  2301. );
  2302. log.push(
  2303. SessionEventType.ToolCallResult,
  2304. {
  2305. toolCallId,
  2306. result: { success: true, content: "ok" },
  2307. duration: 1,
  2308. },
  2309. { turnId },
  2310. );
  2311. const { deltasPerEvent, projection, snapshots } = runAll(log.events);
  2312. expect(
  2313. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  2314. ).toMatchObject({
  2315. input: { value: 1 },
  2316. status: "success",
  2317. toolCallId,
  2318. toolName: "empty_tool_name",
  2319. });
  2320. const direct = applyConversationDeltas(snapshots[0]!, deltasPerEvent.flat());
  2321. for (const profile of [DELIVERY_PROFILES.continuous, DELIVERY_PROFILES.replayable]) {
  2322. const delivered = coalesceConversationDeltas(
  2323. filterConversationDeltasForProfile(deltasPerEvent.flat(), profile),
  2324. );
  2325. expect(applyConversationDeltas(snapshots[0]!, delivered)).toEqual(direct);
  2326. }
  2327. });
  2328. it("O/ETN:普通非空 unknown tool 仍保留 terminal error 工具行", () => {
  2329. const turnId = "turn-unknown-tool";
  2330. const toolCallId = "call-unknown-tool";
  2331. const log = new EventLog();
  2332. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2333. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "continue" }, { turnId });
  2334. log.push(
  2335. SessionEventType.ToolCallScheduled,
  2336. {
  2337. toolCallId,
  2338. toolName: "DefinitelyMissingTool",
  2339. input: {},
  2340. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  2341. },
  2342. { turnId },
  2343. );
  2344. log.push(
  2345. SessionEventType.ToolCallError,
  2346. {
  2347. toolCallId,
  2348. error: { type: "fault.runtime.toolNotFound", message: "Tool not found" },
  2349. },
  2350. { turnId },
  2351. );
  2352. expect(
  2353. runAll(log.events)
  2354. .projection.getSnapshot()
  2355. .rows.window.find((row) => row.kind === "toolCall"),
  2356. ).toMatchObject({
  2357. toolCallId,
  2358. toolName: "DefinitelyMissingTool",
  2359. status: "error",
  2360. });
  2361. });
  2362. it.each(["Write", "Edit"])(
  2363. "STIP06:%s 首包立即,后续 inputText 按事件时间戳每秒合并一次",
  2364. (toolName) => {
  2365. const turnId = "turn-file-tool";
  2366. const base = 1_700_000_010_000;
  2367. const log = new EventLog();
  2368. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2369. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "modify file" }, { turnId });
  2370. log.push(
  2371. SessionEventType.ModelStreaming,
  2372. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-file", toolName },
  2373. { timestampMs: base, turnId },
  2374. );
  2375. log.push(
  2376. SessionEventType.ModelStreaming,
  2377. {
  2378. kind: "tool_input_delta",
  2379. delta: '{"file_path":"src/app.ts",',
  2380. done: false,
  2381. toolCallId: "tc-file",
  2382. },
  2383. { timestampMs: base + 100, turnId },
  2384. );
  2385. log.push(
  2386. SessionEventType.ModelStreaming,
  2387. { kind: "tool_input_delta", delta: '"content":"a', done: false, toolCallId: "tc-file" },
  2388. { timestampMs: base + 400, turnId },
  2389. );
  2390. log.push(
  2391. SessionEventType.ModelStreaming,
  2392. { kind: "tool_input_delta", delta: 'b"}', done: false, toolCallId: "tc-file" },
  2393. { timestampMs: base + 1_100, turnId },
  2394. );
  2395. const { deltasPerEvent, projection } = runAll(log.events);
  2396. expect(inputTextAppends(deltasPerEvent[3] ?? [])).toEqual(['{"file_path":"src/app.ts",']);
  2397. expect(inputTextAppends(deltasPerEvent[4] ?? [])).toEqual([]);
  2398. expect(inputTextAppends(deltasPerEvent[5] ?? [])).toEqual(['"content":"ab"}']);
  2399. expect(
  2400. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  2401. ).toMatchObject({ inputText: '{"file_path":"src/app.ts","content":"ab"}' });
  2402. const estimateProjection = new ProductProjection("session-1", "epoch-1");
  2403. const appendEstimates = log.events.map((event) => {
  2404. const estimate = estimateProjection.establishedStreamingAppend(event);
  2405. estimateProjection.applyEvent(event);
  2406. return estimate;
  2407. });
  2408. expect(appendEstimates.slice(3)).toEqual([
  2409. '{"file_path":"src/app.ts",',
  2410. "",
  2411. '"content":"ab"}',
  2412. ]);
  2413. },
  2414. );
  2415. it("STIP07:Write input end 立即冲刷窗口内尚未发布的 suffix", () => {
  2416. const turnId = "turn-write-end";
  2417. const base = 1_700_000_020_000;
  2418. const log = new EventLog();
  2419. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2420. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "write" }, { turnId });
  2421. log.push(
  2422. SessionEventType.ModelStreaming,
  2423. {
  2424. kind: "tool_input_start",
  2425. delta: "",
  2426. done: false,
  2427. toolCallId: "tc-write",
  2428. toolName: "Write",
  2429. },
  2430. { timestampMs: base, turnId },
  2431. );
  2432. log.push(
  2433. SessionEventType.ModelStreaming,
  2434. { kind: "tool_input_delta", delta: '{"content":"a', done: false, toolCallId: "tc-write" },
  2435. { timestampMs: base + 100, turnId },
  2436. );
  2437. log.push(
  2438. SessionEventType.ModelStreaming,
  2439. { kind: "tool_input_delta", delta: 'b"}', done: false, toolCallId: "tc-write" },
  2440. { timestampMs: base + 200, turnId },
  2441. );
  2442. log.push(
  2443. SessionEventType.ModelStreaming,
  2444. { kind: "tool_input_end", delta: "", done: true, toolCallId: "tc-write" },
  2445. { timestampMs: base + 300, turnId },
  2446. );
  2447. const { deltasPerEvent, projection } = runAll(log.events);
  2448. expect(inputTextAppends(deltasPerEvent[4] ?? [])).toEqual([]);
  2449. expect(inputTextAppends(deltasPerEvent[5] ?? [])).toEqual(['b"}']);
  2450. expect(
  2451. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  2452. ).toMatchObject({ inputText: '{"content":"ab"}' });
  2453. });
  2454. it("STIP07:Write 被取消时把窗口内 suffix 收进 cancelled row", () => {
  2455. const turnId = "turn-write-cancel";
  2456. const base = 1_700_000_030_000;
  2457. const log = new EventLog();
  2458. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2459. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "write" }, { turnId });
  2460. log.push(
  2461. SessionEventType.ModelStreaming,
  2462. {
  2463. kind: "tool_input_start",
  2464. delta: "",
  2465. done: false,
  2466. toolCallId: "tc-write",
  2467. toolName: "Write",
  2468. },
  2469. { timestampMs: base, turnId },
  2470. );
  2471. log.push(
  2472. SessionEventType.ModelStreaming,
  2473. { kind: "tool_input_delta", delta: '{"content":"a', done: false, toolCallId: "tc-write" },
  2474. { timestampMs: base + 100, turnId },
  2475. );
  2476. log.push(
  2477. SessionEventType.ModelStreaming,
  2478. { kind: "tool_input_delta", delta: 'b"}', done: false, toolCallId: "tc-write" },
  2479. { timestampMs: base + 200, turnId },
  2480. );
  2481. log.push(
  2482. SessionEventType.TurnComplete,
  2483. { response: "", tokenCount: 0, toolCallCount: 0, duration: 300, resultType: "cancelled" },
  2484. { timestampMs: base + 300, turnId },
  2485. );
  2486. const { deltasPerEvent, projection } = runAll(log.events);
  2487. expect(inputTextAppends(deltasPerEvent[4] ?? [])).toEqual([]);
  2488. expect(
  2489. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  2490. ).toMatchObject({ status: "cancelled", inputText: '{"content":"ab"}' });
  2491. });
  2492. it("STIP08:非 Write/Edit 工具保留逐投影增量", () => {
  2493. const turnId = "turn-bash";
  2494. const base = 1_700_000_040_000;
  2495. const log = new EventLog();
  2496. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2497. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId });
  2498. log.push(
  2499. SessionEventType.ModelStreaming,
  2500. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-bash", toolName: "Bash" },
  2501. { timestampMs: base, turnId },
  2502. );
  2503. log.push(
  2504. SessionEventType.ModelStreaming,
  2505. { kind: "tool_input_delta", delta: '{"command":"p', done: false, toolCallId: "tc-bash" },
  2506. { timestampMs: base + 100, turnId },
  2507. );
  2508. log.push(
  2509. SessionEventType.ModelStreaming,
  2510. { kind: "tool_input_delta", delta: 'wd"}', done: false, toolCallId: "tc-bash" },
  2511. { timestampMs: base + 200, turnId },
  2512. );
  2513. const { deltasPerEvent } = runAll(log.events);
  2514. expect(inputTextAppends(deltasPerEvent[3] ?? [])).toEqual(['{"command":"p']);
  2515. expect(inputTextAppends(deltasPerEvent[4] ?? [])).toEqual(['wd"}']);
  2516. });
  2517. it("Q:AskUserQuestion 权限等待态 → structured userInput pendingInteraction", () => {
  2518. const turnId = "turn-ask";
  2519. const log = new EventLog();
  2520. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2521. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "帮我做个番茄钟" }, { turnId });
  2522. log.push(
  2523. SessionEventType.ToolCallScheduled,
  2524. {
  2525. toolCallId: "ask-1",
  2526. toolName: "AskUserQuestion",
  2527. input: {
  2528. questions: [
  2529. {
  2530. question: "你想把这个番茄时钟作为什么形式存在?",
  2531. header: "形式",
  2532. options: [
  2533. { label: "独立新页面", description: "新增页面", preview: "新增页面预览" },
  2534. { label: "独立小工具视图", description: "嵌入现有界面" },
  2535. ],
  2536. },
  2537. ],
  2538. },
  2539. schedule: { parallelGroups: [["ask-1"]], executionOrder: ["ask-1"] },
  2540. },
  2541. { turnId },
  2542. );
  2543. log.push(
  2544. SessionEventType.PermissionRequested,
  2545. {
  2546. requestId: "ask-request-1",
  2547. toolCallId: "ask-1",
  2548. toolName: "AskUserQuestion",
  2549. riskLevel: "low",
  2550. reason: "AskUserQuestion pauses execution to collect answers from the user",
  2551. origin: {
  2552. kind: "subagent",
  2553. agentId: "agent-ask",
  2554. agentType: "general-purpose",
  2555. childSessionId: "sess-child-ask",
  2556. description: "Ask from child",
  2557. parentSessionId: "session-1",
  2558. parentToolCallId: "call-parent-agent",
  2559. parentTurnId: turnId,
  2560. },
  2561. input: {
  2562. questions: [
  2563. {
  2564. question: "你想把这个番茄时钟作为什么形式存在?",
  2565. header: "形式",
  2566. options: [
  2567. { label: "独立新页面", description: "新增页面", preview: "新增页面预览" },
  2568. { label: "独立小工具视图", description: "嵌入现有界面" },
  2569. ],
  2570. },
  2571. ],
  2572. },
  2573. },
  2574. { turnId },
  2575. );
  2576. const { projection } = runAll(log.events);
  2577. const snapshot = projection.getSnapshot();
  2578. const toolRow = snapshot.rows.window.find((row) => row.kind === "toolCall");
  2579. expect(toolRow).toMatchObject({
  2580. status: "pendingApproval",
  2581. approvalInteractionId: "ask-request-1",
  2582. });
  2583. expect(snapshot.pendingInteractions).toHaveLength(1);
  2584. expect(snapshot.pendingInteractions[0]).toMatchObject({
  2585. interactionId: "ask-request-1",
  2586. kind: "userInput",
  2587. anchorRowId: toolRow?.rowId,
  2588. payload: {
  2589. kind: "userInput",
  2590. toolName: "AskUserQuestion",
  2591. toolCallId: "ask-1",
  2592. origin: {
  2593. kind: "subagent",
  2594. agentId: "agent-ask",
  2595. childSessionId: "sess-child-ask",
  2596. parentSessionId: "session-1",
  2597. parentToolCallId: "call-parent-agent",
  2598. },
  2599. prompt: "AskUserQuestion pauses execution to collect answers from the user",
  2600. freeText: true,
  2601. schema: { toolName: "AskUserQuestion" },
  2602. questions: [
  2603. {
  2604. question: "你想把这个番茄时钟作为什么形式存在?",
  2605. header: "形式",
  2606. options: [
  2607. {
  2608. value: "独立新页面",
  2609. label: "独立新页面",
  2610. description: "新增页面",
  2611. preview: "新增页面预览",
  2612. },
  2613. { value: "独立小工具视图", label: "独立小工具视图", description: "嵌入现有界面" },
  2614. ],
  2615. },
  2616. ],
  2617. },
  2618. });
  2619. const autoResolutionLog = new EventLog();
  2620. const hiddenGrace = {
  2621. state: "hiddenGrace" as const,
  2622. startedAt: 1_700_000_000_000,
  2623. visibleAt: 1_700_000_060_000,
  2624. deadlineAt: 1_700_000_300_000,
  2625. };
  2626. projection.applyEvent(
  2627. autoResolutionLog.push(
  2628. SessionEventType.UserInputAutoResolutionUpdated,
  2629. {
  2630. interactionId: "ask-request-1",
  2631. toolCallId: "ask-1",
  2632. autoResolution: hiddenGrace,
  2633. },
  2634. { turnId },
  2635. ),
  2636. );
  2637. expect(projection.getSnapshot().pendingInteractions[0]?.autoResolution).toEqual(hiddenGrace);
  2638. const visibleCountdown = { ...hiddenGrace, state: "visibleCountdown" as const };
  2639. projection.applyEvent(
  2640. autoResolutionLog.push(
  2641. SessionEventType.UserInputAutoResolutionUpdated,
  2642. {
  2643. interactionId: "ask-request-1",
  2644. toolCallId: "ask-1",
  2645. autoResolution: visibleCountdown,
  2646. },
  2647. { turnId },
  2648. ),
  2649. );
  2650. expect(projection.getSnapshot().pendingInteractions[0]?.autoResolution).toEqual(
  2651. visibleCountdown,
  2652. );
  2653. const snoozed = {
  2654. state: "snoozed" as const,
  2655. startedAt: hiddenGrace.startedAt,
  2656. snoozedAt: 1_700_000_299_000,
  2657. };
  2658. projection.applyEvent(
  2659. autoResolutionLog.push(
  2660. SessionEventType.UserInputAutoResolutionUpdated,
  2661. {
  2662. interactionId: "ask-request-1",
  2663. toolCallId: "ask-1",
  2664. autoResolution: snoozed,
  2665. },
  2666. { turnId },
  2667. ),
  2668. );
  2669. expect(projection.getSnapshot().pendingInteractions[0]?.autoResolution).toEqual(snoozed);
  2670. const resume = new EventLog();
  2671. projection.applyEvent(
  2672. resume.push(
  2673. SessionEventType.PermissionResolved,
  2674. { requestId: "ask-request-1", toolCallId: "ask-1", decision: "allow" },
  2675. { turnId },
  2676. ),
  2677. );
  2678. expect(projection.getSnapshot().pendingInteractions).toHaveLength(0);
  2679. });
  2680. it("Q:ExitPlanMode 权限等待态 → plan approval elicitation pendingInteraction", () => {
  2681. const turnId = "turn-plan";
  2682. const log = new EventLog();
  2683. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2684. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "进入计划模式" }, { turnId });
  2685. log.push(
  2686. SessionEventType.ToolCallScheduled,
  2687. {
  2688. toolCallId: "exit-plan-1",
  2689. toolName: "ExitPlanMode",
  2690. input: { plan: "1. 增加协议\n2. 补 UI" },
  2691. schedule: { parallelGroups: [["exit-plan-1"]], executionOrder: ["exit-plan-1"] },
  2692. },
  2693. { turnId },
  2694. );
  2695. log.push(
  2696. SessionEventType.PermissionRequested,
  2697. {
  2698. requestId: "plan-request-1",
  2699. toolCallId: "exit-plan-1",
  2700. toolName: "ExitPlanMode",
  2701. riskLevel: "low",
  2702. reason: "ExitPlanMode requires user approval before implementation",
  2703. input: { plan: "1. 增加协议\n2. 补 UI" },
  2704. },
  2705. { turnId },
  2706. );
  2707. const { projection } = runAll(log.events);
  2708. expect(projection.getSnapshot().pendingInteractions[0]).toMatchObject({
  2709. kind: "userInput",
  2710. payload: {
  2711. kind: "userInput",
  2712. toolName: "ExitPlanMode",
  2713. toolCallId: "exit-plan-1",
  2714. schema: { interaction: "plan_approval", toolName: "ExitPlanMode" },
  2715. questions: [
  2716. {
  2717. header: "Plan",
  2718. question: "ExitPlanMode requires user approval before implementation",
  2719. options: [
  2720. {
  2721. value: "approve",
  2722. label: "Approve",
  2723. description: "Exit plan mode and start implementation.",
  2724. },
  2725. ],
  2726. },
  2727. ],
  2728. },
  2729. });
  2730. });
  2731. it("Q:权限拒绝 → toolCall cancelled,交互清除", () => {
  2732. const turnId = "turn-1";
  2733. const log = new EventLog();
  2734. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2735. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "rm -rf" }, { turnId });
  2736. log.push(
  2737. SessionEventType.ToolCallScheduled,
  2738. {
  2739. toolCallId: "tc-1",
  2740. toolName: "bash",
  2741. input: { command: "rm -rf /" },
  2742. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  2743. },
  2744. { turnId },
  2745. );
  2746. log.push(
  2747. SessionEventType.PermissionRequested,
  2748. {
  2749. requestId: "req-1",
  2750. toolCallId: "tc-1",
  2751. toolName: "bash",
  2752. riskLevel: "high",
  2753. reason: "Destructive",
  2754. input: {},
  2755. },
  2756. { turnId },
  2757. );
  2758. log.push(
  2759. SessionEventType.PermissionResolved,
  2760. { requestId: "req-1", toolCallId: "tc-1", decision: "deny" },
  2761. { turnId },
  2762. );
  2763. const { projection } = runAll(log.events);
  2764. const snapshot = projection.getSnapshot();
  2765. expect(snapshot.pendingInteractions).toHaveLength(0);
  2766. expect(snapshot.rows.window.find((row) => row.kind === "toolCall")).toMatchObject({
  2767. status: "cancelled",
  2768. });
  2769. });
  2770. it("O:SubagentSpawned/Stopped → subagent row success 并保留 child session 下钻信息", () => {
  2771. const turnId = "turn-1";
  2772. const log = new EventLog();
  2773. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2774. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "派子代理" }, { turnId });
  2775. log.push(
  2776. SessionEventType.SubagentSpawned,
  2777. {
  2778. agentId: "agent-1",
  2779. agentType: "Explore",
  2780. childSessionId: "sess_child_1",
  2781. description: "探索项目结构",
  2782. parentToolCallId: "call-agent-1",
  2783. prompt: "请探索项目",
  2784. status: "running",
  2785. },
  2786. { turnId },
  2787. );
  2788. log.push(
  2789. SessionEventType.SubagentStopped,
  2790. {
  2791. agentId: "agent-1",
  2792. agentType: "Explore",
  2793. childSessionId: "sess_child_1",
  2794. status: "completed",
  2795. summaryText: "项目结构已经梳理完成",
  2796. },
  2797. { turnId },
  2798. );
  2799. const { projection } = runAll(log.events);
  2800. expect(
  2801. projection.getSnapshot().rows.window.find((row) => row.kind === "subagent"),
  2802. ).toMatchObject({
  2803. childSessionId: "sess_child_1",
  2804. parentToolCallId: "call-agent-1",
  2805. status: "success",
  2806. subagentType: "Explore",
  2807. summaryText: "项目结构已经梳理完成",
  2808. });
  2809. expect(projection.getSnapshot().subagents).toMatchObject({
  2810. childSessionIds: ["sess_child_1"],
  2811. running: [],
  2812. endedTotal: 1,
  2813. });
  2814. });
  2815. it("SAT12:SendMessage resumed spawn 在同一次投影中恢复原 row 和 cancellable work", () => {
  2816. const turnId = "turn-send-message-resume";
  2817. const log = new EventLog();
  2818. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2819. log.push(
  2820. SessionEventType.TurnStarted,
  2821. { turnNumber: 1, input: "先运行前台 Agent" },
  2822. { turnId },
  2823. );
  2824. log.push(
  2825. SessionEventType.SubagentSpawned,
  2826. {
  2827. agentId: "agent-resume",
  2828. agentType: "general-purpose",
  2829. childSessionId: "sess-child-resume",
  2830. description: "前台任务",
  2831. parentToolCallId: "call-agent",
  2832. status: "running",
  2833. },
  2834. { turnId },
  2835. );
  2836. log.push(
  2837. SessionEventType.SubagentStopped,
  2838. {
  2839. agentId: "agent-resume",
  2840. agentType: "general-purpose",
  2841. childSessionId: "sess-child-resume",
  2842. parentToolCallId: "call-agent",
  2843. status: "completed",
  2844. },
  2845. { turnId },
  2846. );
  2847. const projection = new ProductProjection("session-1", "epoch-1");
  2848. for (const item of log.events) projection.applyEvent(item);
  2849. const resumedEvent = log.push(
  2850. SessionEventType.SubagentSpawned,
  2851. {
  2852. agentId: "agent-resume",
  2853. agentType: "general-purpose",
  2854. background: true,
  2855. childSessionId: "sess-child-resume",
  2856. description: "恢复到后台",
  2857. parentToolCallId: "call-send-message",
  2858. resumed: true,
  2859. status: "running",
  2860. },
  2861. { turnId },
  2862. );
  2863. const deltas = projection.applyEvent(resumedEvent);
  2864. const snapshot = projection.getSnapshot();
  2865. expect(
  2866. snapshot.rows.window.filter(
  2867. (row) => row.kind === "subagent" && row.entityId === "agent-resume",
  2868. ),
  2869. ).toHaveLength(1);
  2870. expect(snapshot.rows.window.find((row) => row.kind === "subagent")).toMatchObject({
  2871. childSessionId: "sess-child-resume",
  2872. parentToolCallId: "call-agent",
  2873. status: "running",
  2874. });
  2875. expect(snapshot.backgroundWorks).toEqual([
  2876. expect.objectContaining({
  2877. workId: "agent-resume",
  2878. kind: "subagent",
  2879. childSessionId: "sess-child-resume",
  2880. cancellable: true,
  2881. status: "running",
  2882. title: "恢复到后台",
  2883. }),
  2884. ]);
  2885. expect(snapshot.subagents).toMatchObject({
  2886. childSessionIds: ["sess-child-resume"],
  2887. running: [expect.objectContaining({ childSessionId: "sess-child-resume" })],
  2888. endedTotal: 0,
  2889. });
  2890. expect(
  2891. deltas.some(
  2892. (delta) => delta.op === "state.updated" && delta.patch.backgroundWorks?.length === 1,
  2893. ),
  2894. ).toBe(true);
  2895. expect(
  2896. deltas.some(
  2897. (delta) => delta.op === "state.updated" && delta.patch.subagents?.running.length === 1,
  2898. ),
  2899. ).toBe(true);
  2900. projection.applyEvent(
  2901. log.push(
  2902. SessionEventType.BackgroundTaskCompleted,
  2903. {
  2904. taskId: "agent-resume",
  2905. toolName: "Agent",
  2906. taskKind: "subagent",
  2907. childSessionId: "sess-child-resume",
  2908. status: "cancelled",
  2909. cancellable: false,
  2910. },
  2911. { turnId },
  2912. ),
  2913. );
  2914. projection.applyEvent(
  2915. log.push(
  2916. SessionEventType.SubagentStopped,
  2917. {
  2918. agentId: "agent-resume",
  2919. agentType: "general-purpose",
  2920. background: true,
  2921. childSessionId: "sess-child-resume",
  2922. parentToolCallId: "call-send-message",
  2923. status: "cancelled",
  2924. },
  2925. { turnId },
  2926. ),
  2927. );
  2928. const terminalSnapshot = projection.getSnapshot();
  2929. expect(terminalSnapshot.rows.window.find((row) => row.kind === "subagent")).toMatchObject({
  2930. parentToolCallId: "call-agent",
  2931. status: "cancelled",
  2932. });
  2933. expect(terminalSnapshot.backgroundWorks).toEqual([
  2934. expect.objectContaining({ workId: "agent-resume", status: "cancelled" }),
  2935. ]);
  2936. });
  2937. it("SAT24:7 个毫秒级并行 spawn 在每次 row 提交中原子发布完整 running 投影", () => {
  2938. const turnId = "turn-parallel-subagents";
  2939. const log = new EventLog();
  2940. log.push(SessionEventType.SessionCreated, {
  2941. mode: "default",
  2942. contextWindow: 1000,
  2943. });
  2944. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "并行派生" }, { turnId });
  2945. for (let index = 1; index <= 7; index += 1) {
  2946. log.push(
  2947. SessionEventType.SubagentSpawned,
  2948. {
  2949. agentId: `agent-${index}`,
  2950. agentType: "Explore",
  2951. childSessionId: `sess_child_${index}`,
  2952. description: `并行子智能体 ${index}`,
  2953. parentToolCallId: `call-agent-${index}`,
  2954. status: "running",
  2955. },
  2956. { turnId, timestampMs: 1_700_000_000_000 + index },
  2957. );
  2958. }
  2959. const projection = new ProductProjection("session-1", "epoch-1");
  2960. for (const event of log.events) {
  2961. const deltas = projection.applyEvent(event);
  2962. if (event.type !== SessionEventType.SubagentSpawned) continue;
  2963. const expectedCount = Number((event.payload as { agentId: string }).agentId.split("-")[1]);
  2964. const subagentPatch = deltas.find(
  2965. (delta) => delta.op === "state.updated" && delta.patch.subagents,
  2966. );
  2967. expect(deltas.some((delta) => delta.op === "row.appended")).toBe(true);
  2968. expect(subagentPatch).toMatchObject({
  2969. op: "state.updated",
  2970. patch: {
  2971. subagents: {
  2972. childSessionIds: expect.arrayContaining([`sess_child_${expectedCount}`]),
  2973. endedTotal: 0,
  2974. },
  2975. },
  2976. });
  2977. expect(projection.getSnapshot().subagents?.running).toHaveLength(expectedCount);
  2978. }
  2979. expect(projection.getSnapshot().subagents).toMatchObject({
  2980. childSessionIds: Array.from({ length: 7 }, (_, index) => `sess_child_${index + 1}`),
  2981. endedTotal: 0,
  2982. });
  2983. });
  2984. it("SAT22:cold seed 持续排除未持久化 ghost,直到新的合法 spawn", () => {
  2985. const turnId = "turn-cold-subagent-seed";
  2986. const log = new EventLog();
  2987. log.push(SessionEventType.SessionCreated, {
  2988. mode: "default",
  2989. contextWindow: 1000,
  2990. });
  2991. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "历史派生" }, { turnId });
  2992. log.push(
  2993. SessionEventType.SubagentSpawned,
  2994. {
  2995. agentId: "agent-reliable",
  2996. agentType: "Explore",
  2997. childSessionId: "sess-reliable",
  2998. description: "可靠 child",
  2999. status: "running",
  3000. },
  3001. { turnId },
  3002. );
  3003. log.push(
  3004. SessionEventType.SubagentSpawned,
  3005. {
  3006. agentId: "agent-ghost",
  3007. agentType: "Explore",
  3008. childSessionId: "sess-ghost",
  3009. description: "旧版本 ghost",
  3010. status: "running",
  3011. },
  3012. { turnId },
  3013. );
  3014. const projection = new ProductProjection("session-1", "epoch-1");
  3015. for (const event of log.events) projection.applyEvent(event);
  3016. projection.seedSubagents({
  3017. revision: 10,
  3018. childSessionIds: ["sess-reliable"],
  3019. running: [
  3020. {
  3021. agentId: "agent-reliable",
  3022. childSessionId: "sess-reliable",
  3023. status: "running",
  3024. subagentType: "Explore",
  3025. title: "可靠 child",
  3026. },
  3027. ],
  3028. });
  3029. expect(projection.getSnapshot().subagents).toMatchObject({
  3030. revision: 10,
  3031. childSessionIds: ["sess-reliable"],
  3032. running: [{ childSessionId: "sess-reliable" }],
  3033. endedTotal: 0,
  3034. });
  3035. projection.applyEvent(
  3036. log.push(SessionEventType.ModelSelected, {
  3037. modelSelection: {
  3038. providerId: "test-provider",
  3039. modelId: "test-model",
  3040. },
  3041. }),
  3042. );
  3043. expect(projection.getSnapshot().subagents?.childSessionIds).toEqual(["sess-reliable"]);
  3044. projection.applyEvent(
  3045. log.push(
  3046. SessionEventType.SubagentSpawned,
  3047. {
  3048. agentId: "agent-ghost",
  3049. agentType: "Explore",
  3050. childSessionId: "sess-ghost",
  3051. description: "已持久化后恢复",
  3052. resumed: true,
  3053. status: "running",
  3054. },
  3055. { turnId },
  3056. ),
  3057. );
  3058. expect(projection.getSnapshot().subagents?.childSessionIds).toEqual([
  3059. "sess-reliable",
  3060. "sess-ghost",
  3061. ]);
  3062. expect(projection.getSnapshot().subagents?.running).toHaveLength(2);
  3063. });
  3064. it("SAT22:非空 cold manifest 即使旧查询 revision 为 0 也会建立有效版本", () => {
  3065. const projection = new ProductProjection("session-1", "epoch-1");
  3066. projection.seedSubagents({
  3067. revision: 0,
  3068. childSessionIds: ["sess-reliable"],
  3069. running: [],
  3070. });
  3071. expect(projection.getSnapshot().subagents).toMatchObject({
  3072. revision: 1,
  3073. childSessionIds: ["sess-reliable"],
  3074. endedTotal: 1,
  3075. });
  3076. });
  3077. // ── M 组:turn steer 队列 ──
  3078. it("M:steer 入队/注入 —— queue.items 生命周期", () => {
  3079. const turnId = "turn-1";
  3080. const log = new EventLog();
  3081. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3082. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  3083. log.push(
  3084. SessionEventType.TurnSteerQueued,
  3085. {
  3086. pendingInputId: "pi-1",
  3087. inputId: "command-original",
  3088. input: "顺便加个测试",
  3089. inputPreview: "顺便加个测试",
  3090. inputSize: 6,
  3091. targetTurnId: turnId,
  3092. queueLength: 1,
  3093. delivery: "guide",
  3094. intent: {
  3095. sourceCommandId: "command-original",
  3096. queueItemId: "pi-1",
  3097. clientId: "mobile-client",
  3098. kind: "sendText",
  3099. admissionSeq: 12,
  3100. admittedAt: 1234,
  3101. requestedDelivery: "guide",
  3102. admittedDelivery: "guide",
  3103. highspeed: {
  3104. schemaVersion: 1,
  3105. cardId: "hsc-queue",
  3106. taskId: "session-1",
  3107. provider: "builtin:bigmodel-coding-plan",
  3108. model: "GLM-5.3",
  3109. issuedAt: 1_700_000_000_000,
  3110. expiresAt: 1_700_000_900_000,
  3111. },
  3112. attachmentRefs: [
  3113. { ref: "artifact://one", fileName: "one.txt", mime: "text/plain", bytes: 3 },
  3114. ],
  3115. },
  3116. },
  3117. { turnId },
  3118. );
  3119. const { projection } = runAll(log.events);
  3120. expect(projection.getSnapshot().queue.items).toHaveLength(1);
  3121. expect(projection.getSnapshot().queue.items[0]).toMatchObject({
  3122. queueItemId: "pi-1",
  3123. kind: "sendText",
  3124. text: "顺便加个测试",
  3125. sourceCommandId: "command-original",
  3126. clientId: "mobile-client",
  3127. attachments: [{ ref: "artifact://one", fileName: "one.txt", mime: "text/plain", bytes: 3 }],
  3128. delivery: { requested: "guide", admitted: "guide" },
  3129. order: { admissionSeq: 12, queuePosition: 0 },
  3130. steer: { state: "steering" },
  3131. dispatch: { state: "queued" },
  3132. highspeed: { cardId: "hsc-queue", expiresAt: 1_700_000_900_000 },
  3133. admittedAt: 1234,
  3134. });
  3135. const drain = new EventLog();
  3136. drain.push(
  3137. SessionEventType.TurnSteerDrained,
  3138. {
  3139. pendingInputIds: ["pi-1"],
  3140. targetTurnId: turnId,
  3141. injectedMessageIds: ["message-drained"],
  3142. drainedInputs: [
  3143. {
  3144. pendingInputId: "pi-1",
  3145. messageId: "message-drained",
  3146. text: "顺便加个测试",
  3147. delivery: "guide",
  3148. intent: {
  3149. sourceCommandId: "command-original",
  3150. queueItemId: "pi-1",
  3151. clientId: "mobile-client",
  3152. kind: "sendText",
  3153. admissionSeq: 12,
  3154. admittedAt: 1234,
  3155. requestedDelivery: "guide",
  3156. admittedDelivery: "guide",
  3157. attachmentRefs: [
  3158. {
  3159. ref: "artifact://one",
  3160. fileName: "one.txt",
  3161. mime: "text/plain",
  3162. bytes: 3,
  3163. },
  3164. ],
  3165. },
  3166. },
  3167. ],
  3168. },
  3169. { turnId },
  3170. );
  3171. for (const event of drain.events) projection.applyEvent(event);
  3172. expect(projection.getSnapshot().queue.items).toHaveLength(0);
  3173. expect(projection.getSnapshot().rows.window.at(-1)).toMatchObject({
  3174. kind: "userInput",
  3175. text: "顺便加个测试",
  3176. guided: true,
  3177. sourceCommandId: "command-original",
  3178. clientId: "mobile-client",
  3179. attachments: [{ ref: "artifact://one", fileName: "one.txt", mime: "text/plain", bytes: 3 }],
  3180. });
  3181. });
  3182. it("M:goal command 入队 —— queue item 保留 sendGoalCommand kind", () => {
  3183. const turnId = "turn-1";
  3184. const log = new EventLog();
  3185. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3186. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  3187. log.push(
  3188. SessionEventType.TurnSteerQueued,
  3189. {
  3190. pendingInputId: "pi-goal",
  3191. commandKind: "sendGoalCommand",
  3192. input: "/goal 新目标",
  3193. inputPreview: "/goal 新目标",
  3194. inputSize: 12,
  3195. targetTurnId: turnId,
  3196. queueLength: 1,
  3197. },
  3198. { turnId },
  3199. );
  3200. const { projection } = runAll(log.events);
  3201. expect(projection.getSnapshot().queue.items[0]).toMatchObject({
  3202. queueItemId: "pi-goal",
  3203. kind: "sendGoalCommand",
  3204. text: "/goal 新目标",
  3205. });
  3206. });
  3207. it("M:guide/附件 fallback 保留 requested/admitted 与 reasonCode", () => {
  3208. const log = new EventLog();
  3209. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3210. log.push(
  3211. SessionEventType.TurnSteerQueued,
  3212. {
  3213. pendingInputId: "queue-fallback",
  3214. inputId: "command-fallback",
  3215. input: "带附件",
  3216. inputPreview: "带附件",
  3217. inputSize: 9,
  3218. delivery: "queue",
  3219. targetTurnId: "turn-1",
  3220. queueLength: 1,
  3221. intent: {
  3222. sourceCommandId: "command-fallback",
  3223. queueItemId: "queue-fallback",
  3224. clientId: "desktop-client",
  3225. kind: "sendText",
  3226. admissionSeq: 2,
  3227. admittedAt: 50,
  3228. requestedDelivery: "guide",
  3229. admittedDelivery: "queue",
  3230. fallbackReasonCode: "guide.attachmentsUnsupported",
  3231. attachmentRefs: [
  3232. { ref: "artifact://a", fileName: "a.txt", mime: "text/plain", bytes: 1 },
  3233. ],
  3234. },
  3235. },
  3236. { turnId: "turn-1" },
  3237. );
  3238. const { projection } = runAll(log.events);
  3239. expect(projection.getSnapshot().queue.items[0]).toMatchObject({
  3240. sourceCommandId: "command-fallback",
  3241. attachments: [{ ref: "artifact://a" }],
  3242. delivery: {
  3243. requested: "guide",
  3244. admitted: "queue",
  3245. fallbackReasonCode: "guide.attachmentsUnsupported",
  3246. },
  3247. steer: { state: "fellBack", reasonCode: "guide.attachmentsUnsupported" },
  3248. });
  3249. });
  3250. it("M:text-only terminal 以 delivery changed 原地把 guide 改投 queue", () => {
  3251. const log = new EventLog();
  3252. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3253. log.push(
  3254. SessionEventType.TurnSteerQueued,
  3255. {
  3256. pendingInputId: "queue-guide-terminal",
  3257. input: "等下一个工具边界",
  3258. inputPreview: "等下一个工具边界",
  3259. inputSize: 9,
  3260. delivery: "guide",
  3261. targetTurnId: "turn-1",
  3262. queueLength: 1,
  3263. intent: {
  3264. sourceCommandId: "command-guide-terminal",
  3265. queueItemId: "queue-guide-terminal",
  3266. clientId: "desktop-client",
  3267. kind: "sendText",
  3268. admissionSeq: 3,
  3269. admittedAt: 60,
  3270. requestedDelivery: "guide",
  3271. admittedDelivery: "guide",
  3272. },
  3273. },
  3274. { turnId: "turn-1" },
  3275. );
  3276. log.push(
  3277. SessionEventType.TurnSteerDeliveryChanged,
  3278. {
  3279. pendingInputId: "queue-guide-terminal",
  3280. targetTurnId: "turn-1",
  3281. requestedDelivery: "guide",
  3282. admittedDelivery: "queue",
  3283. fallbackReasonCode: "guide.noToolBoundary",
  3284. },
  3285. { turnId: "turn-1" },
  3286. );
  3287. const { projection } = runAll(log.events);
  3288. expect(projection.getSnapshot().queue.items).toEqual([
  3289. expect.objectContaining({
  3290. queueItemId: "queue-guide-terminal",
  3291. text: "等下一个工具边界",
  3292. delivery: {
  3293. requested: "guide",
  3294. admitted: "queue",
  3295. fallbackReasonCode: "guide.noToolBoundary",
  3296. },
  3297. steer: { state: "fellBack", reasonCode: "guide.noToolBoundary" },
  3298. }),
  3299. ]);
  3300. });
  3301. // ── 错误态 ──
  3302. it("错误:turn_error → phase=error + lastError + turnHeader failed", () => {
  3303. const turnId = "turn-1";
  3304. const log = new EventLog();
  3305. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3306. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  3307. log.push(
  3308. SessionEventType.TurnError,
  3309. { error: { type: "ProviderError", message: "rate limited" }, turnPhase: "model" },
  3310. { turnId },
  3311. );
  3312. const { projection } = runAll(log.events);
  3313. const snapshot = projection.getSnapshot();
  3314. expect(snapshot.control.phase).toBe("error");
  3315. expect(snapshot.control.lastError).toMatchObject({
  3316. code: "ProviderError",
  3317. message: "rate limited",
  3318. recoverable: true,
  3319. source: "runtime",
  3320. });
  3321. expect(snapshot.rows.window.find((row) => row.kind === "turnHeader")).toMatchObject({
  3322. state: "failed",
  3323. });
  3324. });
  3325. it("错误:TurnError 保留底层错误详情到 V4 lastError", () => {
  3326. const log = new EventLog();
  3327. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3328. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  3329. log.push(
  3330. SessionEventType.TurnError,
  3331. {
  3332. error: {
  3333. type: "ModelError",
  3334. message: "Model request failed",
  3335. underlyingErrorMessage: "Runtime headers request failed",
  3336. underlyingErrorDetail: "Runtime headers helper timed out after 10000ms.",
  3337. },
  3338. turnPhase: "model",
  3339. },
  3340. { turnId: "turn-1" },
  3341. );
  3342. expect(runAll(log.events).projection.getSnapshot().control.lastError).toMatchObject({
  3343. underlyingErrorMessage: "Runtime headers request failed",
  3344. underlyingErrorDetail: "Runtime headers helper timed out after 10000ms.",
  3345. });
  3346. });
  3347. it.each([
  3348. ["card-highspeed-1", "card-highspeed-1"],
  3349. [null, null],
  3350. ] as const)("错误:TurnError 的 Highspeed 卡归因 %s 透传到 V4 lastError", (value, expected) => {
  3351. const log = new EventLog();
  3352. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3353. log.push(
  3354. SessionEventType.TurnError,
  3355. {
  3356. error: {
  3357. type: "ModelError",
  3358. message: "Model creation failed",
  3359. code: "provider_not_found",
  3360. attribution: { source: "provider", highspeedCardId: value },
  3361. },
  3362. turnPhase: "model_creation",
  3363. },
  3364. { turnId: "turn-1" },
  3365. );
  3366. expect(runAll(log.events).projection.getSnapshot().control.lastError).toMatchObject({
  3367. code: "provider_not_found",
  3368. attribution: { source: "provider", highspeedCardId: expected },
  3369. });
  3370. });
  3371. it("错误:请求期 Highspeed 无处可退的归因原样透传到 V4 lastError", () => {
  3372. // 3402 是 provider 错误码而非目录错误;Renderer 退卡只能依赖 Core 发布的结构化事实。
  3373. const log = new EventLog();
  3374. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3375. log.push(
  3376. SessionEventType.TurnError,
  3377. {
  3378. error: {
  3379. type: "ModelError",
  3380. message: "highspeed card is invalid",
  3381. code: "3402",
  3382. attribution: {
  3383. source: "provider",
  3384. providerId: "account:bigmodel-highspeed-card",
  3385. providerErrorCode: "3402",
  3386. statusCode: 400,
  3387. highspeedCardId: "card-highspeed-request",
  3388. highspeedFallbackUnavailable: true,
  3389. },
  3390. },
  3391. turnPhase: "model",
  3392. },
  3393. { turnId: "turn-1" },
  3394. );
  3395. expect(runAll(log.events).projection.getSnapshot().control.lastError).toMatchObject({
  3396. code: "3402",
  3397. source: "provider",
  3398. attribution: {
  3399. providerErrorCode: "3402",
  3400. highspeedCardId: "card-highspeed-request",
  3401. highspeedFallbackUnavailable: true,
  3402. },
  3403. });
  3404. });
  3405. it("错误:TurnError 保留 future queue 并暂停自动消费", () => {
  3406. const turnId = "turn-error-queue";
  3407. const log = new EventLog();
  3408. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3409. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "首轮失败" }, { turnId });
  3410. log.push(
  3411. SessionEventType.TurnSteerQueued,
  3412. {
  3413. pendingInputId: "queue-after-error",
  3414. inputId: "input-after-error",
  3415. input: "错误后仍要发送",
  3416. inputPreview: "错误后仍要发送",
  3417. inputSize: 24,
  3418. targetTurnId: turnId,
  3419. queueLength: 1,
  3420. delivery: "queue",
  3421. },
  3422. { turnId },
  3423. );
  3424. log.push(
  3425. SessionEventType.TurnError,
  3426. { error: { type: "ProviderError", message: "provider 失败" }, turnPhase: "model" },
  3427. { turnId },
  3428. );
  3429. const { projection } = runAll(log.events);
  3430. const snapshot = projection.getSnapshot();
  3431. expect(snapshot.control.phase).toBe("error");
  3432. expect(snapshot.queue).toMatchObject({
  3433. autoDrain: false,
  3434. pauseReason: "error",
  3435. items: [expect.objectContaining({ queueItemId: "queue-after-error" })],
  3436. });
  3437. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  3438. });
  3439. it.each([true, false])("错误:TurnError retryable=%s 原样映射 recoverable", (retryable) => {
  3440. const turnId = "turn-retryable";
  3441. const log = new EventLog();
  3442. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3443. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  3444. log.push(
  3445. SessionEventType.TurnError,
  3446. {
  3447. error: { type: "ProviderError", message: "failed", retryable },
  3448. turnPhase: "model",
  3449. },
  3450. { turnId },
  3451. );
  3452. const { projection } = runAll(log.events);
  3453. expect(projection.getSnapshot().control.lastError?.recoverable).toBe(retryable);
  3454. });
  3455. it("错误:TurnError 结构化归因进入 lastError,但不改写既有 recoverable", () => {
  3456. const turnId = "turn-attribution";
  3457. const log = new EventLog();
  3458. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3459. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  3460. log.push(
  3461. SessionEventType.TurnError,
  3462. {
  3463. error: {
  3464. type: "model_request_failed",
  3465. message: "Provider stream failed",
  3466. attribution: {
  3467. source: "network",
  3468. reason: "network_error",
  3469. providerId: "default-deepseek",
  3470. modelId: "deepseek-v4-flash",
  3471. providerKind: "anthropic",
  3472. transport: "sse",
  3473. statusCode: 503,
  3474. retryable: false,
  3475. },
  3476. },
  3477. turnPhase: "model",
  3478. },
  3479. { turnId },
  3480. );
  3481. const { projection } = runAll(log.events);
  3482. const snapshot = projection.getSnapshot();
  3483. expect(snapshot.control.lastError).toMatchObject({
  3484. source: "network",
  3485. recoverable: true,
  3486. attribution: {
  3487. source: "network",
  3488. reason: "network_error",
  3489. providerId: "default-deepseek",
  3490. modelId: "deepseek-v4-flash",
  3491. providerKind: "anthropic",
  3492. transport: "sse",
  3493. statusCode: 503,
  3494. retryable: false,
  3495. },
  3496. });
  3497. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  3498. });
  3499. it("错误后新 turn 清除 lastError(与旧 reducer 同一裁决)", () => {
  3500. const log = new EventLog();
  3501. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3502. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  3503. log.push(
  3504. SessionEventType.TurnError,
  3505. { error: { type: "X", message: "boom" }, turnPhase: "model" },
  3506. { turnId: "turn-1" },
  3507. );
  3508. log.push(SessionEventType.TurnStarted, { turnNumber: 2, input: "retry" }, { turnId: "turn-2" });
  3509. const { projection } = runAll(log.events);
  3510. expect(projection.getSnapshot().control.lastError).toBeNull();
  3511. expect(projection.getSnapshot().control.phase).toBe("running");
  3512. });
  3513. it("K10:retry 目标只允许全时间线最后一条 assistantText row", () => {
  3514. const log = new EventLog();
  3515. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3516. for (const turnNumber of [1, 2]) {
  3517. const turnId = `turn-${turnNumber}`;
  3518. log.push(
  3519. SessionEventType.TurnStarted,
  3520. { turnNumber, input: `Q${turnNumber}`, messageId: `user-${turnNumber}` },
  3521. { turnId },
  3522. );
  3523. log.push(
  3524. SessionEventType.ModelStreaming,
  3525. {
  3526. kind: "text_start",
  3527. delta: "",
  3528. done: false,
  3529. assistantMessageId: `assistant-${turnNumber}`,
  3530. },
  3531. { turnId },
  3532. );
  3533. log.push(
  3534. SessionEventType.ModelStreaming,
  3535. { kind: "text_delta", delta: `A${turnNumber}`, done: false },
  3536. { turnId },
  3537. );
  3538. log.push(
  3539. SessionEventType.ModelStreaming,
  3540. { kind: "text_end", delta: "", done: false },
  3541. { turnId },
  3542. );
  3543. log.push(
  3544. SessionEventType.TurnComplete,
  3545. {
  3546. response: `A${turnNumber}`,
  3547. tokenCount: 1,
  3548. toolCallCount: 0,
  3549. duration: 100,
  3550. resultType: "success",
  3551. },
  3552. { turnId },
  3553. );
  3554. }
  3555. const { projection } = runAll(log.events);
  3556. const assistantRows = projection
  3557. .getSnapshot()
  3558. .rows.window.filter((row) => row.kind === "assistantText");
  3559. expect(assistantRows).toHaveLength(2);
  3560. expect(projection.isLatestRetryAssistantRow(assistantRows[0]!.rowId)).toBe(false);
  3561. expect(projection.isLatestRetryAssistantRow(assistantRows[1]!.rowId)).toBe(true);
  3562. expect(assistantRows[0]!.actions?.canRetry).not.toBe(true);
  3563. expect(assistantRows[1]!.actions?.canRetry).toBe(true);
  3564. expect(projection.getMessageIdForRow(assistantRows[1]!.rowId)).toBe("assistant-2");
  3565. });
  3566. it("BG33/K11:background 结果轮无普通 retry,且不会恢复更早真实用户轮", () => {
  3567. const log = new EventLog();
  3568. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3569. const { projection } = runAll(log.events);
  3570. const apply = (type: SessionEventTypeUnion, payload: unknown, turnId: string): void => {
  3571. projection.applyEvent(log.push(type, payload, { turnId }));
  3572. };
  3573. const appendCompletedTurn = (input: {
  3574. assistantMessageId: string;
  3575. input: string;
  3576. inputSource?: "background_task";
  3577. messageId: string;
  3578. turnId: string;
  3579. turnNumber: number;
  3580. }): void => {
  3581. apply(
  3582. SessionEventType.TurnStarted,
  3583. {
  3584. turnNumber: input.turnNumber,
  3585. input: input.input,
  3586. messageId: input.messageId,
  3587. ...(input.inputSource
  3588. ? { inputSource: input.inputSource, inputVisibility: "model-only" }
  3589. : {}),
  3590. },
  3591. input.turnId,
  3592. );
  3593. apply(
  3594. SessionEventType.ModelStreaming,
  3595. {
  3596. kind: "text_start",
  3597. delta: "",
  3598. done: false,
  3599. assistantMessageId: input.assistantMessageId,
  3600. },
  3601. input.turnId,
  3602. );
  3603. apply(
  3604. SessionEventType.ModelStreaming,
  3605. { kind: "text_delta", delta: `answer ${input.turnNumber}`, done: false },
  3606. input.turnId,
  3607. );
  3608. apply(
  3609. SessionEventType.ModelStreaming,
  3610. { kind: "text_end", delta: "", done: false },
  3611. input.turnId,
  3612. );
  3613. apply(
  3614. SessionEventType.TurnComplete,
  3615. {
  3616. response: `answer ${input.turnNumber}`,
  3617. tokenCount: 1,
  3618. toolCallCount: 0,
  3619. duration: 100,
  3620. resultType: "success",
  3621. },
  3622. input.turnId,
  3623. );
  3624. };
  3625. appendCompletedTurn({
  3626. assistantMessageId: "assistant-user-1",
  3627. input: "Q1",
  3628. messageId: "user-1",
  3629. turnId: "turn-user-1",
  3630. turnNumber: 1,
  3631. });
  3632. let assistantRows = projection
  3633. .getSnapshot()
  3634. .rows.window.filter((row) => row.kind === "assistantText");
  3635. expect(assistantRows.map((row) => row.actions?.canRetry === true)).toEqual([true]);
  3636. appendCompletedTurn({
  3637. assistantMessageId: "assistant-background-1",
  3638. input: "background result",
  3639. inputSource: "background_task",
  3640. messageId: "wake-1",
  3641. turnId: "turn-background-1",
  3642. turnNumber: 2,
  3643. });
  3644. assistantRows = projection
  3645. .getSnapshot()
  3646. .rows.window.filter((row) => row.kind === "assistantText");
  3647. expect(assistantRows.map((row) => row.actions?.canRetry === true)).toEqual([false, false]);
  3648. expect(assistantRows[1]!.actions?.canFork).toBe(true);
  3649. const backgroundEntityId = projection.getEntityIdForRow(assistantRows[1]!.rowId);
  3650. expect(backgroundEntityId).toBeTruthy();
  3651. expect(
  3652. projection.resolveRowActionTarget(
  3653. { rowId: assistantRows[1]!.rowId, entityId: backgroundEntityId! },
  3654. "retryTurn",
  3655. ),
  3656. ).toEqual({ ok: false, status: "rejected", reasonCode: "guard.actionUnavailable" });
  3657. appendCompletedTurn({
  3658. assistantMessageId: "assistant-user-2",
  3659. input: "Q2",
  3660. messageId: "user-2",
  3661. turnId: "turn-user-2",
  3662. turnNumber: 3,
  3663. });
  3664. assistantRows = projection
  3665. .getSnapshot()
  3666. .rows.window.filter((row) => row.kind === "assistantText");
  3667. expect(assistantRows.map((row) => row.actions?.canRetry === true)).toEqual([
  3668. false,
  3669. false,
  3670. true,
  3671. ]);
  3672. });
  3673. });
  3674. describe("V4 API 重试状态投影", () => {
  3675. function runningProjection(): { log: EventLog; projection: ProductProjection } {
  3676. const log = new EventLog();
  3677. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  3678. log.push(
  3679. SessionEventType.TurnStarted,
  3680. { turnNumber: 1, input: "触发模型请求", messageId: "user-retry-1" },
  3681. { turnId: "turn-retry-1" },
  3682. );
  3683. return { log, projection: runAll(log.events).projection };
  3684. }
  3685. function modelStatus(overrides: Record<string, unknown>): Record<string, unknown> {
  3686. return {
  3687. timestamp: "2026-07-14T07:25:25.985Z",
  3688. traceId: "trace-1",
  3689. requestId: "request-retry-1",
  3690. model: { providerId: "bigmodel", modelId: "glm-5.2" },
  3691. transport: "sse",
  3692. attempt: 1,
  3693. maxAttempts: 11,
  3694. ...overrides,
  3695. };
  3696. }
  3697. it("429 重试在两个 delivery profile 中可见,并保持到首次有效模型进展", () => {
  3698. const { log, projection } = runningProjection();
  3699. const scheduledAt = 1_721_000_000_000;
  3700. const scheduled = log.push(
  3701. SessionEventType.ModelNetworkStatus,
  3702. modelStatus({
  3703. type: "model_retry_scheduled",
  3704. delayMs: 44_000,
  3705. nextAttempt: 2,
  3706. reason: "rate_limited",
  3707. message: "rate limited",
  3708. statusCode: 429,
  3709. }),
  3710. { turnId: "turn-retry-1", timestampMs: scheduledAt },
  3711. );
  3712. const retryDeltas = projection.applyEvent(scheduled);
  3713. expect(projection.getSnapshot().control.apiRetry).toEqual({
  3714. attempt: 1,
  3715. maxAttempts: 11,
  3716. nextRetryAt: scheduledAt + 44_000,
  3717. reasonCode: "fault.provider.rateLimited",
  3718. });
  3719. expect(() => conversationSnapshotSchema.parse(projection.getSnapshot())).not.toThrow();
  3720. for (const profile of [DELIVERY_PROFILES.continuous, DELIVERY_PROFILES.replayable]) {
  3721. expect(filterConversationDeltasForProfile(retryDeltas, profile)).toEqual(retryDeltas);
  3722. }
  3723. const retryStarted = log.push(
  3724. SessionEventType.ModelNetworkStatus,
  3725. modelStatus({ type: "model_request_started", attempt: 2 }),
  3726. { turnId: "turn-retry-1" },
  3727. );
  3728. expect(projection.applyEvent(retryStarted)).toEqual([]);
  3729. expect(projection.getSnapshot().control.apiRetry?.attempt).toBe(1);
  3730. projection.applyEvent(
  3731. log.push(
  3732. SessionEventType.ModelStreaming,
  3733. {
  3734. kind: "text_start",
  3735. delta: "",
  3736. done: false,
  3737. assistantMessageId: "assistant-retry-1",
  3738. },
  3739. { turnId: "turn-retry-1" },
  3740. ),
  3741. );
  3742. expect(projection.getSnapshot().control.apiRetry?.attempt).toBe(1);
  3743. projection.applyEvent(
  3744. log.push(
  3745. SessionEventType.ModelStreaming,
  3746. { kind: "text_delta", delta: "连接已恢复", done: false },
  3747. { turnId: "turn-retry-1" },
  3748. ),
  3749. );
  3750. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  3751. });
  3752. it("签名修复复用 provider retry live-tail 状态", () => {
  3753. const { log, projection } = runningProjection();
  3754. const scheduledAt = 1_721_000_000_000;
  3755. projection.applyEvent(
  3756. log.push(
  3757. SessionEventType.ModelNetworkStatus,
  3758. modelStatus({
  3759. type: "model_retry_scheduled",
  3760. delayMs: 0,
  3761. maxAttempts: 2,
  3762. nextAttempt: 2,
  3763. reason: "reasoning_signature_repair",
  3764. message: "thinking signature rejected",
  3765. statusCode: 400,
  3766. }),
  3767. { turnId: "turn-retry-1", timestampMs: scheduledAt },
  3768. ),
  3769. );
  3770. expect(projection.getSnapshot().control.apiRetry).toEqual({
  3771. attempt: 1,
  3772. maxAttempts: 2,
  3773. nextRetryAt: scheduledAt,
  3774. reasonCode: "fault.provider.requestFailed",
  3775. });
  3776. });
  3777. it("忽略非当前 turn 的迟到重试与完成事件", () => {
  3778. const { log, projection } = runningProjection();
  3779. const retryPayload = modelStatus({
  3780. type: "model_retry_scheduled",
  3781. delayMs: 1_000,
  3782. nextAttempt: 2,
  3783. reason: "rate_limited",
  3784. message: "rate limited",
  3785. statusCode: 429,
  3786. });
  3787. projection.applyEvent(
  3788. log.push(SessionEventType.ModelNetworkStatus, retryPayload, { turnId: "turn-stale" }),
  3789. );
  3790. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  3791. projection.applyEvent(
  3792. log.push(SessionEventType.ModelNetworkStatus, retryPayload, { turnId: "turn-retry-1" }),
  3793. );
  3794. expect(projection.getSnapshot().control.apiRetry).not.toBeNull();
  3795. projection.applyEvent(
  3796. log.push(
  3797. SessionEventType.ModelNetworkStatus,
  3798. modelStatus({ type: "model_request_completed", durationMs: 50 }),
  3799. { turnId: "turn-stale" },
  3800. ),
  3801. );
  3802. expect(projection.getSnapshot().control.apiRetry).not.toBeNull();
  3803. });
  3804. it("请求完成、不可重试失败和 turn 终态都会清理重试状态", () => {
  3805. const { log, projection } = runningProjection();
  3806. const scheduleRetry = (attempt: number) =>
  3807. projection.applyEvent(
  3808. log.push(
  3809. SessionEventType.ModelNetworkStatus,
  3810. modelStatus({
  3811. type: "model_retry_scheduled",
  3812. attempt,
  3813. delayMs: 1_000,
  3814. nextAttempt: attempt + 1,
  3815. reason: "server_error",
  3816. message: "server error",
  3817. statusCode: 503,
  3818. }),
  3819. { turnId: "turn-retry-1" },
  3820. ),
  3821. );
  3822. scheduleRetry(1);
  3823. projection.applyEvent(
  3824. log.push(
  3825. SessionEventType.ModelNetworkStatus,
  3826. modelStatus({
  3827. type: "model_request_failed",
  3828. reason: "server_error",
  3829. retryable: true,
  3830. message: "retryable",
  3831. statusCode: 503,
  3832. }),
  3833. { turnId: "turn-retry-1" },
  3834. ),
  3835. );
  3836. expect(projection.getSnapshot().control.apiRetry).not.toBeNull();
  3837. projection.applyEvent(
  3838. log.push(
  3839. SessionEventType.ModelNetworkStatus,
  3840. modelStatus({ type: "model_request_completed", attempt: 2, durationMs: 50 }),
  3841. { turnId: "turn-retry-1" },
  3842. ),
  3843. );
  3844. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  3845. scheduleRetry(2);
  3846. projection.applyEvent(
  3847. log.push(
  3848. SessionEventType.ModelNetworkStatus,
  3849. modelStatus({
  3850. type: "model_request_failed",
  3851. attempt: 3,
  3852. reason: "server_error",
  3853. retryable: false,
  3854. message: "exhausted",
  3855. statusCode: 503,
  3856. }),
  3857. { turnId: "turn-retry-1" },
  3858. ),
  3859. );
  3860. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  3861. scheduleRetry(3);
  3862. projection.applyEvent(
  3863. log.push(
  3864. SessionEventType.TurnComplete,
  3865. {
  3866. response: "done",
  3867. tokenCount: 1,
  3868. toolCallCount: 0,
  3869. duration: 100,
  3870. resultType: "success",
  3871. },
  3872. { turnId: "turn-retry-1" },
  3873. ),
  3874. );
  3875. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  3876. });
  3877. it("core SSE 恢复次数进入同一 apiRetry,并在工具进展后清理", () => {
  3878. const { log, projection } = runningProjection();
  3879. const recoveryStartedAt = 1_721_000_100_000;
  3880. projection.applyEvent(
  3881. log.push(
  3882. SessionEventType.StreamRecoveryStarted,
  3883. {
  3884. attemptId: "stream-attempt-1",
  3885. assistantMessageId: "assistant-retry-1",
  3886. failedRequestId: "request-retry-1",
  3887. failureKind: "provider_stream_error",
  3888. message: "stream disconnected",
  3889. retryNumber: 3,
  3890. maxRetries: 10,
  3891. },
  3892. { turnId: "turn-retry-1", timestampMs: recoveryStartedAt },
  3893. ),
  3894. );
  3895. expect(projection.getSnapshot().control.apiRetry).toEqual({
  3896. attempt: 3,
  3897. maxAttempts: 11,
  3898. nextRetryAt: recoveryStartedAt,
  3899. reasonCode: "fault.network.sseDisconnected",
  3900. });
  3901. projection.applyEvent(
  3902. log.push(
  3903. SessionEventType.StreamRecoveryRetryStarted,
  3904. {
  3905. attemptId: "stream-attempt-1",
  3906. anchorId: "anchor-1",
  3907. failedRequestId: "request-retry-1",
  3908. retryNumber: 3,
  3909. maxRetries: 10,
  3910. streamMode: "sse",
  3911. },
  3912. { turnId: "turn-retry-1" },
  3913. ),
  3914. );
  3915. projection.applyEvent(
  3916. log.push(
  3917. SessionEventType.ModelNetworkStatus,
  3918. modelStatus({
  3919. type: "model_request_started",
  3920. streamRecovery: {
  3921. attemptId: "stream-attempt-1",
  3922. anchorId: "anchor-1",
  3923. recoveredFromRequestId: "request-retry-1",
  3924. retryNumber: 3,
  3925. maxRetries: 10,
  3926. },
  3927. }),
  3928. { turnId: "turn-retry-1" },
  3929. ),
  3930. );
  3931. expect(projection.getSnapshot().control.apiRetry).toMatchObject({
  3932. attempt: 3,
  3933. maxAttempts: 11,
  3934. reasonCode: "fault.network.sseDisconnected",
  3935. });
  3936. projection.applyEvent(
  3937. log.push(
  3938. SessionEventType.ModelStreaming,
  3939. {
  3940. kind: "tool_input_start",
  3941. delta: "",
  3942. done: false,
  3943. toolCallId: "tool-retry-1",
  3944. toolName: "Read",
  3945. },
  3946. { turnId: "turn-retry-1" },
  3947. ),
  3948. );
  3949. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  3950. });
  3951. it("reasoning-only recovery 将旧思考行收口为 interrupted,再用新行承接恢复流", () => {
  3952. const { log, projection } = runningProjection();
  3953. projection.applyEvent(
  3954. log.push(
  3955. SessionEventType.ModelStreaming,
  3956. { kind: "reasoning_start", delta: "", done: false },
  3957. { turnId: "turn-retry-1" },
  3958. ),
  3959. );
  3960. projection.applyEvent(
  3961. log.push(
  3962. SessionEventType.ModelStreaming,
  3963. { kind: "reasoning_delta", delta: "unfinished", done: false },
  3964. { turnId: "turn-retry-1" },
  3965. ),
  3966. );
  3967. projection.applyEvent(
  3968. log.push(
  3969. SessionEventType.StreamRecoveryTailDiscarded,
  3970. {
  3971. attemptId: "stream-attempt-1",
  3972. anchorId: "anchor-1",
  3973. assistantMessageId: "assistant-retry-1",
  3974. discardedReasoningBytes: 10,
  3975. discardedTextBytes: 0,
  3976. discardedToolCallIds: [],
  3977. },
  3978. { turnId: "turn-retry-1" },
  3979. ),
  3980. );
  3981. expect(projection.getSnapshot().rows.window.filter((row) => row.kind === "reasoning")).toEqual([
  3982. expect.objectContaining({ state: "interrupted", text: "unfinished" }),
  3983. ]);
  3984. projection.applyEvent(
  3985. log.push(
  3986. SessionEventType.ModelStreaming,
  3987. { kind: "reasoning_delta", delta: "fresh", done: false },
  3988. { turnId: "turn-retry-1" },
  3989. ),
  3990. );
  3991. expect(
  3992. projection
  3993. .getSnapshot()
  3994. .rows.window.filter((row) => row.kind === "reasoning")
  3995. .map((row) => ({ state: row.state, text: row.text })),
  3996. ).toEqual([
  3997. { state: "interrupted", text: "unfinished" },
  3998. { state: "streaming", text: "fresh" },
  3999. ]);
  4000. });
  4001. it("tail_discarded 收口未定稿的流式 tool row,已提交的 running 行不动,恢复流用新 id 重开", () => {
  4002. const { log, projection } = runningProjection();
  4003. const turnId = "turn-retry-1";
  4004. // 已提交并在执行中的工具:它的终态由 executor 发布,recovery 不能替它收口。
  4005. projection.applyEvent(
  4006. log.push(
  4007. SessionEventType.ToolCallScheduled,
  4008. {
  4009. toolCallId: "tool-committed",
  4010. assistantMessageId: "assistant-retry-1",
  4011. toolName: "Read",
  4012. input: { file_path: "a.ts" },
  4013. schedule: { parallelGroups: [["tool-committed"]], executionOrder: ["tool-committed"] },
  4014. },
  4015. { turnId },
  4016. ),
  4017. );
  4018. projection.applyEvent(
  4019. log.push(
  4020. SessionEventType.ToolCallStarted,
  4021. { toolCallId: "tool-committed", toolName: "Read", startedAt: new Date() },
  4022. { turnId },
  4023. ),
  4024. );
  4025. // 断流时只写到一半的 CreateWorkflow:tool_input_start 已开行,tool_call 永远不会来。
  4026. projection.applyEvent(
  4027. log.push(
  4028. SessionEventType.ModelStreaming,
  4029. {
  4030. kind: "tool_input_start",
  4031. delta: "",
  4032. done: false,
  4033. toolCallId: "tool-orphan",
  4034. toolName: "CreateWorkflow",
  4035. },
  4036. { turnId },
  4037. ),
  4038. );
  4039. projection.applyEvent(
  4040. log.push(
  4041. SessionEventType.ModelStreaming,
  4042. {
  4043. kind: "tool_input_delta",
  4044. delta: '{"script":"const a = agent(',
  4045. done: false,
  4046. toolCallId: "tool-orphan",
  4047. },
  4048. { turnId },
  4049. ),
  4050. );
  4051. projection.applyEvent(
  4052. log.push(
  4053. SessionEventType.StreamRecoveryTailDiscarded,
  4054. {
  4055. attemptId: "stream-attempt-1",
  4056. anchorId: "anchor-1",
  4057. assistantMessageId: "assistant-retry-1",
  4058. discardedReasoningBytes: 0,
  4059. discardedTextBytes: 12,
  4060. discardedToolCallIds: [],
  4061. },
  4062. { turnId },
  4063. ),
  4064. );
  4065. const toolRows = () =>
  4066. projection
  4067. .getSnapshot()
  4068. .rows.window.filter((row) => row.kind === "toolCall")
  4069. .map((row) => ({
  4070. toolCallId: row.toolCallId,
  4071. status: row.status,
  4072. inputText: row.inputText,
  4073. }));
  4074. expect(toolRows()).toEqual([
  4075. { toolCallId: "tool-committed", status: "running", inputText: '{"file_path":"a.ts"}' },
  4076. { toolCallId: "tool-orphan", status: "cancelled", inputText: '{"script":"const a = agent(' },
  4077. ]);
  4078. // 恢复请求重新写脚本:新 id 开新行,旧行保持已收口,不会并排两张「正在编写工作流」。
  4079. projection.applyEvent(
  4080. log.push(
  4081. SessionEventType.ModelStreaming,
  4082. {
  4083. kind: "tool_input_start",
  4084. delta: "",
  4085. done: false,
  4086. toolCallId: "tool-retry",
  4087. toolName: "CreateWorkflow",
  4088. },
  4089. { turnId },
  4090. ),
  4091. );
  4092. expect(toolRows().map((row) => [row.toolCallId, row.status])).toEqual([
  4093. ["tool-committed", "running"],
  4094. ["tool-orphan", "cancelled"],
  4095. ["tool-retry", "inputStreaming"],
  4096. ]);
  4097. });
  4098. });
  4099. // ── 结构性黄金测试(13-golden-test-mapping §v4 新增)──
  4100. describe("结构性不变量", () => {
  4101. function fullDeltaStream(events: readonly SessionEvent[]): {
  4102. deltasPerEvent: ConversationDelta[][];
  4103. snapshots: ConversationSnapshot[];
  4104. } {
  4105. const { deltasPerEvent, snapshots } = runAll(events);
  4106. return { deltasPerEvent, snapshots };
  4107. }
  4108. it("结构性1:任意水位 W 取 snapshot + 续流 ≡ 全量重放(R-03)", () => {
  4109. const log = new EventLog();
  4110. basicTurnEvents(log);
  4111. const { deltasPerEvent, snapshots } = fullDeltaStream(log.events);
  4112. const final = snapshots[snapshots.length - 1]!;
  4113. for (let w = 0; w < log.events.length; w++) {
  4114. const snapshotAtW = snapshots[w + 1]!;
  4115. const tail = deltasPerEvent.slice(w + 1).flat();
  4116. const resumed = applyConversationDeltas(snapshotAtW, tail);
  4117. // seq 由帧区间记账推进(不在 delta 内),对比时对齐到终值。
  4118. expect({ ...resumed, seq: final.seq }).toEqual(final);
  4119. }
  4120. });
  4121. it("结构性4(半):coalesce 后的 delta 流与逐条投递终态逐字节一致", () => {
  4122. const log = new EventLog();
  4123. basicTurnEvents(log);
  4124. const { deltasPerEvent, snapshots } = fullDeltaStream(log.events);
  4125. const base = snapshots[0]!;
  4126. const all = deltasPerEvent.flat();
  4127. const direct = applyConversationDeltas(base, all);
  4128. const coalesced = applyConversationDeltas(base, coalesceConversationDeltas(all));
  4129. expect(coalesced).toEqual(direct);
  4130. });
  4131. it("结构性10:fault 注入 session A,session B 投影逐字节不变(X 组)", () => {
  4132. const logA = new EventLog("session-a");
  4133. logA.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4134. logA.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-a" });
  4135. const logB = new EventLog("session-b");
  4136. basicTurnEvents(logB, "turn-b");
  4137. const projectionA = new ProductProjection("session-a", "epoch-1");
  4138. const projectionB = new ProductProjection("session-b", "epoch-1");
  4139. for (const event of logB.events) projectionB.applyEvent(event);
  4140. const snapshotB = structuredClone(projectionB.getSnapshot());
  4141. for (const event of logA.events) projectionA.applyEvent(event);
  4142. const fault = new EventLog("session-a");
  4143. fault.push(
  4144. SessionEventType.TurnError,
  4145. { error: { type: "fault.network.unreachable", message: "ECONNREFUSED" }, turnPhase: "model" },
  4146. { turnId: "turn-a" },
  4147. );
  4148. for (const event of fault.events) projectionA.applyEvent(event);
  4149. expect(projectionA.getSnapshot().control.phase).toBe("error");
  4150. expect(projectionB.getSnapshot()).toEqual(snapshotB);
  4151. });
  4152. it("revision 递进:结构性事件 +1 且随帧携带;纯 row.delta 不递增(R-04)", () => {
  4153. const log = new EventLog();
  4154. basicTurnEvents(log);
  4155. const { deltasPerEvent, snapshots } = fullDeltaStream(log.events);
  4156. deltasPerEvent.forEach((deltas, index) => {
  4157. const structural = deltas.some(
  4158. (delta) =>
  4159. delta.op === "row.appended" ||
  4160. delta.op === "row.upserted" ||
  4161. delta.op === "row.removed" ||
  4162. (delta.op === "state.updated" &&
  4163. Object.keys(delta.patch).some((key) => key !== "revision" && key !== "usage")),
  4164. );
  4165. const prev = snapshots[index]!.revision;
  4166. const next = snapshots[index + 1]!.revision;
  4167. if (structural) {
  4168. expect(next).toBe(prev + 1);
  4169. // 携带规则:含 revision 递增事件的帧,deltas 必含 state.updated.revision。
  4170. const carried = deltas.some(
  4171. (delta) => delta.op === "state.updated" && delta.patch.revision === next,
  4172. );
  4173. expect(carried).toBe(true);
  4174. } else {
  4175. expect(next).toBe(prev);
  4176. }
  4177. });
  4178. // 纯文本流事件(text_delta)revision 不动。
  4179. const textDeltaIndex = log.events.findIndex(
  4180. (event) =>
  4181. event.type === SessionEventType.ModelStreaming &&
  4182. (event.payload as { kind?: string }).kind === "text_delta",
  4183. );
  4184. expect(snapshots[textDeltaIndex + 1]!.revision).toBe(snapshots[textDeltaIndex]!.revision);
  4185. });
  4186. it("确定性:同一事件日志重放两次,投影与 delta 流逐字节一致(rowId 纯函数,R-04)", () => {
  4187. const log = new EventLog();
  4188. basicTurnEvents(log);
  4189. const first = runAll(log.events);
  4190. const second = runAll(log.events);
  4191. expect(second.projection.getSnapshot()).toEqual(first.projection.getSnapshot());
  4192. expect(second.deltasPerEvent).toEqual(first.deltasPerEvent);
  4193. });
  4194. });
  4195. // ── 结构性4:两 profile 终态逐字节一致(05 §delivery-profile 收敛性黄金测试)──
  4196. // 同一事件序列跑 continuous / replayable 两档 flush 管线(filter → coalesce → apply),
  4197. // 断言终态与逐条直投逐字节一致。replayable 只是中间帧少,终态必须相同——
  4198. // 这同时机械验证收口不变量:被 profile 过滤的 row.delta(inputText/output.text/
  4199. // summaryText)必须被后续不可过滤的 row.upserted 蕴含。
  4200. describe("结构性4:两 profile 终态一致", () => {
  4201. function pipelineFinalState(
  4202. events: readonly SessionEvent[],
  4203. profile: DeliveryProfile,
  4204. ): ConversationSnapshot {
  4205. const { deltasPerEvent, snapshots } = runAll(events);
  4206. const base = snapshots[0]!;
  4207. const piped = coalesceConversationDeltas(
  4208. filterConversationDeltasForProfile(deltasPerEvent.flat(), profile),
  4209. );
  4210. return applyConversationDeltas(base, piped);
  4211. }
  4212. function assertProfileConvergence(events: readonly SessionEvent[]): void {
  4213. const { deltasPerEvent, snapshots } = runAll(events);
  4214. const direct = applyConversationDeltas(snapshots[0]!, deltasPerEvent.flat());
  4215. expect(pipelineFinalState(events, DELIVERY_PROFILES.continuous)).toEqual(direct);
  4216. expect(pipelineFinalState(events, DELIVERY_PROFILES.replayable)).toEqual(direct);
  4217. }
  4218. it("基础 turn(文本流式)", () => {
  4219. const log = new EventLog();
  4220. basicTurnEvents(log);
  4221. assertProfileConvergence(log.events);
  4222. });
  4223. it("tool 输入流式 → 权限 → 执行成功(inputText 被 upsert 收口)", () => {
  4224. const turnId = "turn-1";
  4225. const log = new EventLog();
  4226. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4227. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run ls" }, { turnId });
  4228. log.push(
  4229. SessionEventType.ModelStreaming,
  4230. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-1", toolName: "bash" },
  4231. { turnId },
  4232. );
  4233. log.push(
  4234. SessionEventType.ModelStreaming,
  4235. { kind: "tool_input_delta", delta: '{"command":', done: false, toolCallId: "tc-1" },
  4236. { turnId },
  4237. );
  4238. log.push(
  4239. SessionEventType.ModelStreaming,
  4240. { kind: "tool_input_delta", delta: '"ls"}', done: false, toolCallId: "tc-1" },
  4241. { turnId },
  4242. );
  4243. log.push(
  4244. SessionEventType.ToolCallScheduled,
  4245. {
  4246. toolCallId: "tc-1",
  4247. toolName: "bash",
  4248. input: { command: "ls" },
  4249. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  4250. },
  4251. { turnId },
  4252. );
  4253. log.push(
  4254. SessionEventType.PermissionRequested,
  4255. {
  4256. requestId: "req-1",
  4257. toolCallId: "tc-1",
  4258. toolName: "bash",
  4259. riskLevel: "medium",
  4260. reason: "Run",
  4261. input: { command: "ls" },
  4262. },
  4263. { turnId },
  4264. );
  4265. log.push(
  4266. SessionEventType.PermissionResolved,
  4267. { requestId: "req-1", toolCallId: "tc-1", decision: "allow" },
  4268. { turnId },
  4269. );
  4270. log.push(
  4271. SessionEventType.ToolCallStarted,
  4272. { toolCallId: "tc-1", toolName: "bash", startedAt: new Date() },
  4273. { turnId },
  4274. );
  4275. log.push(
  4276. SessionEventType.ToolCallResult,
  4277. { toolCallId: "tc-1", result: { success: true, content: "file-a" }, duration: 42 },
  4278. { turnId },
  4279. );
  4280. log.push(
  4281. SessionEventType.TurnComplete,
  4282. { response: "done", tokenCount: 1, toolCallCount: 1, duration: 100, resultType: "success" },
  4283. { turnId },
  4284. );
  4285. assertProfileConvergence(log.events);
  4286. });
  4287. it("BG13:foreground subagent child tool 只留在 child conversation,main 仍由父 Agent 保持 running", () => {
  4288. const turnId = "turn-foreground-agent";
  4289. const parentToolCallId = "call_parent_agent";
  4290. const childToolCallId = "tool_subagent_agent-1_call_child_todo";
  4291. const mirrored = {
  4292. agentId: "agent-1",
  4293. agentType: "general-purpose",
  4294. childSessionId: "session-child-1",
  4295. childToolCallId: "call_child_todo",
  4296. description: "Inspect the project",
  4297. parentToolCallId,
  4298. source: "subagent",
  4299. };
  4300. const log = new EventLog();
  4301. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4302. log.push(
  4303. SessionEventType.TurnStarted,
  4304. { turnNumber: 1, input: "inspect with a foreground agent" },
  4305. { turnId },
  4306. );
  4307. log.push(
  4308. SessionEventType.ToolCallScheduled,
  4309. {
  4310. toolCallId: parentToolCallId,
  4311. toolName: "Agent",
  4312. input: { description: "Inspect the project", prompt: "Inspect the project" },
  4313. schedule: {
  4314. parallelGroups: [[parentToolCallId]],
  4315. executionOrder: [parentToolCallId],
  4316. },
  4317. },
  4318. { turnId },
  4319. );
  4320. log.push(
  4321. SessionEventType.ToolCallStarted,
  4322. { toolCallId: parentToolCallId, toolName: "Agent", startedAt: new Date() },
  4323. { turnId },
  4324. );
  4325. log.push(
  4326. SessionEventType.SubagentSpawned,
  4327. {
  4328. agentId: "agent-1",
  4329. agentType: "general-purpose",
  4330. childSessionId: "session-child-1",
  4331. description: "Inspect the project",
  4332. parentToolCallId,
  4333. status: "running",
  4334. },
  4335. { turnId },
  4336. );
  4337. log.push(
  4338. SessionEventType.ToolCallScheduled,
  4339. {
  4340. ...mirrored,
  4341. toolCallId: childToolCallId,
  4342. toolName: "TodoWrite",
  4343. input: { todos: [{ id: "child-only", content: "Read files", status: "in_progress" }] },
  4344. schedule: {
  4345. parallelGroups: [[childToolCallId]],
  4346. executionOrder: [childToolCallId],
  4347. },
  4348. },
  4349. { turnId },
  4350. );
  4351. log.push(
  4352. SessionEventType.ToolCallStarted,
  4353. { ...mirrored, toolCallId: childToolCallId, toolName: "TodoWrite", startedAt: new Date() },
  4354. { turnId },
  4355. );
  4356. log.push(
  4357. SessionEventType.ToolCallResult,
  4358. {
  4359. ...mirrored,
  4360. toolCallId: childToolCallId,
  4361. result: { success: true, content: "child todo updated" },
  4362. duration: 10,
  4363. },
  4364. { turnId },
  4365. );
  4366. assertProfileConvergence(log.events);
  4367. const snapshot = runAll(log.events).projection.getSnapshot();
  4368. expect(snapshot.control.phase).toBe("running");
  4369. expect(snapshot.plan).toBeNull();
  4370. expect(
  4371. snapshot.rows.window.filter((row) => row.kind === "toolCall").map((row) => row.toolCallId),
  4372. ).toEqual([parentToolCallId]);
  4373. expect(snapshot.rows.window).toContainEqual(
  4374. expect.objectContaining({
  4375. kind: "subagent",
  4376. childSessionId: "session-child-1",
  4377. parentToolCallId,
  4378. status: "running",
  4379. }),
  4380. );
  4381. const childLog = new EventLog();
  4382. childLog.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4383. childLog.push(
  4384. SessionEventType.TurnStarted,
  4385. { turnNumber: 1, input: "Inspect the project" },
  4386. { turnId: "turn-child-1" },
  4387. );
  4388. childLog.push(
  4389. SessionEventType.ToolCallScheduled,
  4390. {
  4391. toolCallId: "call_child_todo",
  4392. toolName: "TodoWrite",
  4393. input: { todos: [{ id: "child-only", content: "Read files", status: "in_progress" }] },
  4394. schedule: {
  4395. parallelGroups: [["call_child_todo"]],
  4396. executionOrder: ["call_child_todo"],
  4397. },
  4398. },
  4399. { turnId: "turn-child-1" },
  4400. );
  4401. childLog.push(
  4402. SessionEventType.ToolCallStarted,
  4403. { toolCallId: "call_child_todo", toolName: "TodoWrite", startedAt: new Date() },
  4404. { turnId: "turn-child-1" },
  4405. );
  4406. childLog.push(
  4407. SessionEventType.ToolCallResult,
  4408. {
  4409. toolCallId: "call_child_todo",
  4410. result: { success: true, content: "child todo updated" },
  4411. duration: 10,
  4412. },
  4413. { turnId: "turn-child-1" },
  4414. );
  4415. assertProfileConvergence(childLog.events);
  4416. expect(runAll(childLog.events).projection.getSnapshot().rows.window).toContainEqual(
  4417. expect.objectContaining({
  4418. kind: "toolCall",
  4419. toolCallId: "call_child_todo",
  4420. status: "success",
  4421. }),
  4422. );
  4423. });
  4424. it("BG26:真实失败 lifecycle 归并 hydration 合成行并补齐 child session 身份", () => {
  4425. const turnId = "turn-background-agent-rate-limit";
  4426. const parentToolCallId = "call-background-agent-rate-limit";
  4427. const realAgentId = "agent-background-rate-limit";
  4428. const childSessionId = "session-child-rate-limit";
  4429. const log = new EventLog();
  4430. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4431. log.push(
  4432. SessionEventType.TurnStarted,
  4433. { turnNumber: 1, input: "launch background agent" },
  4434. { turnId },
  4435. );
  4436. log.push(
  4437. SessionEventType.ToolCallScheduled,
  4438. {
  4439. toolCallId: parentToolCallId,
  4440. toolName: "Agent",
  4441. input: {
  4442. description: "Trigger provider rate limit",
  4443. prompt: "Trigger provider rate limit",
  4444. run_in_background: true,
  4445. },
  4446. schedule: {
  4447. parallelGroups: [[parentToolCallId]],
  4448. executionOrder: [parentToolCallId],
  4449. },
  4450. },
  4451. { turnId },
  4452. );
  4453. log.push(
  4454. SessionEventType.ToolCallStarted,
  4455. { toolCallId: parentToolCallId, toolName: "Agent", startedAt: new Date() },
  4456. { turnId },
  4457. );
  4458. // transcript hydration 只能从文本 tool output 合成出 toolCallId 身份,拿不到 childSessionId。
  4459. log.push(
  4460. SessionEventType.SubagentSpawned,
  4461. {
  4462. agentId: parentToolCallId,
  4463. agentType: "general-purpose",
  4464. description: "Trigger provider rate limit",
  4465. parentToolCallId,
  4466. status: "running",
  4467. },
  4468. { turnId },
  4469. );
  4470. // hydration await 窗口内补回的真实 spawned 也必须复用合成行,并建立真实 agentId 映射。
  4471. log.push(
  4472. SessionEventType.SubagentSpawned,
  4473. {
  4474. agentId: realAgentId,
  4475. agentType: "general-purpose",
  4476. background: true,
  4477. childSessionId,
  4478. description: "Trigger provider rate limit",
  4479. parentToolCallId,
  4480. status: "running",
  4481. },
  4482. { turnId },
  4483. );
  4484. // live terminal 事件携带真实 runtime 身份,必须更新上一行而不是追加重复 SubagentRow。
  4485. log.push(
  4486. SessionEventType.SubagentStopped,
  4487. {
  4488. agentId: realAgentId,
  4489. agentType: "general-purpose",
  4490. background: true,
  4491. parentToolCallId,
  4492. status: "failed",
  4493. error: "PROVIDER_ERROR: 429 rate limited",
  4494. },
  4495. { turnId },
  4496. );
  4497. const snapshot = runAll(log.events).projection.getSnapshot();
  4498. const subagentRows = snapshot.rows.window.filter(
  4499. (row): row is Extract<(typeof snapshot.rows.window)[number], { kind: "subagent" }> =>
  4500. row.kind === "subagent",
  4501. );
  4502. expect(subagentRows).toHaveLength(1);
  4503. expect(subagentRows[0]).toMatchObject({
  4504. childSessionId,
  4505. parentToolCallId,
  4506. status: "failed",
  4507. summaryText: "PROVIDER_ERROR: 429 rate limited",
  4508. });
  4509. });
  4510. it("BG35:background subagent child tool 不生成父 row,迟到终态也不复活", () => {
  4511. const turnId = "turn-background-agent";
  4512. const parentToolCallId = "call_parent_agent";
  4513. const childToolCallId = "tool_subagent_agent-1_call_child_bash";
  4514. const mirrored = {
  4515. agentId: "agent-1",
  4516. agentType: "general-purpose",
  4517. background: true,
  4518. childSessionId: "session-child-1",
  4519. childToolCallId: "call_child_bash",
  4520. description: "Run delayed Bash",
  4521. parentToolCallId,
  4522. source: "subagent",
  4523. };
  4524. const log = new EventLog();
  4525. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4526. log.push(
  4527. SessionEventType.TurnStarted,
  4528. { turnNumber: 1, input: "launch background agent" },
  4529. { turnId },
  4530. );
  4531. log.push(
  4532. SessionEventType.ToolCallScheduled,
  4533. {
  4534. toolCallId: parentToolCallId,
  4535. toolName: "Agent",
  4536. input: {
  4537. description: "Run delayed Bash",
  4538. prompt: "Run delayed Bash",
  4539. run_in_background: true,
  4540. },
  4541. schedule: {
  4542. parallelGroups: [[parentToolCallId]],
  4543. executionOrder: [parentToolCallId],
  4544. },
  4545. },
  4546. { turnId },
  4547. );
  4548. log.push(
  4549. SessionEventType.ToolCallStarted,
  4550. { toolCallId: parentToolCallId, toolName: "Agent", startedAt: new Date() },
  4551. { turnId },
  4552. );
  4553. log.push(
  4554. SessionEventType.ToolCallResult,
  4555. {
  4556. toolCallId: parentToolCallId,
  4557. result: { success: true, content: "background agent launched" },
  4558. duration: 5,
  4559. },
  4560. { turnId },
  4561. );
  4562. log.push(
  4563. SessionEventType.ToolCallScheduled,
  4564. {
  4565. ...mirrored,
  4566. toolCallId: childToolCallId,
  4567. toolName: "Bash",
  4568. input: { command: "sleep 60 && date" },
  4569. schedule: {
  4570. parallelGroups: [[childToolCallId]],
  4571. executionOrder: [childToolCallId],
  4572. },
  4573. },
  4574. { turnId },
  4575. );
  4576. log.push(
  4577. SessionEventType.ToolCallStarted,
  4578. { ...mirrored, toolCallId: childToolCallId, toolName: "Bash", startedAt: new Date() },
  4579. { turnId },
  4580. );
  4581. log.push(
  4582. SessionEventType.TurnComplete,
  4583. {
  4584. response: "launched",
  4585. tokenCount: 1,
  4586. toolCallCount: 1,
  4587. duration: 10,
  4588. resultType: "success",
  4589. },
  4590. { turnId },
  4591. );
  4592. const beforeChildTerminal = runAll(log.events).projection.getSnapshot();
  4593. expect(beforeChildTerminal.control.phase).toBe("completedSuccess");
  4594. expect(
  4595. beforeChildTerminal.rows.window
  4596. .filter((row) => row.kind === "toolCall")
  4597. .map((row) => row.toolCallId),
  4598. ).toEqual([parentToolCallId]);
  4599. log.push(
  4600. SessionEventType.ToolCallResult,
  4601. {
  4602. ...mirrored,
  4603. toolCallId: childToolCallId,
  4604. result: { success: true, content: "Fri Jul 17 12:40:36 CST 2026" },
  4605. duration: 60_000,
  4606. },
  4607. { turnId },
  4608. );
  4609. log.push(
  4610. SessionEventType.ToolCallError,
  4611. {
  4612. ...mirrored,
  4613. toolCallId: "tool_subagent_agent-1_call_child_error",
  4614. error: { type: "fault.runtime.toolFailed", message: "late child failure" },
  4615. },
  4616. { turnId },
  4617. );
  4618. assertProfileConvergence(log.events);
  4619. const terminalSnapshot = runAll(log.events).projection.getSnapshot();
  4620. expect(terminalSnapshot.control.phase).toBe("completedSuccess");
  4621. expect(
  4622. terminalSnapshot.rows.window
  4623. .filter((row) => row.kind === "toolCall")
  4624. .map((row) => row.toolCallId),
  4625. ).toEqual([parentToolCallId]);
  4626. });
  4627. it("BG18:父轮结束后的 child tool 事件不应清掉原 background Agent 控制身份", () => {
  4628. const parentTurnId = "turn-background-parent-anchor";
  4629. const followUpTurnId = "turn-background-parent-anchor-follow-up";
  4630. const parentToolCallId = "toolu_e2e_background_parent_anchor_agent";
  4631. const agentId = "agent-parent-anchor";
  4632. const childSessionId = "session-child-parent-anchor";
  4633. const log = new EventLog();
  4634. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4635. log.push(
  4636. SessionEventType.TurnStarted,
  4637. { turnNumber: 1, input: "launch background agent" },
  4638. { turnId: parentTurnId },
  4639. );
  4640. log.push(
  4641. SessionEventType.SubagentSpawned,
  4642. {
  4643. agentId,
  4644. agentType: "general-purpose",
  4645. background: true,
  4646. childSessionId,
  4647. description: "E2E background child tool parent anchor",
  4648. parentToolCallId,
  4649. status: "running",
  4650. },
  4651. { turnId: parentTurnId },
  4652. );
  4653. log.push(SessionEventType.TurnComplete, {}, { turnId: parentTurnId });
  4654. log.push(
  4655. SessionEventType.TurnStarted,
  4656. { turnNumber: 2, input: "finish a main follow-up first" },
  4657. { turnId: followUpTurnId },
  4658. );
  4659. log.push(SessionEventType.TurnComplete, {}, { turnId: followUpTurnId });
  4660. log.push(
  4661. SessionEventType.ToolCallStarted,
  4662. {
  4663. agentId,
  4664. childSessionId,
  4665. parentToolCallId,
  4666. source: "subagent",
  4667. toolCallId: "toolu_e2e_background_parent_anchor_child_bash",
  4668. toolName: "Bash",
  4669. },
  4670. { turnId: parentTurnId },
  4671. );
  4672. const snapshot = runAll(log.events).projection.getSnapshot();
  4673. expect(snapshot.subagents.running).toEqual([
  4674. expect.objectContaining({
  4675. agentId,
  4676. childSessionId,
  4677. title: "E2E background child tool parent anchor",
  4678. }),
  4679. ]);
  4680. });
  4681. it("tool 输入流到一半被 stop(cancelled 收口,inputStreaming 不悬挂)", () => {
  4682. const turnId = "turn-1";
  4683. const log = new EventLog();
  4684. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4685. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  4686. log.push(
  4687. SessionEventType.ModelStreaming,
  4688. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-1", toolName: "bash" },
  4689. { turnId },
  4690. );
  4691. log.push(
  4692. SessionEventType.ModelStreaming,
  4693. { kind: "tool_input_delta", delta: '{"command":"rm', done: false, toolCallId: "tc-1" },
  4694. { turnId },
  4695. );
  4696. log.push(
  4697. SessionEventType.TurnComplete,
  4698. { response: "", tokenCount: 0, toolCallCount: 0, duration: 50, resultType: "cancelled" },
  4699. { turnId },
  4700. );
  4701. assertProfileConvergence(log.events);
  4702. // 收口语义本体:中断后 tool row 必须离开 inputStreaming(cancelled + 完整 inputText)。
  4703. const { projection } = runAll(log.events);
  4704. expect(
  4705. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  4706. ).toMatchObject({ status: "cancelled", inputText: '{"command":"rm' });
  4707. });
  4708. it("success turn 兜底收口缺少 terminal event 的 foreground tool", () => {
  4709. const turnId = "turn-1";
  4710. const log = new EventLog();
  4711. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4712. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "search" }, { turnId });
  4713. log.push(
  4714. SessionEventType.ModelStreaming,
  4715. {
  4716. kind: "tool_input_start",
  4717. delta: "",
  4718. done: false,
  4719. toolCallId: "tc-missing",
  4720. toolName: "GrepMissingFromRegistry",
  4721. },
  4722. { turnId },
  4723. );
  4724. log.push(
  4725. SessionEventType.ModelStreaming,
  4726. {
  4727. kind: "tool_input_delta",
  4728. delta: '{"pattern":"needle"}',
  4729. done: false,
  4730. toolCallId: "tc-missing",
  4731. },
  4732. { turnId },
  4733. );
  4734. log.push(
  4735. SessionEventType.PermissionRequested,
  4736. {
  4737. requestId: "req-missing",
  4738. toolCallId: "tc-missing",
  4739. toolName: "GrepMissingFromRegistry",
  4740. riskLevel: "low",
  4741. reason: "Search",
  4742. input: { pattern: "needle" },
  4743. },
  4744. { turnId },
  4745. );
  4746. log.push(
  4747. SessionEventType.TurnComplete,
  4748. { response: "done", tokenCount: 1, toolCallCount: 1, duration: 50, resultType: "success" },
  4749. { turnId },
  4750. );
  4751. assertProfileConvergence(log.events);
  4752. const { projection } = runAll(log.events);
  4753. expect(
  4754. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  4755. ).toMatchObject({
  4756. status: "error",
  4757. inputText: '{"pattern":"needle"}',
  4758. error: { code: "fault.runtime.toolLifecycleIncomplete" },
  4759. });
  4760. expect(projection.getSnapshot().pendingInteractions).toEqual([]);
  4761. });
  4762. it("reasoning 流式 + 中断", () => {
  4763. const turnId = "turn-1";
  4764. const log = new EventLog();
  4765. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4766. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "think" }, { turnId });
  4767. log.push(
  4768. SessionEventType.ModelStreaming,
  4769. { kind: "reasoning_start", delta: "", done: false },
  4770. { turnId },
  4771. );
  4772. log.push(
  4773. SessionEventType.ModelStreaming,
  4774. { kind: "reasoning_delta", delta: "hmm...", done: false },
  4775. { turnId },
  4776. );
  4777. log.push(
  4778. SessionEventType.ModelStreaming,
  4779. { kind: "text_start", delta: "", done: false },
  4780. { turnId },
  4781. );
  4782. log.push(
  4783. SessionEventType.ModelStreaming,
  4784. { kind: "text_delta", delta: "part", done: false },
  4785. { turnId },
  4786. );
  4787. log.push(
  4788. SessionEventType.TurnComplete,
  4789. { response: "", tokenCount: 0, toolCallCount: 0, duration: 10, resultType: "cancelled" },
  4790. { turnId },
  4791. );
  4792. assertProfileConvergence(log.events);
  4793. });
  4794. it("compact 生命周期(marker + usage 回落)", () => {
  4795. const log = new EventLog();
  4796. basicTurnEvents(log);
  4797. log.push(SessionEventType.CompactStarted, {
  4798. operationId: "op-1",
  4799. messageId: "msg-1",
  4800. status: "started",
  4801. trigger: "manual",
  4802. display: "separator",
  4803. sourceCommandId: "command-compact",
  4804. });
  4805. log.push(SessionEventType.CompactCompleted, {
  4806. operationId: "op-1",
  4807. messageId: "msg-1",
  4808. status: "completed",
  4809. trigger: "manual",
  4810. display: "separator",
  4811. preCompactTokenCount: 150,
  4812. postCompactTokenCount: 50,
  4813. });
  4814. assertProfileConvergence(log.events);
  4815. });
  4816. it("goal set → verify pass → fork → modelChange 全链路", () => {
  4817. const log = new EventLog();
  4818. basicTurnEvents(log);
  4819. log.push(SessionEventType.TargetChanged, {
  4820. action: "set",
  4821. source: "command",
  4822. target: {
  4823. sessionID: "session-1",
  4824. targetID: "target-1",
  4825. objective: "修绿",
  4826. summaryTitle: null,
  4827. status: "active",
  4828. tokenBudget: null,
  4829. tokensUsed: 0,
  4830. timeUsedSeconds: 0,
  4831. time: { created: 0, updated: 0 },
  4832. },
  4833. previousTarget: null,
  4834. });
  4835. log.push(SessionEventType.TargetCompletionVerification, {
  4836. targetId: "target-1",
  4837. status: "started",
  4838. verificationId: "verify-1",
  4839. goalIteration: 1,
  4840. });
  4841. log.push(SessionEventType.TargetCompletionVerification, {
  4842. targetId: "target-1",
  4843. status: "completed",
  4844. verificationId: "verify-1",
  4845. goalIteration: 1,
  4846. verification: { passed: true, reason: "ok" },
  4847. });
  4848. log.push(SessionEventType.SessionForked, {
  4849. originalSessionId: "session-1",
  4850. forkedSessionId: "session-child",
  4851. });
  4852. log.push(SessionEventType.ModelSelected, {
  4853. modelSelection: { providerId: "anthropic", modelId: "claude-4" },
  4854. });
  4855. log.push(SessionEventType.ModelSelected, {
  4856. modelSelection: { providerId: "openai", modelId: "gpt-6" },
  4857. });
  4858. assertProfileConvergence(log.events);
  4859. });
  4860. });
  4861. // ── G 组:compact marker ──
  4862. describe("compact marker(10 §4.4.7 / §6.4)", () => {
  4863. it("G:manual compact running→success —— 同一 marker row 状态迁移 + usage 回落", () => {
  4864. const log = new EventLog();
  4865. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  4866. log.push(SessionEventType.CompactStarted, {
  4867. operationId: "op-1",
  4868. messageId: "msg-marker",
  4869. status: "started",
  4870. trigger: "manual",
  4871. display: "separator",
  4872. sourceCommandId: "command-compact",
  4873. });
  4874. const { projection, deltasPerEvent } = runAll(log.events);
  4875. const runningMarker = projection
  4876. .getSnapshot()
  4877. .rows.window.find((row) => row.kind === "timelineMarker");
  4878. expect(runningMarker).toMatchObject({
  4879. sourceCommandId: "command-compact",
  4880. marker: { type: "compact", origin: "manual", status: "running" },
  4881. });
  4882. expect(deltasPerEvent[1]![0]!.op).toBe("row.appended");
  4883. projection.applyEvent(
  4884. new EventLog().push(SessionEventType.CompactCompleted, {
  4885. operationId: "op-1",
  4886. messageId: "msg-marker",
  4887. status: "completed",
  4888. trigger: "manual",
  4889. display: "separator",
  4890. sourceCommandId: "command-compact",
  4891. preCompactTokenCount: 100_000,
  4892. postCompactTokenCount: 30_000,
  4893. truePostCompactTokenCount: 20_000,
  4894. summaryMessageId: "msg-summary",
  4895. }),
  4896. );
  4897. const snapshot = projection.getSnapshot();
  4898. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  4899. const markers = snapshot.rows.window.filter((row) => row.kind === "timelineMarker");
  4900. // 全生命周期占同一行:终态是 upsert 不是新行。
  4901. expect(markers).toHaveLength(1);
  4902. expect(markers[0]).toMatchObject({
  4903. rowId: runningMarker?.rowId,
  4904. sourceCommandId: "command-compact",
  4905. marker: {
  4906. type: "compact",
  4907. origin: "manual",
  4908. status: "success",
  4909. tokensBefore: 100_000,
  4910. tokensAfter: 20_000,
  4911. summaryRef: "msg-summary",
  4912. },
  4913. });
  4914. // compact 成功 → context 水位立即回落(§6.4)。
  4915. expect(snapshot.usage.contextWindow?.usedTokens).toBe(20_000);
  4916. });
  4917. it("G12:auto compact 被 stop —— marker=cancelled,usage 不动", () => {
  4918. const log = new EventLog();
  4919. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4920. log.push(SessionEventType.CompactStarted, {
  4921. operationId: "op-1",
  4922. messageId: "msg-1",
  4923. status: "started",
  4924. trigger: "auto",
  4925. display: "separator",
  4926. });
  4927. log.push(SessionEventType.CompactFailed, {
  4928. operationId: "op-1",
  4929. messageId: "msg-1",
  4930. status: "interrupted",
  4931. trigger: "auto",
  4932. display: "separator",
  4933. });
  4934. const { projection } = runAll(log.events);
  4935. const snapshot = projection.getSnapshot();
  4936. expect(snapshot.rows.window.find((row) => row.kind === "timelineMarker")).toMatchObject({
  4937. marker: { type: "compact", origin: "auto", status: "cancelled" },
  4938. });
  4939. expect(snapshot.usage.contextWindow).toBeNull();
  4940. });
  4941. it("F09:compact 失败 —— marker=failed(retry 入口),会话状态不受污染", () => {
  4942. const log = new EventLog();
  4943. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4944. log.push(SessionEventType.CompactStarted, {
  4945. operationId: "op-1",
  4946. messageId: "msg-1",
  4947. status: "started",
  4948. trigger: "manual",
  4949. display: "separator",
  4950. });
  4951. log.push(SessionEventType.CompactFailed, {
  4952. operationId: "op-1",
  4953. messageId: "msg-1",
  4954. status: "failed",
  4955. trigger: "manual",
  4956. display: "separator",
  4957. reason: "api_error",
  4958. });
  4959. const { projection } = runAll(log.events);
  4960. const snapshot = projection.getSnapshot();
  4961. expect(snapshot.rows.window.find((row) => row.kind === "timelineMarker")).toMatchObject({
  4962. marker: { type: "compact", status: "failed" },
  4963. });
  4964. expect(snapshot.control.lastError).toBeNull();
  4965. });
  4966. });
  4967. // ── goal 状态机(10 §4.2.8)──
  4968. describe("goal 状态机", () => {
  4969. const goalTarget = (status: string, objective = "把测试全修绿") => ({
  4970. sessionID: "session-1",
  4971. targetID: "target-1",
  4972. objective,
  4973. summaryTitle: null,
  4974. status,
  4975. tokenBudget: null,
  4976. tokensUsed: 0,
  4977. timeUsedSeconds: 0,
  4978. time: { created: 0, updated: 0 },
  4979. });
  4980. it("goal set → stateOnly(不产 row)+ GoalState.active;verify pass → verified + 摘要锚点", () => {
  4981. const log = new EventLog();
  4982. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4983. log.push(SessionEventType.TargetChanged, {
  4984. action: "set",
  4985. source: "command",
  4986. target: goalTarget("active"),
  4987. previousTarget: null,
  4988. });
  4989. log.push(SessionEventType.TargetCompletionVerification, {
  4990. targetId: "target-1",
  4991. status: "started",
  4992. verificationId: "verify-1",
  4993. foregroundExecutionId: "foreground-1",
  4994. goalIteration: 1,
  4995. });
  4996. const { projection } = runAll(log.events);
  4997. const verifying = projection.getSnapshot();
  4998. expect(verifying.goal).toMatchObject({
  4999. objective: "把测试全修绿",
  5000. status: "verifying",
  5001. iteration: 1,
  5002. });
  5003. expect(verifying.control).toMatchObject({
  5004. phase: "running",
  5005. canStop: true,
  5006. stopState: "stoppable",
  5007. stopTargetKind: "goalVerifier",
  5008. sessionEnded: false,
  5009. });
  5010. expect(verifying.control.activeWorks).toEqual([
  5011. expect.objectContaining({
  5012. kind: "goalVerifier",
  5013. foregroundExecutionId: "foreground-1",
  5014. }),
  5015. ]);
  5016. expect(verifying.inputRouting).toEqual({
  5017. mode: "enqueue",
  5018. reasonCode: "goalVerifierAcceptsFutureInput",
  5019. });
  5020. const verifyMarker = verifying.rows.window.find(
  5021. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  5022. );
  5023. expect(verifyMarker).toMatchObject({
  5024. marker: { type: "goalVerify", iteration: 1, outcome: "running" },
  5025. });
  5026. // S10(16-plan,2026-07-08 裁决):goalSet 是 stateOnly——不进 rows.window
  5027. //(旧实现产「渲染 null」的隐形行,污染 turn 分组),目标由 goal 面板承载。
  5028. expect(
  5029. verifying.rows.window.find(
  5030. (row) => row.kind === "timelineMarker" && row.marker.type === "goalSet",
  5031. ),
  5032. ).toBeUndefined();
  5033. projection.applyEvent(
  5034. new EventLog().push(SessionEventType.TargetCompletionVerification, {
  5035. targetId: "target-1",
  5036. status: "completed",
  5037. verificationId: "verify-1",
  5038. goalIteration: 1,
  5039. verification: { passed: true, reason: "全部通过" },
  5040. }),
  5041. );
  5042. const done = projection.getSnapshot();
  5043. expect(() => conversationSnapshotSchema.parse(done)).not.toThrow();
  5044. expect(done.goal).toMatchObject({ status: "verified", iteration: 1 });
  5045. expect(done.control).toMatchObject({
  5046. phase: "completedSuccess",
  5047. canStop: false,
  5048. stopState: "idle",
  5049. stopTargetKind: "unknown",
  5050. sessionEnded: true,
  5051. });
  5052. expect(done.control.activeWorks).toEqual([]);
  5053. expect(done.goal?.verifications).toEqual([
  5054. expect.objectContaining({
  5055. iteration: 1,
  5056. outcome: "pass",
  5057. anchorRowId: verifyMarker?.rowId,
  5058. }),
  5059. ]);
  5060. // marker 就地终态化(同 rowId)。
  5061. expect(
  5062. done.rows.window.find(
  5063. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  5064. ),
  5065. ).toMatchObject({
  5066. rowId: verifyMarker?.rowId,
  5067. marker: { outcome: "pass", detail: "全部通过" },
  5068. });
  5069. });
  5070. it("goal verifier 被 Stop 时暂停已有 future queue", () => {
  5071. const log = new EventLog();
  5072. log.push(SessionEventType.SessionCreated, {
  5073. mode: "default",
  5074. contextWindow: 1000,
  5075. });
  5076. log.push(SessionEventType.TargetChanged, {
  5077. action: "set",
  5078. source: "command",
  5079. target: goalTarget("active"),
  5080. previousTarget: null,
  5081. });
  5082. log.push(SessionEventType.TargetCompletionVerification, {
  5083. targetId: "target-1",
  5084. status: "started",
  5085. verificationId: "verify-stop",
  5086. foregroundExecutionId: "foreground-stop",
  5087. goalIteration: 1,
  5088. });
  5089. log.push(SessionEventType.TurnSteerQueued, {
  5090. pendingInputId: "queue-after-verifier",
  5091. inputId: "command-after-verifier",
  5092. input: "verifier 后继续的问题",
  5093. inputPreview: "verifier 后继续的问题",
  5094. inputSize: 13,
  5095. targetTurnId: "turn-goal",
  5096. queueLength: 1,
  5097. delivery: "queue",
  5098. });
  5099. log.push(SessionEventType.TargetCompletionVerification, {
  5100. targetId: "target-1",
  5101. status: "cancelled",
  5102. verificationId: "verify-stop",
  5103. foregroundExecutionId: "foreground-stop",
  5104. goalIteration: 1,
  5105. });
  5106. const { projection } = runAll(log.events);
  5107. const snapshot = projection.getSnapshot();
  5108. expect(snapshot.goal?.status).toBe("paused");
  5109. expect(snapshot.queue).toMatchObject({
  5110. autoDrain: false,
  5111. pauseReason: "stopped",
  5112. items: [expect.objectContaining({ queueItemId: "queue-after-verifier" })],
  5113. });
  5114. expect(snapshot.inputRouting).toEqual({
  5115. mode: "choice",
  5116. reasonCode: "heldQueueInputRequiresChoice",
  5117. });
  5118. });
  5119. it("M07j:sendQueuedNow 抢占 goal verifier 时不暂停 future queue", () => {
  5120. const log = new EventLog();
  5121. log.push(SessionEventType.SessionCreated, {
  5122. mode: "default",
  5123. contextWindow: 1000,
  5124. });
  5125. log.push(SessionEventType.TargetChanged, {
  5126. action: "set",
  5127. source: "command",
  5128. target: goalTarget("active"),
  5129. previousTarget: null,
  5130. });
  5131. log.push(SessionEventType.TargetCompletionVerification, {
  5132. targetId: "target-1",
  5133. status: "started",
  5134. verificationId: "verify-send-now",
  5135. foregroundExecutionId: "foreground-send-now",
  5136. goalIteration: 1,
  5137. });
  5138. log.push(SessionEventType.TurnSteerQueued, {
  5139. pendingInputId: "queue-send-now",
  5140. inputId: "command-send-now",
  5141. input: "立即发送的问题",
  5142. inputPreview: "立即发送的问题",
  5143. inputSize: 21,
  5144. targetTurnId: "turn-goal",
  5145. queueLength: 1,
  5146. delivery: "queue",
  5147. });
  5148. log.push(SessionEventType.TargetCompletionVerification, {
  5149. targetId: "target-1",
  5150. status: "cancelled",
  5151. verificationId: "verify-send-now",
  5152. foregroundExecutionId: "foreground-send-now",
  5153. preserveQueueAutoDrainOnCancel: true,
  5154. goalIteration: 1,
  5155. });
  5156. const { projection } = runAll(log.events);
  5157. const snapshot = projection.getSnapshot();
  5158. expect(snapshot.goal?.status).toBe("paused");
  5159. expect(snapshot.queue).toMatchObject({
  5160. autoDrain: true,
  5161. items: [expect.objectContaining({ queueItemId: "queue-send-now" })],
  5162. });
  5163. expect(snapshot.queue.pauseReason).toBeUndefined();
  5164. expect(snapshot.inputRouting.mode).toBe("startNow");
  5165. });
  5166. it("verify notSatisfied —— 有效结论与过程失败分离(goalVerificationOutcomeSeparation)", () => {
  5167. const log = new EventLog();
  5168. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5169. log.push(SessionEventType.TargetChanged, {
  5170. action: "set",
  5171. source: "command",
  5172. target: goalTarget("active"),
  5173. });
  5174. log.push(SessionEventType.TargetCompletionVerification, {
  5175. targetId: "target-1",
  5176. status: "started",
  5177. verificationId: "verify-1",
  5178. goalIteration: 1,
  5179. });
  5180. log.push(SessionEventType.TargetCompletionVerification, {
  5181. targetId: "target-1",
  5182. status: "completed",
  5183. verificationId: "verify-1",
  5184. goalIteration: 1,
  5185. verification: { passed: false, reason: "还有 2 个用例红" },
  5186. });
  5187. const { projection } = runAll(log.events);
  5188. expect(projection.getSnapshot().goal).toMatchObject({ status: "notSatisfied" });
  5189. expect(projection.getSnapshot().goal?.verifications[0]).toMatchObject({
  5190. outcome: "notSatisfied",
  5191. });
  5192. });
  5193. it("H13-H16:投影 target 计时/标题、verifier action 与逐轮 Todo 状态", () => {
  5194. const log = new EventLog();
  5195. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5196. log.push(SessionEventType.TargetChanged, {
  5197. action: "set",
  5198. source: "command",
  5199. target: {
  5200. ...goalTarget("active"),
  5201. summaryTitle: "第一轮:恢复摘要",
  5202. timeUsedSeconds: 7,
  5203. activeRunStartedAtMs: 1_700_000_001_000,
  5204. },
  5205. });
  5206. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "first" }, { turnId: "turn-1" });
  5207. log.push(
  5208. SessionEventType.ToolCallScheduled,
  5209. {
  5210. toolCallId: "todo-1",
  5211. toolName: "TodoWrite",
  5212. input: {
  5213. todos: [{ content: "恢复计时", status: "completed", priority: "high" }],
  5214. },
  5215. schedule: { parallelGroups: [["todo-1"]], executionOrder: ["todo-1"] },
  5216. },
  5217. { turnId: "turn-1" },
  5218. );
  5219. log.push(
  5220. SessionEventType.TurnComplete,
  5221. { response: "done", tokenCount: 1, toolCallCount: 1, duration: 1, resultType: "success" },
  5222. { turnId: "turn-1" },
  5223. );
  5224. log.push(SessionEventType.TargetCompletionVerification, {
  5225. targetId: "target-1",
  5226. status: "started",
  5227. verificationId: "verify-1",
  5228. goalIteration: 1,
  5229. });
  5230. log.push(SessionEventType.TargetCompletionVerification, {
  5231. targetId: "target-1",
  5232. status: "completed",
  5233. verificationId: "verify-1",
  5234. goalIteration: 1,
  5235. verification: {
  5236. passed: false,
  5237. reason: "还缺暂停状态",
  5238. nextAction: "第二轮:补暂停和完成态",
  5239. },
  5240. });
  5241. log.push(SessionEventType.TargetChanged, {
  5242. action: "run_started",
  5243. source: "runtime",
  5244. target: {
  5245. ...goalTarget("active"),
  5246. summaryTitle: "第一轮:恢复摘要",
  5247. timeUsedSeconds: 11,
  5248. activeRunStartedAtMs: 1_700_000_009_000,
  5249. },
  5250. });
  5251. log.push(
  5252. SessionEventType.TurnStarted,
  5253. { turnNumber: 2, input: "second" },
  5254. { turnId: "turn-2" },
  5255. );
  5256. log.push(
  5257. SessionEventType.ToolCallScheduled,
  5258. {
  5259. toolCallId: "todo-2",
  5260. toolName: "todo_write",
  5261. input: {
  5262. todos: [
  5263. { content: "恢复暂停按钮", status: "in_progress", priority: "high" },
  5264. { content: "恢复完成图标", status: "pending", priority: "medium" },
  5265. ],
  5266. },
  5267. schedule: { parallelGroups: [["todo-2"]], executionOrder: ["todo-2"] },
  5268. },
  5269. { turnId: "turn-2" },
  5270. );
  5271. const { projection } = runAll(log.events);
  5272. const snapshot = projection.getSnapshot();
  5273. expect(snapshot.goal).toMatchObject({
  5274. targetId: "target-1",
  5275. summaryTitle: "第一轮:恢复摘要",
  5276. timeUsedSeconds: 11,
  5277. activeRunStartedAtMs: 1_700_000_009_000,
  5278. status: "active",
  5279. iteration: 1,
  5280. verifications: [
  5281. expect.objectContaining({
  5282. iteration: 1,
  5283. outcome: "notSatisfied",
  5284. reason: "还缺暂停状态",
  5285. nextAction: "第二轮:补暂停和完成态",
  5286. }),
  5287. ],
  5288. iterations: [
  5289. expect.objectContaining({
  5290. iteration: 1,
  5291. items: [expect.objectContaining({ content: "恢复计时", status: "completed" })],
  5292. }),
  5293. expect.objectContaining({
  5294. iteration: 2,
  5295. items: [
  5296. expect.objectContaining({ content: "恢复暂停按钮", status: "inProgress" }),
  5297. expect.objectContaining({ content: "恢复完成图标", status: "pending" }),
  5298. ],
  5299. }),
  5300. ],
  5301. });
  5302. expect(snapshot.plan?.items).toHaveLength(2);
  5303. expect(snapshot.availability.pauseGoal).toEqual({ allowed: true });
  5304. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  5305. });
  5306. it("stopPausesActiveGoalTarget:stop(cancelled turn)把 active goal 压成 paused,resumeGoal 放行", () => {
  5307. const log = new EventLog();
  5308. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5309. log.push(SessionEventType.TargetChanged, {
  5310. action: "set",
  5311. source: "command",
  5312. target: goalTarget("active"),
  5313. });
  5314. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "go" }, { turnId: "turn-1" });
  5315. log.push(
  5316. SessionEventType.TurnComplete,
  5317. { response: "", tokenCount: 0, toolCallCount: 0, duration: 100, resultType: "cancelled" },
  5318. { turnId: "turn-1" },
  5319. );
  5320. const { projection } = runAll(log.events);
  5321. const snapshot = projection.getSnapshot();
  5322. expect(snapshot.goal).toMatchObject({ status: "paused" });
  5323. expect(snapshot.availability.resumeGoal).toEqual({ allowed: true });
  5324. });
  5325. it("verify 被 stop(cancelled)—— marker=failed(detail=cancelled),goal 回 paused,摘要不追加", () => {
  5326. const log = new EventLog();
  5327. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5328. log.push(SessionEventType.TargetChanged, {
  5329. action: "set",
  5330. source: "command",
  5331. target: goalTarget("active"),
  5332. });
  5333. log.push(SessionEventType.TargetCompletionVerification, {
  5334. targetId: "target-1",
  5335. status: "started",
  5336. verificationId: "verify-1",
  5337. goalIteration: 1,
  5338. });
  5339. log.push(SessionEventType.TargetCompletionVerification, {
  5340. targetId: "target-1",
  5341. status: "cancelled",
  5342. verificationId: "verify-1",
  5343. goalIteration: 1,
  5344. });
  5345. const { projection } = runAll(log.events);
  5346. const snapshot = projection.getSnapshot();
  5347. expect(snapshot.goal).toMatchObject({ status: "paused" });
  5348. expect(snapshot.goal?.verifications).toHaveLength(0);
  5349. expect(
  5350. snapshot.rows.window.find(
  5351. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  5352. ),
  5353. ).toMatchObject({ marker: { outcome: "failed", detail: "cancelled" } });
  5354. expect(snapshot.availability.resumeGoal).toEqual({ allowed: true });
  5355. });
  5356. it("goal cleared → GoalState=null;重复 status_updated 值未变不下发(conflation)", () => {
  5357. const log = new EventLog();
  5358. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5359. log.push(SessionEventType.TargetChanged, {
  5360. action: "set",
  5361. source: "command",
  5362. target: goalTarget("active"),
  5363. });
  5364. const { projection } = runAll(log.events);
  5365. const noop = new EventLog().push(SessionEventType.TargetChanged, {
  5366. action: "status_updated",
  5367. source: "runtime",
  5368. target: goalTarget("active"),
  5369. });
  5370. expect(projection.applyEvent(noop)).toEqual([]);
  5371. projection.applyEvent(
  5372. new EventLog().push(SessionEventType.TargetChanged, {
  5373. action: "cleared",
  5374. source: "command",
  5375. target: null,
  5376. }),
  5377. );
  5378. expect(projection.getSnapshot().goal).toBeNull();
  5379. expect(projection.getSnapshot().availability.resumeGoal).toEqual({
  5380. allowed: false,
  5381. reasonCode: "noGoalToResume",
  5382. });
  5383. });
  5384. });
  5385. // ── fork marker 与 modelChange marker ──
  5386. describe("fork / modelChange marker", () => {
  5387. it("fork:parent 时间线不显示 forkCreated(S7);child 首部 forkNotice", () => {
  5388. const parentLog = new EventLog("session-1");
  5389. basicTurnEvents(parentLog);
  5390. parentLog.push(SessionEventType.SessionForked, {
  5391. originalSessionId: "session-1",
  5392. forkedSessionId: "session-child",
  5393. targetMessageId: "msg-3",
  5394. });
  5395. const { projection: parent } = runAll(parentLog.events);
  5396. const parentSnapshot = parent.getSnapshot();
  5397. expect(() => conversationSnapshotSchema.parse(parentSnapshot)).not.toThrow();
  5398. // S7(16-plan,2026-07-08 裁决):fork 关系只在 sessions 树体现,父时间线零入侵
  5399. //(旧实现的 forkCreated 是「渲染 null」的隐形行 + nextRowId-1 近似锚点)。
  5400. expect(
  5401. parentSnapshot.rows.window.find(
  5402. (row) => row.kind === "timelineMarker" && row.marker.type === "forkCreated",
  5403. ),
  5404. ).toBeUndefined();
  5405. const childProjection = new ProductProjection("session-child", "epoch-1");
  5406. const childLog = new EventLog("session-child");
  5407. childLog.push(SessionEventType.SessionForked, {
  5408. originalSessionId: "session-1",
  5409. forkedSessionId: "session-child",
  5410. });
  5411. for (const event of childLog.events) childProjection.applyEvent(event);
  5412. expect(childProjection.getSnapshot().rows.window[0]).toMatchObject({
  5413. kind: "timelineMarker",
  5414. marker: { type: "forkNotice", parentSessionId: "session-1" },
  5415. });
  5416. });
  5417. it("modelChange(R-17 时机):marker 只在下一 turn 开始且与上一轮选型不同时产生", () => {
  5418. // 场景 1(草稿态 bug 复现,2026-07-07):turn 前任意切换选择器 → 不产 marker,
  5419. // 首轮以最终选型启动也不产(「第一次用什么模型」不构成「变化」)。
  5420. const log = new EventLog();
  5421. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5422. log.push(SessionEventType.ModelSelected, {
  5423. modelSelection: {
  5424. providerId: "anthropic",
  5425. modelId: "claude-4",
  5426. options: { reasoningLevel: "thinking" },
  5427. },
  5428. });
  5429. log.push(SessionEventType.ModelSelected, {
  5430. previousModelSelection: {
  5431. providerId: "anthropic",
  5432. modelId: "claude-4",
  5433. options: { reasoningLevel: "thinking" },
  5434. },
  5435. modelSelection: { providerId: "openai", modelId: "gpt-6" },
  5436. });
  5437. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  5438. const { projection } = runAll(log.events);
  5439. expect(projection.getSnapshot().config).toMatchObject({
  5440. provider: "openai",
  5441. model: "gpt-6",
  5442. });
  5443. expect(
  5444. projection
  5445. .getSnapshot()
  5446. .rows.window.filter(
  5447. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5448. ),
  5449. ).toHaveLength(0);
  5450. // 重复选同一配置:conflation,无 delta。
  5451. const repeat = new EventLog().push(SessionEventType.ModelSelected, {
  5452. modelSelection: { providerId: "openai", modelId: "gpt-6" },
  5453. });
  5454. expect(projection.applyEvent(repeat)).toEqual([]);
  5455. // 场景 2:turn-1 用 gpt-6,期间切换 A→B→A(净变化为零)→ turn-2 不产 marker。
  5456. projection.applyEvent(
  5457. new EventLog().push(SessionEventType.ModelSelected, {
  5458. modelSelection: { providerId: "anthropic", modelId: "claude-4" },
  5459. }),
  5460. );
  5461. projection.applyEvent(
  5462. new EventLog().push(SessionEventType.ModelSelected, {
  5463. modelSelection: { providerId: "openai", modelId: "gpt-6" },
  5464. }),
  5465. );
  5466. projection.applyEvent(
  5467. new EventLog().push(
  5468. SessionEventType.TurnStarted,
  5469. { turnNumber: 2, input: "again" },
  5470. { turnId: "turn-2" },
  5471. ),
  5472. );
  5473. expect(
  5474. projection
  5475. .getSnapshot()
  5476. .rows.window.filter(
  5477. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5478. ),
  5479. ).toHaveLength(0);
  5480. // 场景 3:切到不同选型后 turn-3 启动 → marker 落在 turnHeader 之前,
  5481. // from = 上一轮实际选型(gpt-6),to = 本轮选型(claude-4)。
  5482. projection.applyEvent(
  5483. new EventLog().push(SessionEventType.ModelSelected, {
  5484. modelSelection: { providerId: "anthropic", modelId: "claude-4" },
  5485. }),
  5486. );
  5487. projection.applyEvent(
  5488. new EventLog().push(
  5489. SessionEventType.TurnStarted,
  5490. { turnNumber: 3, input: "switch" },
  5491. { turnId: "turn-3" },
  5492. ),
  5493. );
  5494. const rows = projection.getSnapshot().rows.window;
  5495. const markerIndex = rows.findIndex(
  5496. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5497. );
  5498. expect(rows[markerIndex]).toMatchObject({
  5499. marker: {
  5500. type: "modelChange",
  5501. fromProvider: "openai",
  5502. fromModel: "gpt-6",
  5503. toProvider: "anthropic",
  5504. toModel: "claude-4",
  5505. toThought: "",
  5506. },
  5507. });
  5508. // marker 紧邻 turn-3 的 turnHeader 之前。
  5509. expect(rows[markerIndex + 1]).toMatchObject({
  5510. kind: "turnHeader",
  5511. turnId: "turn-3",
  5512. });
  5513. });
  5514. it("显式 source-less 模型边界经原子投影只在首个 turn 生成一次 marker", () => {
  5515. const log = new EventLog("child-session");
  5516. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  5517. log.push(SessionEventType.ModelSelected, {
  5518. previousModelSelection: null,
  5519. modelSelection: {
  5520. providerId: "child-provider",
  5521. modelId: "child-model",
  5522. options: { reasoningLevel: "high" },
  5523. },
  5524. });
  5525. log.push(SessionEventType.ModelSelected, {
  5526. previousModelSelection: {
  5527. providerId: "child-provider",
  5528. modelId: "child-model",
  5529. options: { reasoningLevel: "high" },
  5530. },
  5531. modelSelection: {
  5532. providerId: "child-provider",
  5533. modelId: "child-model-final",
  5534. options: { reasoningLevel: "max" },
  5535. },
  5536. });
  5537. log.push(
  5538. SessionEventType.TurnStarted,
  5539. { turnNumber: 1, input: "first child prompt" },
  5540. { turnId: "child-turn-1" },
  5541. );
  5542. log.push(
  5543. SessionEventType.TurnComplete,
  5544. {
  5545. response: "done",
  5546. tokenCount: 1,
  5547. toolCallCount: 0,
  5548. duration: 1,
  5549. resultType: "success",
  5550. },
  5551. { turnId: "child-turn-1" },
  5552. );
  5553. log.push(
  5554. SessionEventType.TurnStarted,
  5555. { turnNumber: 2, input: "second child prompt" },
  5556. { turnId: "child-turn-2" },
  5557. );
  5558. const projection = new ProductProjection("child-session", "epoch-1");
  5559. for (const event of log.events) {
  5560. expect(projection.applyEventAtomically(event, () => true)).not.toBeNull();
  5561. }
  5562. const rows = projection.getSnapshot().rows.window;
  5563. const markers = rows.filter(
  5564. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5565. );
  5566. expect(markers).toHaveLength(1);
  5567. expect(markers[0]).toMatchObject({
  5568. turnId: "child-turn-1",
  5569. marker: {
  5570. type: "modelChange",
  5571. toProvider: "child-provider",
  5572. toModel: "child-model-final",
  5573. toThought: "max",
  5574. },
  5575. });
  5576. expect(markers[0]?.kind === "timelineMarker" ? markers[0].marker : {}).not.toHaveProperty(
  5577. "fromProvider",
  5578. );
  5579. const markerIndex = rows.indexOf(markers[0]!);
  5580. expect(rows[markerIndex + 1]).toMatchObject({
  5581. kind: "turnHeader",
  5582. turnId: "child-turn-1",
  5583. });
  5584. expect(() => conversationSnapshotSchema.parse(projection.getSnapshot())).not.toThrow();
  5585. });
  5586. it("H17:切模型后 /goal 控制输入不创建工作生命周期,只有 continuation 为 running", () => {
  5587. const log = new EventLog();
  5588. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5589. log.push(SessionEventType.ModelSelected, {
  5590. modelSelection: { providerId: "zhipu", modelId: "glm-5.2-highspeed" },
  5591. });
  5592. log.push(
  5593. SessionEventType.TurnStarted,
  5594. { turnNumber: 1, input: "上一轮", messageId: "user-previous" },
  5595. { turnId: "turn-previous" },
  5596. );
  5597. log.push(
  5598. SessionEventType.TurnComplete,
  5599. { response: "done", tokenCount: 1, toolCallCount: 0, duration: 1000, resultType: "success" },
  5600. { turnId: "turn-previous" },
  5601. );
  5602. log.push(SessionEventType.ModelSelected, {
  5603. modelSelection: {
  5604. providerId: "deepseek",
  5605. modelId: "deepseek-v4-flash",
  5606. options: { reasoningLevel: "max" },
  5607. },
  5608. });
  5609. log.push(
  5610. SessionEventType.TurnStarted,
  5611. {
  5612. turnNumber: 2,
  5613. input: "/Goal 开发一个招投标管理系统",
  5614. messageId: "user-goal",
  5615. executionKind: "controlOnly",
  5616. intent: {
  5617. sourceCommandId: "command-goal",
  5618. queueItemId: "queue-goal",
  5619. clientId: "desktop",
  5620. kind: "sendGoalCommand",
  5621. text: "开发一个招投标管理系统",
  5622. admissionSeq: 1,
  5623. admittedAt: 1,
  5624. requestedDelivery: "startNow",
  5625. admittedDelivery: "startNow",
  5626. },
  5627. },
  5628. { turnId: "turn-goal-query" },
  5629. );
  5630. const projection = new ProductProjection("session-1", "epoch-1");
  5631. for (const event of log.events) projection.applyEvent(event);
  5632. expect(projection.getSnapshot().control).toMatchObject({
  5633. phase: "completedSuccess",
  5634. canStop: false,
  5635. activeWorks: [],
  5636. });
  5637. log.push(
  5638. SessionEventType.TurnComplete,
  5639. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  5640. { turnId: "turn-goal-query" },
  5641. );
  5642. projection.applyEvent(log.events.at(-1)!);
  5643. const goalHeader = projection
  5644. .getSnapshot()
  5645. .rows.window.find((row) => row.kind === "turnHeader" && row.turnId === "user-goal");
  5646. expect(goalHeader).toMatchObject({
  5647. kind: "turnHeader",
  5648. executionKind: "controlOnly",
  5649. state: "completedSuccess",
  5650. });
  5651. expect(goalHeader).not.toHaveProperty("activeMs");
  5652. expect(projection.getSnapshot().control).toMatchObject({
  5653. phase: "completedSuccess",
  5654. canStop: false,
  5655. activeWorks: [],
  5656. });
  5657. log.push(
  5658. SessionEventType.TurnStarted,
  5659. {
  5660. turnNumber: 3,
  5661. input: "继续执行目标",
  5662. messageId: "goal-continuation-1",
  5663. inputSource: "goal-continuation",
  5664. inputVisibility: "model-only",
  5665. },
  5666. { turnId: "turn-goal-continuation" },
  5667. );
  5668. projection.applyEvent(log.events.at(-1)!);
  5669. const snapshot = projection.getSnapshot();
  5670. expect(snapshot.control).toMatchObject({
  5671. phase: "running",
  5672. canStop: true,
  5673. activeWorks: [{ kind: "goalContinuation" }],
  5674. });
  5675. expect(
  5676. snapshot.rows.window.find(
  5677. (row) => row.kind === "turnHeader" && row.turnId === "goal-continuation-1",
  5678. ),
  5679. ).toMatchObject({ executionKind: "agent", state: "running" });
  5680. expect(
  5681. snapshot.rows.window.filter(
  5682. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5683. ),
  5684. ).toHaveLength(1);
  5685. });
  5686. it("modelChange:仅思考深度变化不产 marker", () => {
  5687. const log = new EventLog();
  5688. log.push(SessionEventType.ModelSelected, {
  5689. modelSelection: { providerId: "default-deepseek", modelId: "deepseek-v4-flash" },
  5690. });
  5691. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "first" }, { turnId: "turn-1" });
  5692. const { projection } = runAll(log.events);
  5693. projection.applyEvent(
  5694. new EventLog().push(SessionEventType.ModelSelected, {
  5695. modelSelection: {
  5696. providerId: "default-deepseek",
  5697. modelId: "deepseek-v4-flash",
  5698. options: { reasoningLevel: "max" },
  5699. },
  5700. }),
  5701. );
  5702. projection.applyEvent(
  5703. new EventLog().push(
  5704. SessionEventType.TurnStarted,
  5705. { turnNumber: 2, input: "same model, deeper thought" },
  5706. { turnId: "turn-2" },
  5707. ),
  5708. );
  5709. expect(projection.getSnapshot().config).toMatchObject({
  5710. provider: "default-deepseek",
  5711. model: "deepseek-v4-flash",
  5712. thought: "max",
  5713. });
  5714. expect(
  5715. projection
  5716. .getSnapshot()
  5717. .rows.window.filter(
  5718. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5719. ),
  5720. ).toHaveLength(0);
  5721. });
  5722. // ── M4:rowId → messageId 侧表(forkAssistant/editUserQuery 桥接翻译,13 §E 组前置)──
  5723. it("E:assistant 行记录 assistantMessageId,getMessageIdForRow 可翻译", () => {
  5724. const log = new EventLog();
  5725. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  5726. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  5727. log.push(
  5728. SessionEventType.ModelStreaming,
  5729. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-assist-1" },
  5730. { turnId: "turn-1" },
  5731. );
  5732. log.push(
  5733. SessionEventType.ModelStreaming,
  5734. { kind: "text_delta", delta: "hello", done: false, assistantMessageId: "msg-assist-1" },
  5735. { turnId: "turn-1" },
  5736. );
  5737. log.push(
  5738. SessionEventType.ModelStreaming,
  5739. { kind: "text_end", delta: "", done: false },
  5740. { turnId: "turn-1" },
  5741. );
  5742. const { projection } = runAll(log.events);
  5743. const assistantRow = projection
  5744. .getSnapshot()
  5745. .rows.window.find((row) => row.kind === "assistantText");
  5746. expect(assistantRow).toBeDefined();
  5747. expect(projection.getMessageIdForRow(assistantRow!.rowId)).toBe("msg-assist-1");
  5748. // 非 assistant 行 / 未知 rowId → null(桥接层据此 reject,不静默兜底 fork 错点)。
  5749. expect(projection.getMessageIdForRow(9999)).toBeNull();
  5750. const turnHeaderRow = projection
  5751. .getSnapshot()
  5752. .rows.window.find((row) => row.kind === "turnHeader");
  5753. expect(projection.getMessageIdForRow(turnHeaderRow!.rowId)).toBeNull();
  5754. });
  5755. it("E:无 assistantMessageId 的流(老 provider)→ 行存在但翻译为 null", () => {
  5756. const log = new EventLog();
  5757. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  5758. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  5759. log.push(
  5760. SessionEventType.ModelStreaming,
  5761. { kind: "text_start", delta: "", done: false },
  5762. { turnId: "turn-1" },
  5763. );
  5764. log.push(
  5765. SessionEventType.ModelStreaming,
  5766. { kind: "text_delta", delta: "hello", done: false },
  5767. { turnId: "turn-1" },
  5768. );
  5769. const { projection } = runAll(log.events);
  5770. const assistantRow = projection
  5771. .getSnapshot()
  5772. .rows.window.find((row) => row.kind === "assistantText");
  5773. expect(assistantRow).toBeDefined();
  5774. expect(projection.getMessageIdForRow(assistantRow!.rowId)).toBeNull();
  5775. });
  5776. it("P0:user messageId 缺失时不得用同 turn assistant anchor 冒充 canEdit target", () => {
  5777. const log = new EventLog();
  5778. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  5779. log.push(
  5780. SessionEventType.TurnStarted,
  5781. { turnNumber: 1, input: "缺少持久 user id" },
  5782. { turnId: "turn-1" },
  5783. );
  5784. log.push(
  5785. SessionEventType.ModelStreaming,
  5786. {
  5787. kind: "text_start",
  5788. delta: "",
  5789. done: false,
  5790. assistantMessageId: "assistant-only-anchor",
  5791. },
  5792. { turnId: "turn-1" },
  5793. );
  5794. log.push(
  5795. SessionEventType.ModelStreaming,
  5796. { kind: "text_delta", delta: "回答", done: false },
  5797. { turnId: "turn-1" },
  5798. );
  5799. log.push(
  5800. SessionEventType.TurnComplete,
  5801. { response: "回答", tokenCount: 1, toolCallCount: 0, duration: 1, resultType: "success" },
  5802. { turnId: "turn-1" },
  5803. );
  5804. const { projection } = runAll(log.events);
  5805. const userRow = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput");
  5806. expect(userRow).toBeDefined();
  5807. expect(projection.getMessageIdForRow(userRow!.rowId)).toBeNull();
  5808. // turn rewind 仍能找到 assistant anchor,但 exact user target 不存在。
  5809. expect(projection.getTurnRewindAnchor(userRow!.rowId)).toBe("assistant-only-anchor");
  5810. expect(userRow!.actions?.canEdit).not.toBe(true);
  5811. expect(projection.isLatestEditableUserRow(userRow!.rowId)).toBe(false);
  5812. });
  5813. it("P1:legacy 身份 fallback 必须由 normalizer 留下可观测诊断", () => {
  5814. const log = new EventLog();
  5815. log.push(
  5816. SessionEventType.TurnStarted,
  5817. { turnNumber: 1, input: "legacy query" },
  5818. { turnId: "turn-legacy" },
  5819. );
  5820. const { projection } = runAll(log.events);
  5821. expect(projection.getNormalizationDiagnostics()).toEqual([
  5822. {
  5823. code: "normalizer.user.missingTranscriptMessageId",
  5824. eventId: "event-1",
  5825. },
  5826. ]);
  5827. });
  5828. it("P1/P2:live 与 cold 合成事件的 command target/actions 逐实体等价", () => {
  5829. const project = (turnId: string) => {
  5830. const log = new EventLog();
  5831. log.push(
  5832. SessionEventType.TurnStarted,
  5833. { turnNumber: 1, input: "same query", messageId: "message-user-1" },
  5834. { turnId },
  5835. );
  5836. log.push(
  5837. SessionEventType.ModelStreaming,
  5838. {
  5839. kind: "text_start",
  5840. delta: "",
  5841. done: false,
  5842. assistantMessageId: "message-assistant-1",
  5843. partId: "part-1",
  5844. },
  5845. { turnId },
  5846. );
  5847. log.push(
  5848. SessionEventType.ModelStreaming,
  5849. { kind: "text_delta", delta: "same answer", done: false, partId: "part-1" },
  5850. { turnId },
  5851. );
  5852. log.push(
  5853. SessionEventType.ModelStreaming,
  5854. { kind: "text_end", delta: "", done: false, partId: "part-1" },
  5855. { turnId },
  5856. );
  5857. log.push(
  5858. SessionEventType.TurnComplete,
  5859. {
  5860. response: "same answer",
  5861. tokenCount: 1,
  5862. toolCallCount: 0,
  5863. duration: 1,
  5864. resultType: "success",
  5865. },
  5866. { turnId },
  5867. );
  5868. return runAll(log.events).projection;
  5869. };
  5870. const live = project("runtime-turn-1");
  5871. const cold = project("hydrate-turn-1");
  5872. const semanticRows = (projection: ProductProjection) =>
  5873. projection
  5874. .getSnapshot()
  5875. .rows.window.filter((row) => row.kind === "userInput" || row.kind === "assistantText")
  5876. .map((row) => ({
  5877. kind: row.kind,
  5878. text: row.text,
  5879. productTurnId: row.turnId,
  5880. actions: row.actions,
  5881. entityId: projection.getEntityIdForRow(row.rowId),
  5882. target: projection.getMessageIdForRow(row.rowId),
  5883. }));
  5884. expect(semanticRows(cold)).toEqual(semanticRows(live));
  5885. expect(semanticRows(live).map((row) => row.productTurnId)).toEqual([
  5886. "message-user-1",
  5887. "message-user-1",
  5888. ]);
  5889. expect(live.getNormalizationDiagnostics()).toEqual([]);
  5890. expect(cold.getNormalizationDiagnostics()).toEqual([]);
  5891. });
  5892. it("P2:entity resolver 只允许当前 canEdit 的真实用户实体", () => {
  5893. const log = new EventLog();
  5894. for (const turnNumber of [1, 2]) {
  5895. const turnId = `turn-${turnNumber}`;
  5896. log.push(
  5897. SessionEventType.TurnStarted,
  5898. {
  5899. turnNumber,
  5900. input: `query ${turnNumber}`,
  5901. messageId: `message-user-${turnNumber}`,
  5902. },
  5903. { turnId },
  5904. );
  5905. log.push(
  5906. SessionEventType.TurnComplete,
  5907. {
  5908. response: "",
  5909. tokenCount: 0,
  5910. toolCallCount: 0,
  5911. duration: 1,
  5912. resultType: "success",
  5913. },
  5914. { turnId },
  5915. );
  5916. }
  5917. const { projection } = runAll(log.events);
  5918. const userRows = projection.getSnapshot().rows.window.filter((row) => row.kind === "userInput");
  5919. expect(userRows.map((row) => row.actions?.canEdit === true)).toEqual([false, true]);
  5920. expect(projection.resolveEditTargetByEntityId("message-user-1")).toBeNull();
  5921. expect(projection.resolveEditTargetByEntityId("message-user-2")).toMatchObject({
  5922. entityId: "message-user-2",
  5923. productTurnId: "message-user-2",
  5924. transcriptMessageId: "message-user-2",
  5925. });
  5926. });
  5927. it("Task3:row.actions 与 target resolver 同源并声明 edit disposition", () => {
  5928. const log = new EventLog();
  5929. log.push(
  5930. SessionEventType.TurnStarted,
  5931. { turnNumber: 1, input: "query", messageId: "message-user-1" },
  5932. { turnId: "turn-1" },
  5933. );
  5934. log.push(
  5935. SessionEventType.ModelStreaming,
  5936. {
  5937. kind: "text_start",
  5938. delta: "",
  5939. done: false,
  5940. assistantMessageId: "message-assistant-1",
  5941. },
  5942. { turnId: "turn-1" },
  5943. );
  5944. log.push(
  5945. SessionEventType.ModelStreaming,
  5946. { kind: "text_end", delta: "", done: false },
  5947. { turnId: "turn-1" },
  5948. );
  5949. log.push(
  5950. SessionEventType.TurnComplete,
  5951. {
  5952. response: "",
  5953. tokenCount: 0,
  5954. toolCallCount: 0,
  5955. duration: 1,
  5956. resultType: "success",
  5957. },
  5958. { turnId: "turn-1" },
  5959. );
  5960. const { projection } = runAll(log.events);
  5961. const userRow = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput")!;
  5962. const assistantRow = projection
  5963. .getSnapshot()
  5964. .rows.window.find((row) => row.kind === "assistantText")!;
  5965. const target = { rowId: userRow.rowId, entityId: "message-user-1" };
  5966. expect(userRow.actions).toMatchObject({
  5967. canEdit: true,
  5968. editDisposition: "rewind",
  5969. });
  5970. expect(assistantRow.actions).toMatchObject({
  5971. canFork: true,
  5972. canRetry: true,
  5973. });
  5974. expect(projection.resolveRowActionTarget(target, "editUserQuery")).toMatchObject({
  5975. ok: true,
  5976. action: "editUserQuery",
  5977. editTarget: { transcriptMessageId: "message-user-1" },
  5978. });
  5979. expect(
  5980. projection.resolveRowActionTarget(
  5981. { rowId: userRow.rowId, entityId: "reused-for-another-entity" },
  5982. "editUserQuery",
  5983. ),
  5984. ).toEqual({ ok: false, status: "stale", reasonCode: "proto.staleTarget" });
  5985. expect(projection.resolveRowActionTarget(target, "retryTurn")).toEqual({
  5986. ok: false,
  5987. status: "rejected",
  5988. reasonCode: "guard.actionUnavailable",
  5989. });
  5990. projection.applyEvent(
  5991. new EventLog().push(SessionEventType.CompactStarted, {
  5992. operationId: "compact-1",
  5993. messageId: "compact-message",
  5994. status: "started",
  5995. trigger: "manual",
  5996. display: "separator",
  5997. }),
  5998. );
  5999. const lockedRow = projection
  6000. .getSnapshot()
  6001. .rows.window.find((row) => row.rowId === userRow.rowId)!;
  6002. const lockedAssistantRow = projection
  6003. .getSnapshot()
  6004. .rows.window.find((row) => row.rowId === assistantRow.rowId)!;
  6005. expect(lockedRow.actions?.canEdit).toBeUndefined();
  6006. expect(lockedAssistantRow.actions?.canFork).toBeUndefined();
  6007. expect(lockedAssistantRow.actions?.canRetry).toBeUndefined();
  6008. expect(projection.getSnapshot().availability.sendQueuedNow).toEqual({
  6009. allowed: false,
  6010. reasonCode: "compactOperationLock",
  6011. });
  6012. projection.applyEvent(
  6013. new EventLog().push(SessionEventType.CompactCompleted, {
  6014. operationId: "compact-1",
  6015. messageId: "compact-message",
  6016. status: "completed",
  6017. trigger: "manual",
  6018. display: "separator",
  6019. tailStartMessageId: "message-user-1",
  6020. }),
  6021. );
  6022. const compactedRow = projection
  6023. .getSnapshot()
  6024. .rows.window.find((row) => row.rowId === userRow.rowId)!;
  6025. expect(compactedRow.actions).toMatchObject({
  6026. canEdit: true,
  6027. editDisposition: "rewind",
  6028. });
  6029. expect(projection.resolveRowActionTarget(target, "editUserQuery")).toMatchObject({
  6030. ok: true,
  6031. action: "editUserQuery",
  6032. editTarget: { coveredByStableCompact: true },
  6033. });
  6034. });
  6035. it("root review:primary/goal continuation/verifier running 时 retry 与 file rewind 同源禁用", () => {
  6036. const completedProjection = () => {
  6037. const log = new EventLog();
  6038. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6039. log.push(
  6040. SessionEventType.TurnStarted,
  6041. { turnNumber: 1, input: "改文件", messageId: "message-user-base" },
  6042. { turnId: "turn-base" },
  6043. );
  6044. log.push(
  6045. SessionEventType.ModelStreaming,
  6046. {
  6047. kind: "text_start",
  6048. delta: "",
  6049. done: false,
  6050. assistantMessageId: "message-assistant-base",
  6051. },
  6052. { turnId: "turn-base" },
  6053. );
  6054. log.push(
  6055. SessionEventType.ModelStreaming,
  6056. { kind: "text_delta", delta: "done", done: false },
  6057. { turnId: "turn-base" },
  6058. );
  6059. log.push(
  6060. SessionEventType.ModelComplete,
  6061. {
  6062. content: "done",
  6063. stopReason: "stop",
  6064. querySource: "main_turn",
  6065. contextWindow: 200_000,
  6066. usage: { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 },
  6067. fileChanges: {
  6068. files: 1,
  6069. additions: 2,
  6070. deletions: 1,
  6071. items: [{ path: "/work/a.ts", additions: 2, deletions: 1, writeCount: 1 }],
  6072. },
  6073. },
  6074. { turnId: "turn-base" },
  6075. );
  6076. log.push(
  6077. SessionEventType.TurnComplete,
  6078. { response: "done", tokenCount: 2, toolCallCount: 0, duration: 1, resultType: "success" },
  6079. { turnId: "turn-base" },
  6080. );
  6081. return runAll(log.events).projection;
  6082. };
  6083. const contexts = [
  6084. {
  6085. kind: "primaryTurn",
  6086. event: () =>
  6087. new EventLog().push(
  6088. SessionEventType.TurnStarted,
  6089. { turnNumber: 2, input: "next", messageId: "message-user-next" },
  6090. { turnId: "turn-next" },
  6091. ),
  6092. },
  6093. {
  6094. kind: "goalContinuation",
  6095. event: () =>
  6096. new EventLog().push(
  6097. SessionEventType.TurnStarted,
  6098. {
  6099. turnNumber: 2,
  6100. input: "continue",
  6101. inputSource: "goal-continuation",
  6102. inputVisibility: "model-only",
  6103. },
  6104. { turnId: "turn-goal-continuation" },
  6105. ),
  6106. },
  6107. {
  6108. kind: "goalVerifier",
  6109. event: () =>
  6110. new EventLog().push(SessionEventType.TargetCompletionVerification, {
  6111. targetId: "target-1",
  6112. status: "started",
  6113. verificationId: "verify-1",
  6114. goalIteration: 1,
  6115. }),
  6116. },
  6117. ] as const;
  6118. for (const context of contexts) {
  6119. const projection = completedProjection();
  6120. const base = projection.getSnapshot();
  6121. const header = base.rows.window.find((row) => row.kind === "turnHeader")!;
  6122. const assistant = base.rows.window.find((row) => row.kind === "assistantText")!;
  6123. const headerTarget = { rowId: header.rowId, entityId: header.entityId! };
  6124. const assistantTarget = { rowId: assistant.rowId, entityId: assistant.entityId! };
  6125. projection.applyEvent(context.event());
  6126. const running = projection.getSnapshot();
  6127. const lockedHeader = running.rows.window.find((row) => row.rowId === header.rowId)!;
  6128. const lockedAssistant = running.rows.window.find((row) => row.rowId === assistant.rowId)!;
  6129. expect(running.control.activeWorks.some((work) => work.kind === context.kind)).toBe(true);
  6130. expect(lockedHeader.actions?.canRewindFiles, context.kind).toBeUndefined();
  6131. expect(lockedAssistant.actions?.canRetry, context.kind).toBeUndefined();
  6132. expect(lockedAssistant.actions?.canFork, context.kind).toBe(true);
  6133. expect(projection.resolveRowActionTarget(headerTarget, "applyFileRewind")).toMatchObject({
  6134. ok: false,
  6135. reasonCode: "guard.actionUnavailable",
  6136. });
  6137. expect(projection.resolveRowActionTarget(assistantTarget, "retryTurn")).toMatchObject({
  6138. ok: false,
  6139. reasonCode: "guard.actionUnavailable",
  6140. });
  6141. expect(projection.resolveRowActionTarget(assistantTarget, "forkAssistant")).toMatchObject({
  6142. ok: true,
  6143. });
  6144. }
  6145. });
  6146. // ── M4:queue 单项编辑(同 id 重入 TurnSteerQueued → 原地更新保位)──
  6147. it("A/B:editQueueItem —— 同 queueItemId 重入更新文本且保位", () => {
  6148. const log = new EventLog();
  6149. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6150. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6151. // 入队两条
  6152. log.push(
  6153. SessionEventType.TurnSteerQueued,
  6154. {
  6155. pendingInputId: "q1",
  6156. input: "第一条",
  6157. inputPreview: "第一条",
  6158. inputSize: 9,
  6159. queueLength: 1,
  6160. targetTurnId: "t1",
  6161. intent: {
  6162. botGroupSource: {
  6163. provider: "feishu",
  6164. botId: "bot",
  6165. chatId: "group",
  6166. senderId: "member",
  6167. senderName: "Member",
  6168. messageId: "message",
  6169. },
  6170. sourceCommandId: "command-q1",
  6171. queueItemId: "q1",
  6172. clientId: "mobile-client",
  6173. kind: "sendText",
  6174. admissionSeq: 1,
  6175. admittedAt: 10,
  6176. requestedDelivery: "guide",
  6177. admittedDelivery: "queue",
  6178. fallbackReasonCode: "guide.attachmentsUnsupported",
  6179. attachmentRefs: [
  6180. { ref: "artifact://q1", fileName: "q1.txt", mime: "text/plain", bytes: 2 },
  6181. ],
  6182. },
  6183. },
  6184. { turnId: "t1" },
  6185. );
  6186. log.push(
  6187. SessionEventType.TurnSteerQueued,
  6188. {
  6189. pendingInputId: "q2",
  6190. input: "第二条",
  6191. inputPreview: "第二条",
  6192. inputSize: 9,
  6193. queueLength: 2,
  6194. targetTurnId: "t1",
  6195. },
  6196. { turnId: "t1" },
  6197. );
  6198. // 编辑第一条(同 id 重入)
  6199. log.push(
  6200. SessionEventType.TurnSteerQueued,
  6201. {
  6202. pendingInputId: "q1",
  6203. input: "第一条改",
  6204. inputPreview: "第一条改",
  6205. inputSize: 12,
  6206. queueLength: 2,
  6207. targetTurnId: "t1",
  6208. },
  6209. { turnId: "t1" },
  6210. );
  6211. const { projection } = runAll(log.events);
  6212. const items = projection.getSnapshot().queue.items;
  6213. // 仍 2 条,q1 在原位(index 0)且文本已更新。
  6214. expect(items.map((i) => i.queueItemId)).toEqual(["q1", "q2"]);
  6215. expect(items[0]).toMatchObject({
  6216. text: "第一条改",
  6217. botGroupSource: { senderId: "member", chatId: "group" },
  6218. sourceCommandId: "command-q1",
  6219. clientId: "mobile-client",
  6220. attachments: [{ ref: "artifact://q1" }],
  6221. delivery: {
  6222. requested: "guide",
  6223. admitted: "queue",
  6224. fallbackReasonCode: "guide.attachmentsUnsupported",
  6225. },
  6226. order: { admissionSeq: 1, queuePosition: 0 },
  6227. steer: { state: "fellBack", reasonCode: "guide.attachmentsUnsupported" },
  6228. });
  6229. expect(items[1]!.text).toBe("第二条");
  6230. });
  6231. // ── M4:queue 重排(TurnSteerReordered → 按新序重排 queue rows)──
  6232. it("A/B:reorderQueueItem —— 按 orderedPendingInputIds 重排 queue", () => {
  6233. const log = new EventLog();
  6234. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6235. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6236. for (const [id, text, len] of [
  6237. ["q1", "一", 3],
  6238. ["q2", "二", 3],
  6239. ["q3", "三", 3],
  6240. ] as const) {
  6241. log.push(
  6242. SessionEventType.TurnSteerQueued,
  6243. {
  6244. pendingInputId: id,
  6245. input: text,
  6246. inputPreview: text,
  6247. inputSize: len,
  6248. queueLength: 3,
  6249. targetTurnId: "t1",
  6250. },
  6251. { turnId: "t1" },
  6252. );
  6253. }
  6254. // 把 q3 移到 q1 之前:新序 q3, q1, q2。
  6255. log.push(
  6256. SessionEventType.TurnSteerReordered,
  6257. { orderedPendingInputIds: ["q3", "q1", "q2"], targetTurnId: "t1" },
  6258. { turnId: "t1" },
  6259. );
  6260. const { projection } = runAll(log.events);
  6261. expect(projection.getSnapshot().queue.items.map((i) => i.queueItemId)).toEqual([
  6262. "q3",
  6263. "q1",
  6264. "q2",
  6265. ]);
  6266. expect(projection.getSnapshot().queue.items.map((i) => i.order.queuePosition)).toEqual([
  6267. 0, 1, 2,
  6268. ]);
  6269. });
  6270. it("sendQueuedNow dispatch:reserved/promoting 只更新目标项且保留完整 intent", () => {
  6271. const log = new EventLog();
  6272. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6273. log.push(
  6274. SessionEventType.TurnSteerQueued,
  6275. {
  6276. pendingInputId: "q1",
  6277. input: "带附件输入",
  6278. inputPreview: "带附件输入",
  6279. inputSize: 18,
  6280. queueLength: 1,
  6281. targetTurnId: "t1",
  6282. intent: {
  6283. sourceCommandId: "source-q1",
  6284. queueItemId: "q1",
  6285. clientId: "mobile-client",
  6286. kind: "sendText",
  6287. admissionSeq: 1,
  6288. admittedAt: 10,
  6289. requestedDelivery: "queue",
  6290. admittedDelivery: "queue",
  6291. attachmentRefs: [
  6292. { ref: "artifact://q1", fileName: "q1.txt", mime: "text/plain", bytes: 2 },
  6293. ],
  6294. },
  6295. },
  6296. { turnId: "t1" },
  6297. );
  6298. log.push(SessionEventType.TurnSteerDispatchChanged, {
  6299. pendingInputId: "q1",
  6300. reservationId: "send-now-1",
  6301. state: "reserved",
  6302. targetTurnId: "t1",
  6303. });
  6304. log.push(SessionEventType.TurnSteerDispatchChanged, {
  6305. pendingInputId: "q1",
  6306. reservationId: "send-now-1",
  6307. state: "promoting",
  6308. targetTurnId: "t1",
  6309. });
  6310. const { projection } = runAll(log.events);
  6311. expect(projection.getSnapshot().queue.items[0]).toMatchObject({
  6312. sourceCommandId: "source-q1",
  6313. clientId: "mobile-client",
  6314. attachments: [{ ref: "artifact://q1" }],
  6315. dispatch: { state: "promoting", reservationId: "send-now-1" },
  6316. });
  6317. });
  6318. it("sendQueuedNow commit:SessionInputPromoted 是 queue 移除的 durable 提交信号", () => {
  6319. const log = new EventLog();
  6320. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6321. log.push(
  6322. SessionEventType.TurnSteerQueued,
  6323. {
  6324. pendingInputId: "q1",
  6325. input: "已持久化输入",
  6326. inputPreview: "已持久化输入",
  6327. inputSize: 21,
  6328. queueLength: 1,
  6329. targetTurnId: "t1",
  6330. intent: {
  6331. sourceCommandId: "source-q1",
  6332. queueItemId: "q1",
  6333. clientId: "desktop-client",
  6334. kind: "sendText",
  6335. admissionSeq: 1,
  6336. admittedAt: 10,
  6337. requestedDelivery: "queue",
  6338. admittedDelivery: "queue",
  6339. attachmentRefs: [],
  6340. },
  6341. },
  6342. { turnId: "t1" },
  6343. );
  6344. log.push(SessionEventType.TurnSteerDispatchChanged, {
  6345. pendingInputId: "q1",
  6346. reservationId: "send-now-1",
  6347. state: "promoting",
  6348. targetTurnId: "t1",
  6349. });
  6350. // startPromptTurn 已把 user message + session_input promotion 同事务提交。
  6351. // 即使后续 TurnSteerDiscarded(promoted) 丢失,投影也不能留下幽灵 queue item。
  6352. log.push(SessionEventType.SessionInputPromoted, {
  6353. pendingInputId: "q1",
  6354. sourceCommandId: "source-q1",
  6355. messageId: "message-q1",
  6356. });
  6357. const { projection } = runAll(log.events);
  6358. expect(projection.getSnapshot().queue.items).toEqual([]);
  6359. });
  6360. // ── M4:setAutoDrain(QueueAutoDrainChanged → queue.autoDrain + held 派生)──
  6361. it("A/B:setAutoDrain(false) → queue.autoDrain=false,held 时 completed+queue>0 走 choice", () => {
  6362. const log = new EventLog();
  6363. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6364. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6365. log.push(
  6366. SessionEventType.TurnSteerQueued,
  6367. {
  6368. pendingInputId: "q1",
  6369. input: "排队项",
  6370. inputPreview: "排队项",
  6371. inputSize: 9,
  6372. queueLength: 1,
  6373. targetTurnId: "t1",
  6374. },
  6375. { turnId: "t1" },
  6376. );
  6377. // 关闭 autoDrain(保留队列)
  6378. log.push(SessionEventType.QueueAutoDrainChanged, { autoDrain: false });
  6379. // turn 结束 → completed + queue>0 + autoDrain=false → 输入路由为 choice
  6380. log.push(
  6381. SessionEventType.TurnComplete,
  6382. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  6383. { turnId: "t1" },
  6384. );
  6385. const { projection } = runAll(log.events);
  6386. const snapshot = projection.getSnapshot();
  6387. expect(snapshot.queue.autoDrain).toBe(false);
  6388. expect(snapshot.queue.pauseReason).toBe("manual");
  6389. expect(snapshot.inputRouting.mode).toBe("choice");
  6390. expect(snapshot.inputRouting.reasonCode).toBe("heldQueueInputRequiresChoice");
  6391. });
  6392. it("B:Stop 保留队列时记录 stopped 原因;恢复后清除暂停原因", () => {
  6393. const log = new EventLog();
  6394. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6395. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6396. log.push(
  6397. SessionEventType.TurnSteerQueued,
  6398. {
  6399. pendingInputId: "q1",
  6400. input: "排队项",
  6401. inputPreview: "排队项",
  6402. inputSize: 9,
  6403. queueLength: 1,
  6404. targetTurnId: "t1",
  6405. },
  6406. { turnId: "t1" },
  6407. );
  6408. log.push(
  6409. SessionEventType.TurnComplete,
  6410. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "cancelled" },
  6411. { turnId: "t1" },
  6412. );
  6413. log.push(SessionEventType.QueueAutoDrainChanged, { autoDrain: true });
  6414. const projection = new ProductProjection("s1", "epoch-1");
  6415. for (const event of log.events.slice(0, -1)) projection.applyEvent(event);
  6416. expect(projection.getSnapshot().queue).toMatchObject({
  6417. autoDrain: false,
  6418. pauseReason: "stopped",
  6419. });
  6420. projection.applyEvent(log.events.at(-1)!);
  6421. expect(projection.getSnapshot().queue.autoDrain).toBe(true);
  6422. expect(projection.getSnapshot().queue.pauseReason).toBeUndefined();
  6423. });
  6424. it("M07a:sendQueuedNow 内部抢占不把 future queue 投影为 stopped", () => {
  6425. const log = new EventLog();
  6426. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6427. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6428. log.push(
  6429. SessionEventType.TurnSteerQueued,
  6430. {
  6431. pendingInputId: "q1",
  6432. input: "立即发送",
  6433. inputPreview: "立即发送",
  6434. inputSize: 12,
  6435. queueLength: 1,
  6436. targetTurnId: "t1",
  6437. },
  6438. { turnId: "t1" },
  6439. );
  6440. log.push(
  6441. SessionEventType.TurnComplete,
  6442. {
  6443. response: "",
  6444. tokenCount: 0,
  6445. toolCallCount: 0,
  6446. duration: 0,
  6447. resultType: "cancelled",
  6448. preserveQueueAutoDrainOnCancel: true,
  6449. },
  6450. { turnId: "t1" },
  6451. );
  6452. const { projection } = runAll(log.events);
  6453. const snapshot = projection.getSnapshot();
  6454. expect(snapshot.control.phase).toBe("completedInterrupted");
  6455. expect(snapshot.queue).toMatchObject({
  6456. autoDrain: true,
  6457. items: [expect.objectContaining({ queueItemId: "q1" })],
  6458. });
  6459. expect(snapshot.queue.pauseReason).toBeUndefined();
  6460. expect(snapshot.inputRouting.mode).toBe("startNow");
  6461. });
  6462. it("A/B:setAutoDrain 幂等 —— 同值不产 delta", () => {
  6463. const log = new EventLog();
  6464. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6465. // 初始 autoDrain=true,再置 true 应无变化。
  6466. log.push(SessionEventType.QueueAutoDrainChanged, { autoDrain: true });
  6467. const { projection } = runAll(log.events);
  6468. expect(projection.getSnapshot().queue.autoDrain).toBe(true);
  6469. });
  6470. // ── M4:setFollowupMode(FollowupModeChanged → running 时 enqueue vs guide)──
  6471. it("A/B:setFollowupMode(guide) → running 时输入路由为 guide", () => {
  6472. const log = new EventLog();
  6473. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6474. log.push(SessionEventType.FollowupModeChanged, { mode: "guide" });
  6475. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6476. const { projection } = runAll(log.events);
  6477. const snapshot = projection.getSnapshot();
  6478. expect(snapshot.config.followupMode).toBe("guide");
  6479. expect(snapshot.inputRouting.mode).toBe("guide");
  6480. });
  6481. it("A/B:followupMode 默认 queue —— running 时输入入队", () => {
  6482. const log = new EventLog();
  6483. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6484. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6485. const { projection } = runAll(log.events);
  6486. const snapshot = projection.getSnapshot();
  6487. expect(snapshot.config.followupMode).toBe("queue");
  6488. expect(snapshot.inputRouting.mode).toBe("enqueue");
  6489. });
  6490. // ── M5:switchCollaborationMode(SessionModeChanged → config.mode)──
  6491. it("A/B:SessionModeChanged —— config.mode 更新且 revision 前进;同值不动", () => {
  6492. const log = new EventLog();
  6493. log.push(SessionEventType.SessionCreated, { mode: "build", contextWindow: 200_000 });
  6494. log.push(SessionEventType.SessionModeChanged, {
  6495. mode: "plan",
  6496. previousMode: "build",
  6497. source: "command",
  6498. });
  6499. const { projection } = runAll(log.events);
  6500. const snapshot = projection.getSnapshot();
  6501. expect(snapshot.config.mode).toBe("plan");
  6502. const revisionAfterSwitch = snapshot.revision;
  6503. // 同值再切:无 delta,revision 不前进。
  6504. log.push(SessionEventType.SessionModeChanged, {
  6505. mode: "plan",
  6506. previousMode: "plan",
  6507. source: "command",
  6508. });
  6509. const { projection: projection2 } = runAll(log.events);
  6510. expect(projection2.getSnapshot().config.mode).toBe("plan");
  6511. expect(projection2.getSnapshot().revision).toBe(revisionAfterSwitch);
  6512. });
  6513. it("A/B:config.mode 初值 = build(draft 期无 SessionModeChanged 时的回落)", () => {
  6514. const log = new EventLog();
  6515. log.push(SessionEventType.SessionCreated, { mode: "build", contextWindow: 200_000 });
  6516. const { projection } = runAll(log.events);
  6517. expect(projection.getSnapshot().config.mode).toBe("build");
  6518. });
  6519. // ── M4:renameSession / 自动标题(SessionTitleUpdated → meta.title)──
  6520. it("A/B:SessionTitleUpdated —— generated 更新,custom 覆盖且 custom 后不被 generated 回退", () => {
  6521. const log = new EventLog();
  6522. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6523. // 初始 default
  6524. expect(runAll(log.events).projection.getSnapshot().meta.titleSource).toBe("default");
  6525. // 自动生成标题
  6526. log.push(SessionEventType.SessionTitleUpdated, {
  6527. previousTitle: "",
  6528. source: "generated",
  6529. title: "自动标题",
  6530. });
  6531. // 用户重命名(custom)
  6532. log.push(SessionEventType.SessionTitleUpdated, {
  6533. previousTitle: "自动标题",
  6534. source: "custom",
  6535. title: "我的会话",
  6536. });
  6537. // custom 后再来一次 generated —— 应被忽略(custom 粘性)
  6538. log.push(SessionEventType.SessionTitleUpdated, {
  6539. previousTitle: "我的会话",
  6540. source: "generated",
  6541. title: "又一个自动标题",
  6542. });
  6543. const meta = runAll(log.events).projection.getSnapshot().meta;
  6544. expect(meta.title).toBe("我的会话");
  6545. expect(meta.titleSource).toBe("custom");
  6546. });
  6547. it("A/B:SessionTitleUpdated —— first_input 归一为 generated", () => {
  6548. const log = new EventLog();
  6549. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6550. log.push(SessionEventType.SessionTitleUpdated, {
  6551. previousTitle: "",
  6552. source: "first_input",
  6553. title: "首条输入标题",
  6554. });
  6555. const meta = runAll(log.events).projection.getSnapshot().meta;
  6556. expect(meta.title).toBe("首条输入标题");
  6557. expect(meta.titleSource).toBe("generated");
  6558. });
  6559. // ── M4:switchModelConfig(ModelSelected → config 更新 + 中途切换 modelChange marker)──
  6560. it("A/B:ModelSelected 首次 → config 更新,无 marker(首次选型不算切换)", () => {
  6561. const log = new EventLog();
  6562. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6563. log.push(SessionEventType.ModelSelected, {
  6564. modelSelection: { providerId: "e2e-deepseek", modelId: "deepseek-v4-flash" },
  6565. supportedThoughtLevels: ["max", "high", "nothink"],
  6566. });
  6567. const { projection } = runAll(log.events);
  6568. const snapshot = projection.getSnapshot();
  6569. expect(snapshot.config.provider).toBe("e2e-deepseek");
  6570. expect(snapshot.config.model).toBe("deepseek-v4-flash");
  6571. expect(snapshot.config.thoughtLevels).toEqual(["max", "high", "nothink"]);
  6572. // 首次选型不产 modelChange marker。
  6573. expect(
  6574. snapshot.rows.window.some(
  6575. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  6576. ),
  6577. ).toBe(false);
  6578. });
  6579. it("ModelSelected 分离稀疏 Session Selection 与 effective reasoning 展示事实", () => {
  6580. const log = new EventLog();
  6581. log.push(SessionEventType.ModelSelected, {
  6582. modelSelection: { providerId: "provider-a", modelId: "model-a" },
  6583. effectiveReasoningLevel: "high",
  6584. supportedThoughtLevels: ["low", "high"],
  6585. });
  6586. const snapshot = runAll(log.events).projection.getSnapshot();
  6587. expect(snapshot.config.modelSelection).toEqual({
  6588. providerId: "provider-a",
  6589. modelId: "model-a",
  6590. });
  6591. expect(snapshot.config.thought).toBe("high");
  6592. });
  6593. it("A/B:ModelSelected 中途切换 → config 更新;marker 归 turn 开始(R-17 时机)", () => {
  6594. const log = new EventLog();
  6595. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6596. log.push(SessionEventType.ModelSelected, {
  6597. modelSelection: { providerId: "e2e-deepseek", modelId: "deepseek-v4-flash" },
  6598. supportedThoughtLevels: ["max", "high", "nothink"],
  6599. });
  6600. log.push(SessionEventType.ModelSelected, {
  6601. modelSelection: {
  6602. providerId: "e2e-deepseek",
  6603. modelId: "deepseek-v4-pro",
  6604. options: { reasoningLevel: "max" },
  6605. },
  6606. supportedThoughtLevels: ["max", "nothink"],
  6607. });
  6608. const { projection } = runAll(log.events);
  6609. const snapshot = projection.getSnapshot();
  6610. expect(snapshot.config.model).toBe("deepseek-v4-pro");
  6611. expect(snapshot.config.thought).toBe("max");
  6612. expect(snapshot.config.thoughtLevels).toEqual(["max", "nothink"]);
  6613. // R-17 时机修复(2026-07-07):切换动作本身不落 marker——尚未有 turn 使用过
  6614. // 任何模型(草稿态截图 bug:首条消息上方挂 [modelChange])。
  6615. expect(
  6616. snapshot.rows.window.some(
  6617. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  6618. ),
  6619. ).toBe(false);
  6620. });
  6621. it("I56:registry fallback 投影稳定事件与起止模型,显式切换不伪造来源", () => {
  6622. const log = new EventLog();
  6623. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6624. log.push(SessionEventType.ModelSelected, {
  6625. modelSelection: { providerId: "provider-a", modelId: "model-a" },
  6626. });
  6627. const fallbackEvent = log.push(SessionEventType.ModelSelected, {
  6628. modelSelection: {
  6629. providerId: "provider-b",
  6630. modelId: "model-b",
  6631. options: { reasoningLevel: "deep" },
  6632. },
  6633. previousModelSelection: { providerId: "provider-a", modelId: "model-a" },
  6634. origin: "registryFallback",
  6635. });
  6636. const { projection } = runAll(log.events);
  6637. expect(projection.getSnapshot().modelTransition).toEqual({
  6638. eventId: fallbackEvent.id,
  6639. origin: "registryFallback",
  6640. from: { provider: "provider-a", model: "model-a" },
  6641. to: { provider: "provider-b", model: "model-b" },
  6642. });
  6643. projection.applyEvent(
  6644. log.push(SessionEventType.ModelSelected, {
  6645. modelSelection: { providerId: "provider-c", modelId: "model-c" },
  6646. previousModelSelection: {
  6647. providerId: "provider-b",
  6648. modelId: "model-b",
  6649. options: { reasoningLevel: "deep" },
  6650. },
  6651. }),
  6652. );
  6653. expect(projection.getSnapshot().modelTransition?.eventId).toBe(fallbackEvent.id);
  6654. });
  6655. it("A/B:历史会话切换模型后立即刷新 context window 分母并保留已用量", () => {
  6656. const log = new EventLog();
  6657. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6658. log.push(
  6659. SessionEventType.TurnStarted,
  6660. { turnNumber: 1, input: "history" },
  6661. { turnId: "turn-1" },
  6662. );
  6663. log.push(
  6664. SessionEventType.ModelComplete,
  6665. {
  6666. content: "done",
  6667. stopReason: "end_turn",
  6668. querySource: "main_turn",
  6669. contextWindow: 200_000,
  6670. usage: { inputTokens: 120, outputTokens: 30 },
  6671. },
  6672. { turnId: "turn-1" },
  6673. );
  6674. const { projection } = runAll(log.events);
  6675. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6676. usedTokens: 150,
  6677. maxTokens: 200_000,
  6678. });
  6679. projection.applyEvent(
  6680. log.push(SessionEventType.ModelSelected, {
  6681. modelSelection: {
  6682. providerId: "deepseek",
  6683. modelId: "deepseek-v4-flash",
  6684. options: { reasoningLevel: "max" },
  6685. },
  6686. supportedThoughtLevels: ["max", "high", "nothink"],
  6687. }),
  6688. );
  6689. // 旧持久化事件没有 contextWindow,重放时保持既有分母,不能清零。
  6690. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6691. usedTokens: 150,
  6692. maxTokens: 200_000,
  6693. });
  6694. projection.applyEvent(
  6695. log.push(SessionEventType.ModelSelected, {
  6696. modelSelection: {
  6697. providerId: "deepseek",
  6698. modelId: "deepseek-v4-flash",
  6699. options: { reasoningLevel: "max" },
  6700. },
  6701. contextWindow: 1_000_000,
  6702. supportedThoughtLevels: ["max", "high", "nothink"],
  6703. }),
  6704. );
  6705. // 修复目标:模型切换事件本身就是 runtime 新能力的权威提交点;不等下一轮发送完成。
  6706. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6707. usedTokens: 150,
  6708. maxTokens: 1_000_000,
  6709. });
  6710. projection.applyEvent(
  6711. log.push(
  6712. SessionEventType.ModelComplete,
  6713. {
  6714. content: "next",
  6715. stopReason: "end_turn",
  6716. querySource: "main_turn",
  6717. usage: { inputTokens: 160, outputTokens: 40 },
  6718. },
  6719. { turnId: "turn-2" },
  6720. ),
  6721. );
  6722. // 后续旧 adapter 未携带 contextWindow 时,也必须回退到刚切换后的新窗口。
  6723. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6724. usedTokens: 200,
  6725. maxTokens: 1_000_000,
  6726. });
  6727. });
  6728. it("A/B:清除 context window 后持续隐藏分母并在容量恢复时保留最新已用量", () => {
  6729. const log = new EventLog();
  6730. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6731. log.push(
  6732. SessionEventType.ModelComplete,
  6733. {
  6734. content: "before clear",
  6735. stopReason: "end_turn",
  6736. querySource: "main_turn",
  6737. contextWindow: 200_000,
  6738. usage: { inputTokens: 120, outputTokens: 30 },
  6739. },
  6740. { turnId: "turn-1" },
  6741. );
  6742. const { projection } = runAll(log.events);
  6743. projection.applyEvent(
  6744. log.push(SessionEventType.ModelSelected, {
  6745. modelSelection: { providerId: "custom", modelId: "unknown-context-model" },
  6746. contextWindow: null,
  6747. }),
  6748. );
  6749. expect(projection.getSnapshot().usage.contextWindow).toBeNull();
  6750. projection.applyEvent(
  6751. log.push(
  6752. SessionEventType.ModelComplete,
  6753. {
  6754. content: "while unknown",
  6755. stopReason: "end_turn",
  6756. querySource: "main_turn",
  6757. usage: { inputTokens: 160, outputTokens: 40 },
  6758. },
  6759. { turnId: "turn-2" },
  6760. ),
  6761. );
  6762. expect(projection.getSnapshot().usage.contextWindow).toBeNull();
  6763. expect(projection.getSnapshot().usage.cumulative).toMatchObject({
  6764. inputTokens: 280,
  6765. outputTokens: 70,
  6766. });
  6767. projection.applyEvent(
  6768. log.push(SessionEventType.ModelSelected, {
  6769. modelSelection: { providerId: "custom", modelId: "unknown-context-model" },
  6770. contextWindow: 1_000_000,
  6771. }),
  6772. );
  6773. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6774. usedTokens: 200,
  6775. maxTokens: 1_000_000,
  6776. });
  6777. });
  6778. it("A/B:显式清除窗口后 hydration seed 只恢复用量而不覆盖容量", () => {
  6779. const log = new EventLog();
  6780. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6781. log.push(SessionEventType.ModelSelected, {
  6782. modelSelection: { providerId: "custom", modelId: "unknown-context-model" },
  6783. contextWindow: null,
  6784. });
  6785. const { projection } = runAll(log.events);
  6786. projection.seedUsage({
  6787. contextWindow: {
  6788. usedTokens: 999,
  6789. maxTokens: 200_000,
  6790. autoCompactThresholdTokens: null,
  6791. },
  6792. cumulative: {
  6793. inputTokens: 700,
  6794. outputTokens: 50,
  6795. cacheReadTokens: 20,
  6796. cacheWriteTokens: 10,
  6797. },
  6798. });
  6799. expect(projection.getSnapshot().usage.contextWindow).toBeNull();
  6800. expect(projection.getSnapshot().usage.cumulative).toEqual({
  6801. inputTokens: 700,
  6802. outputTokens: 50,
  6803. cacheReadTokens: 20,
  6804. cacheWriteTokens: 10,
  6805. });
  6806. projection.applyEvent(
  6807. log.push(SessionEventType.ModelSelected, {
  6808. modelSelection: { providerId: "custom", modelId: "unknown-context-model" },
  6809. contextWindow: 1_000_000,
  6810. }),
  6811. );
  6812. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6813. usedTokens: 999,
  6814. maxTokens: 1_000_000,
  6815. });
  6816. });
  6817. it("Todo123: 未知容量种子保留用量,后续容量恢复不归零", () => {
  6818. const log = new EventLog();
  6819. log.push(SessionEventType.SessionCreated, { mode: "default" });
  6820. const { projection } = runAll(log.events);
  6821. projection.seedUsage({
  6822. contextWindow: { usedTokens: 29908, maxTokens: null, autoCompactThresholdTokens: null },
  6823. });
  6824. expect(projection.getSnapshot().usage.contextWindow).toBeNull();
  6825. projection.applyEvent(
  6826. log.push(SessionEventType.ModelSelected, {
  6827. modelSelection: { providerId: "glm", modelId: "GLM-5.3-Flash" },
  6828. contextWindow: 1_000_000,
  6829. }),
  6830. );
  6831. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6832. usedTokens: 29908,
  6833. maxTokens: 1_000_000,
  6834. });
  6835. });
  6836. it("Todo123: 未知容量期间真实用量优先,迟到恢复种子不能覆盖", () => {
  6837. const log = new EventLog();
  6838. log.push(SessionEventType.SessionCreated, { mode: "default" });
  6839. log.push(SessionEventType.ModelSelected, {
  6840. modelSelection: { providerId: "glm", modelId: "GLM-5.3-Flash" },
  6841. contextWindow: null,
  6842. });
  6843. log.push(SessionEventType.ModelComplete, {
  6844. content: "",
  6845. stopReason: "end_turn",
  6846. querySource: "main_turn",
  6847. usage: { inputTokens: 700, outputTokens: 30 },
  6848. });
  6849. const { projection } = runAll(log.events);
  6850. projection.seedUsage({
  6851. contextWindow: { usedTokens: 29908, maxTokens: null, autoCompactThresholdTokens: null },
  6852. });
  6853. projection.applyEvent(
  6854. log.push(SessionEventType.ModelSelected, {
  6855. modelSelection: { providerId: "glm", modelId: "GLM-5.3-Flash" },
  6856. contextWindow: 1_000_000,
  6857. }),
  6858. );
  6859. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6860. usedTokens: 730,
  6861. maxTokens: 1_000_000,
  6862. });
  6863. });
  6864. // ── M4:cancelBackgroundWork(BackgroundTask* → backgroundWorks 投影)──
  6865. it("A/B:BackgroundTaskStarted → backgroundWorks 出现 running 项,Completed(cancelled) → cancelled", () => {
  6866. const log = new EventLog();
  6867. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6868. log.push(SessionEventType.BackgroundTaskStarted, {
  6869. taskId: "bg-1",
  6870. toolName: "Bash",
  6871. command: "sleep 100",
  6872. description: "长任务",
  6873. status: "running",
  6874. });
  6875. let snapshot = runAll(log.events).projection.getSnapshot();
  6876. expect(snapshot.backgroundWorks).toHaveLength(1);
  6877. expect(snapshot.backgroundWorks[0]!.workId).toBe("bg-1");
  6878. expect(snapshot.backgroundWorks[0]!.kind).toBe("bash");
  6879. expect(snapshot.backgroundWorks[0]!.title).toBe("长任务");
  6880. expect(snapshot.backgroundWorks[0]!.status).toBe("running");
  6881. // 取消 → cancelled
  6882. log.push(SessionEventType.BackgroundTaskCompleted, {
  6883. taskId: "bg-1",
  6884. toolName: "Bash",
  6885. status: "cancelled",
  6886. });
  6887. snapshot = runAll(log.events).projection.getSnapshot();
  6888. expect(snapshot.backgroundWorks).toHaveLength(1);
  6889. expect(snapshot.backgroundWorks[0]!.status).toBe("cancelled");
  6890. });
  6891. it("A/B:真实 Agent 后台事件使用 runtime taskKind,且旧 Agent 事件兼容为 subagent", () => {
  6892. const log = new EventLog();
  6893. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6894. log.push(SessionEventType.BackgroundTaskStarted, {
  6895. taskId: "bg-2",
  6896. toolName: "Agent",
  6897. taskKind: "subagent",
  6898. childSessionId: "sess_child_bg_2",
  6899. description: "子代理",
  6900. status: "running",
  6901. cancellable: true,
  6902. });
  6903. let snapshot = runAll(log.events).projection.getSnapshot();
  6904. expect(snapshot.backgroundWorks[0]).toMatchObject({
  6905. kind: "subagent",
  6906. childSessionId: "sess_child_bg_2",
  6907. cancellable: true,
  6908. status: "running",
  6909. title: "子代理",
  6910. });
  6911. log.push(SessionEventType.BackgroundTaskCompleted, {
  6912. taskId: "bg-2",
  6913. toolName: "Agent",
  6914. taskKind: "subagent",
  6915. status: "completed",
  6916. cancellable: false,
  6917. });
  6918. snapshot = runAll(log.events).projection.getSnapshot();
  6919. expect(snapshot.backgroundWorks[0]).toMatchObject({
  6920. kind: "subagent",
  6921. childSessionId: "sess_child_bg_2",
  6922. cancellable: false,
  6923. status: "resultPending",
  6924. });
  6925. const lateIdentity = new EventLog();
  6926. lateIdentity.push(SessionEventType.SessionCreated, {
  6927. mode: "default",
  6928. contextWindow: 200_000,
  6929. });
  6930. lateIdentity.push(SessionEventType.BackgroundTaskStarted, {
  6931. taskId: "late-child-id",
  6932. toolName: "Agent",
  6933. taskKind: "subagent",
  6934. description: "晚到身份",
  6935. status: "running",
  6936. cancellable: true,
  6937. });
  6938. lateIdentity.push(SessionEventType.BackgroundTaskUpdated, {
  6939. taskId: "late-child-id",
  6940. toolName: "Agent",
  6941. taskKind: "subagent",
  6942. childSessionId: "sess_child_late",
  6943. description: "晚到身份",
  6944. status: "running",
  6945. cancellable: true,
  6946. });
  6947. expect(runAll(lateIdentity.events).projection.getSnapshot().backgroundWorks[0]).toMatchObject({
  6948. childSessionId: "sess_child_late",
  6949. status: "running",
  6950. });
  6951. const legacy = new EventLog();
  6952. legacy.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6953. legacy.push(SessionEventType.BackgroundTaskStarted, {
  6954. taskId: "legacy-agent",
  6955. toolName: "Agent",
  6956. description: "旧子代理",
  6957. status: "running",
  6958. });
  6959. legacy.push(SessionEventType.BackgroundTaskUpdated, {
  6960. taskId: "legacy-agent",
  6961. status: "running",
  6962. });
  6963. legacy.push(SessionEventType.BackgroundTaskCompleted, {
  6964. taskId: "legacy-agent",
  6965. status: "completed",
  6966. });
  6967. expect(runAll(legacy.events).projection.getSnapshot().backgroundWorks[0]).toMatchObject({
  6968. kind: "subagent",
  6969. status: "resultPending",
  6970. title: "旧子代理",
  6971. });
  6972. const explicit = new EventLog();
  6973. explicit.push(SessionEventType.SessionCreated, {
  6974. mode: "default",
  6975. contextWindow: 200_000,
  6976. });
  6977. explicit.push(SessionEventType.BackgroundTaskStarted, {
  6978. taskId: "explicit-bash",
  6979. // taskKind 是新事实;即使旧 toolName 数据矛盾也不得反向覆盖。
  6980. taskKind: "bash",
  6981. toolName: "Agent",
  6982. description: "显式进程",
  6983. status: "running",
  6984. });
  6985. expect(runAll(explicit.events).projection.getSnapshot().backgroundWorks[0]!.kind).toBe("bash");
  6986. });
  6987. // ── M4:RewindTriggered → row.removed(editUserQuery/retryTurn 的 live 截断)──
  6988. it("D/G:RewindTriggered(targetMessageId) 从目标 turn 首行整段移除", () => {
  6989. const log = new EventLog();
  6990. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6991. // turn1
  6992. log.push(
  6993. SessionEventType.TurnStarted,
  6994. { turnNumber: 1, input: "第一问", messageId: "msg-u1" },
  6995. { turnId: "t1" },
  6996. );
  6997. log.push(
  6998. SessionEventType.ModelStreaming,
  6999. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  7000. { turnId: "t1" },
  7001. );
  7002. log.push(
  7003. SessionEventType.ModelStreaming,
  7004. { kind: "text_delta", delta: "第一答", done: false, assistantMessageId: "msg-a1" },
  7005. { turnId: "t1" },
  7006. );
  7007. log.push(
  7008. SessionEventType.ModelStreaming,
  7009. { kind: "text_end", delta: "", done: false },
  7010. { turnId: "t1" },
  7011. );
  7012. log.push(
  7013. SessionEventType.TurnComplete,
  7014. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  7015. { turnId: "t1" },
  7016. );
  7017. // turn2
  7018. log.push(
  7019. SessionEventType.TurnStarted,
  7020. { turnNumber: 2, input: "第二问", messageId: "msg-u2" },
  7021. { turnId: "t2" },
  7022. );
  7023. log.push(
  7024. SessionEventType.ModelStreaming,
  7025. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a2" },
  7026. { turnId: "t2" },
  7027. );
  7028. log.push(
  7029. SessionEventType.ModelStreaming,
  7030. { kind: "text_delta", delta: "第二答", done: false, assistantMessageId: "msg-a2" },
  7031. { turnId: "t2" },
  7032. );
  7033. log.push(
  7034. SessionEventType.ModelStreaming,
  7035. { kind: "text_end", delta: "", done: false },
  7036. { turnId: "t2" },
  7037. );
  7038. log.push(
  7039. SessionEventType.TurnComplete,
  7040. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  7041. { turnId: "t2" },
  7042. );
  7043. // rewind 到 turn2 的 assistant 消息 → 整个 turn2 被移除。
  7044. // createdMessageId = applied 语义(unavailable/workspace 回滚不带,投影必须忽略)。
  7045. log.push(SessionEventType.RewindTriggered, {
  7046. targetMessageId: "msg-a2",
  7047. scope: "conversation",
  7048. createdMessageId: "msg-rewind-notice",
  7049. });
  7050. const { projection } = runAll(log.events);
  7051. const texts = projection
  7052. .getSnapshot()
  7053. .rows.window.filter((r) => r.kind === "userInput" || r.kind === "assistantText")
  7054. .map((r) => (r.kind === "userInput" || r.kind === "assistantText" ? r.text : ""));
  7055. // turn1 保留,turn2 整段被移除。
  7056. expect(texts).toEqual(["第一问", "第一答"]);
  7057. // 被移除的用户实体不可再解析为编辑目标。
  7058. expect(projection.resolveEditTargetByEntityId("msg-u2")).toBeNull();
  7059. expect(projection.resolveEditTargetByEntityId("msg-u1")).toMatchObject({
  7060. entityId: "msg-u1",
  7061. transcriptMessageId: "msg-u1",
  7062. });
  7063. });
  7064. it("PV4-10 回归:首轮 edit rewind 后分页首行切换到新 active branch", () => {
  7065. const log = new EventLog();
  7066. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7067. log.push(
  7068. SessionEventType.TurnStarted,
  7069. { turnNumber: 1, input: "你好", messageId: "msg-u1" },
  7070. { turnId: "t1" },
  7071. );
  7072. log.push(
  7073. SessionEventType.ModelStreaming,
  7074. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  7075. { turnId: "t1" },
  7076. );
  7077. log.push(
  7078. SessionEventType.ModelStreaming,
  7079. { kind: "text_delta", delta: "旧回答", done: false, assistantMessageId: "msg-a1" },
  7080. { turnId: "t1" },
  7081. );
  7082. log.push(
  7083. SessionEventType.ModelStreaming,
  7084. { kind: "text_end", delta: "", done: false },
  7085. { turnId: "t1" },
  7086. );
  7087. log.push(
  7088. SessionEventType.TurnComplete,
  7089. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  7090. { turnId: "t1" },
  7091. );
  7092. const original = runAll(log.events).projection.getSnapshot();
  7093. const originalMaxRowId = Math.max(...original.rows.window.map((row) => row.rowId));
  7094. log.push(SessionEventType.RewindTriggered, {
  7095. targetMessageId: "msg-u1",
  7096. scope: "conversation",
  7097. branchCutAfterMessageId: "msg-a1",
  7098. branchGeneration: 1,
  7099. });
  7100. const rewound = runAll(log.events).projection.getSnapshot();
  7101. expect(rewound.rows).toEqual({ window: [], totalCount: 0, firstRowId: null });
  7102. log.push(
  7103. SessionEventType.TurnStarted,
  7104. { turnNumber: 2, input: "你是谁", messageId: "msg-u2" },
  7105. { turnId: "t2" },
  7106. );
  7107. const rerun = runAll(log.events).projection.getSnapshot();
  7108. const newFirstRow = rerun.rows.window[0]!;
  7109. expect(newFirstRow.rowId).toBeGreaterThan(originalMaxRowId);
  7110. expect(rerun.rows.firstRowId).toBe(newFirstRow.rowId);
  7111. expect(rerun.rows.totalCount).toBe(rerun.rows.window.length);
  7112. });
  7113. it("D:getTurnRewindAnchor(user 行 rowId) → 同 turn 的 assistant messageId", () => {
  7114. const log = new EventLog();
  7115. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7116. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "问" }, { turnId: "t1" });
  7117. log.push(
  7118. SessionEventType.ModelStreaming,
  7119. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  7120. { turnId: "t1" },
  7121. );
  7122. log.push(
  7123. SessionEventType.ModelStreaming,
  7124. { kind: "text_delta", delta: "答", done: false, assistantMessageId: "msg-a1" },
  7125. { turnId: "t1" },
  7126. );
  7127. log.push(
  7128. SessionEventType.ModelStreaming,
  7129. { kind: "text_end", delta: "", done: false },
  7130. { turnId: "t1" },
  7131. );
  7132. const { projection } = runAll(log.events);
  7133. const userRow = projection.getSnapshot().rows.window.find((r) => r.kind === "userInput");
  7134. expect(userRow).toBeDefined();
  7135. // user 行自身无 messageId,但同 turn 的 assistant messageId 作 rewind 锚点。
  7136. expect(projection.getMessageIdForRow(userRow!.rowId)).toBeNull();
  7137. expect(projection.getTurnRewindAnchor(userRow!.rowId)).toBe("msg-a1");
  7138. });
  7139. it("D/G:RewindTriggered 目标 messageId 无法反查(user 行无 messageId)→ 不误删", () => {
  7140. const log = new EventLog();
  7141. basicTurnEvents(log);
  7142. const before = runAll(log.events).projection.getSnapshot().rows.window.length;
  7143. log.push(SessionEventType.RewindTriggered, {
  7144. targetMessageId: "unknown-msg",
  7145. scope: "conversation",
  7146. createdMessageId: "msg-rewind-notice",
  7147. });
  7148. const after = runAll(log.events).projection.getSnapshot().rows.window.length;
  7149. expect(after).toBe(before);
  7150. });
  7151. it("D/E09 回归:unavailable rewind(无 createdMessageId)与 workspace 回滚不得截断 live 行", () => {
  7152. // Bugfix 回归(2026-07-06 case catalog 战役):finishUnavailable 也发 RewindTriggered,
  7153. // 投影曾不加区分地截断 live 行——store/模型上下文却保留旧分支(假截断),
  7154. // fork child / 刷新 hydration 随后把旧分支复活(E09 失败形态)。
  7155. const log = new EventLog();
  7156. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7157. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "问" }, { turnId: "t1" });
  7158. log.push(
  7159. SessionEventType.ModelStreaming,
  7160. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  7161. { turnId: "t1" },
  7162. );
  7163. log.push(
  7164. SessionEventType.ModelStreaming,
  7165. { kind: "text_delta", delta: "答", done: false, assistantMessageId: "msg-a1" },
  7166. { turnId: "t1" },
  7167. );
  7168. log.push(
  7169. SessionEventType.ModelStreaming,
  7170. { kind: "text_end", delta: "", done: false },
  7171. { turnId: "t1" },
  7172. );
  7173. log.push(
  7174. SessionEventType.TurnComplete,
  7175. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  7176. { turnId: "t1" },
  7177. );
  7178. const beforeRows = runAll(log.events).projection.getSnapshot().rows.window.length;
  7179. expect(beforeRows).toBeGreaterThan(0);
  7180. // unavailable conversation rewind(无 createdMessageId)
  7181. log.push(SessionEventType.RewindTriggered, {
  7182. targetMessageId: "msg-a1",
  7183. scope: "conversation",
  7184. strategy: "unavailable",
  7185. reason: "target_message_is_not_user_prompt",
  7186. });
  7187. // workspace 文件回滚(带 createdMessageId 但 scope=workspace)
  7188. log.push(SessionEventType.RewindTriggered, {
  7189. targetMessageId: "msg-a1",
  7190. scope: "workspace",
  7191. createdMessageId: "msg-ws-notice",
  7192. });
  7193. const after = runAll(log.events).projection.getSnapshot().rows.window.length;
  7194. expect(after).toBe(beforeRows);
  7195. });
  7196. it("O10:ModelComplete.fileChanges 更新 turn header 摘要", () => {
  7197. const log = new EventLog();
  7198. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7199. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "改文件" }, { turnId: "t1" });
  7200. log.push(
  7201. SessionEventType.ModelComplete,
  7202. {
  7203. content: "done",
  7204. stopReason: "stop",
  7205. querySource: "main_turn",
  7206. contextWindow: 200_000,
  7207. usage: { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 },
  7208. fileChanges: {
  7209. files: 1,
  7210. additions: 2,
  7211. deletions: 1,
  7212. items: [{ path: "/work/src/demo.ts", additions: 2, deletions: 1, writeCount: 2 }],
  7213. },
  7214. },
  7215. { turnId: "t1" },
  7216. );
  7217. log.push(
  7218. SessionEventType.TurnComplete,
  7219. { response: "done", tokenCount: 2, toolCallCount: 0, duration: 1, resultType: "success" },
  7220. { turnId: "t1" },
  7221. );
  7222. const { projection } = runAll(log.events);
  7223. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  7224. expect(header).toMatchObject({
  7225. kind: "turnHeader",
  7226. fileChanges: {
  7227. additions: 2,
  7228. deletions: 1,
  7229. files: 1,
  7230. state: "active",
  7231. },
  7232. actions: { canRewindFiles: true },
  7233. });
  7234. const target = { rowId: header!.rowId, entityId: header!.entityId! };
  7235. expect(projection.resolveRowActionTarget(target, "applyFileRewind")).toMatchObject({
  7236. ok: true,
  7237. });
  7238. projection.applyEvent(
  7239. new EventLog().push(SessionEventType.CompactStarted, {
  7240. operationId: "compact-files",
  7241. messageId: "compact-files-message",
  7242. status: "started",
  7243. trigger: "manual",
  7244. display: "separator",
  7245. }),
  7246. );
  7247. const lockedHeader = projection
  7248. .getSnapshot()
  7249. .rows.window.find((row) => row.rowId === header!.rowId)!;
  7250. expect(lockedHeader.actions?.canRewindFiles).toBeUndefined();
  7251. expect(projection.resolveRowActionTarget(target, "applyFileRewind")).toEqual({
  7252. ok: false,
  7253. status: "rejected",
  7254. reasonCode: "guard.actionUnavailable",
  7255. });
  7256. });
  7257. it("O10:subagent ModelComplete 只更新 child turn 文件摘要,不覆盖 usage", () => {
  7258. const log = new EventLog();
  7259. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7260. log.push(
  7261. SessionEventType.TurnStarted,
  7262. { turnNumber: 1, input: "子会话改文件" },
  7263. { turnId: "t1" },
  7264. );
  7265. log.push(
  7266. SessionEventType.ModelComplete,
  7267. {
  7268. content: "done",
  7269. stopReason: "stop",
  7270. querySource: "subagent",
  7271. contextWindow: 999_999,
  7272. usage: { inputTokens: 100, outputTokens: 50, cacheReadTokens: 10, cacheWriteTokens: 5 },
  7273. fileChanges: {
  7274. files: 1,
  7275. additions: 1,
  7276. deletions: 0,
  7277. items: [{ path: "/work/src/child.ts", additions: 1, deletions: 0, writeCount: 1 }],
  7278. },
  7279. },
  7280. { turnId: "t1" },
  7281. );
  7282. log.push(
  7283. SessionEventType.TurnComplete,
  7284. { response: "done", tokenCount: 150, toolCallCount: 1, duration: 1, resultType: "success" },
  7285. { turnId: "t1" },
  7286. );
  7287. const { projection } = runAll(log.events);
  7288. const snapshot = projection.getSnapshot();
  7289. const header = snapshot.rows.window.find((row) => row.kind === "turnHeader");
  7290. expect(header).toMatchObject({
  7291. kind: "turnHeader",
  7292. fileChanges: {
  7293. additions: 1,
  7294. deletions: 0,
  7295. files: 1,
  7296. state: "active",
  7297. },
  7298. actions: { canRewindFiles: true },
  7299. });
  7300. expect(snapshot.usage.cumulative).toEqual({
  7301. inputTokens: 0,
  7302. outputTokens: 0,
  7303. cacheReadTokens: 0,
  7304. cacheWriteTokens: 0,
  7305. });
  7306. });
  7307. it("O10:普通 TurnStarted 的 user messageId 进入同轮文件摘要锚点", () => {
  7308. const log = new EventLog();
  7309. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7310. log.push(
  7311. SessionEventType.TurnStarted,
  7312. { turnNumber: 1, input: "改文件", messageId: "msg-user-1" },
  7313. { turnId: "t1" },
  7314. );
  7315. const { projection } = runAll(log.events);
  7316. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  7317. expect(header).toBeDefined();
  7318. expect(projection.getMessageIdsForTurnRow(header!.rowId)).toContain("msg-user-1");
  7319. });
  7320. it("O12:workspace 文件撤销只标记 fileChanges.reverted,不移除聊天行", () => {
  7321. const log = new EventLog();
  7322. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7323. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "改文件" }, { turnId: "t1" });
  7324. log.push(
  7325. SessionEventType.ModelStreaming,
  7326. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  7327. { turnId: "t1" },
  7328. );
  7329. log.push(
  7330. SessionEventType.ModelStreaming,
  7331. { kind: "text_delta", delta: "已改", done: false, assistantMessageId: "msg-a1" },
  7332. { turnId: "t1" },
  7333. );
  7334. log.push(
  7335. SessionEventType.ModelStreaming,
  7336. { kind: "text_end", delta: "", done: false },
  7337. { turnId: "t1" },
  7338. );
  7339. log.push(
  7340. SessionEventType.ModelComplete,
  7341. {
  7342. content: "已改",
  7343. stopReason: "stop",
  7344. querySource: "main_turn",
  7345. contextWindow: 200_000,
  7346. usage: { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 },
  7347. fileChanges: {
  7348. files: 1,
  7349. additions: 2,
  7350. deletions: 1,
  7351. items: [{ path: "/work/src/demo.ts", additions: 2, deletions: 1, writeCount: 1 }],
  7352. },
  7353. },
  7354. { turnId: "t1" },
  7355. );
  7356. log.push(
  7357. SessionEventType.TurnComplete,
  7358. { response: "已改", tokenCount: 1, toolCallCount: 1, duration: 10, resultType: "success" },
  7359. { turnId: "t1" },
  7360. );
  7361. const before = runAll(log.events).projection.getSnapshot().rows.window;
  7362. log.push(SessionEventType.RewindTriggered, {
  7363. targetMessageId: "msg-a1",
  7364. scope: "workspace",
  7365. reason: "file_summary_rewind",
  7366. });
  7367. const { projection } = runAll(log.events);
  7368. const rows = projection.getSnapshot().rows.window;
  7369. expect(rows).toHaveLength(before.length);
  7370. const header = rows.find((row) => row.kind === "turnHeader");
  7371. expect(header).toMatchObject({
  7372. kind: "turnHeader",
  7373. fileChanges: {
  7374. additions: 2,
  7375. deletions: 1,
  7376. files: 1,
  7377. state: "reverted",
  7378. },
  7379. });
  7380. expect(rows.some((row) => row.kind === "assistantText" && row.text === "已改")).toBe(true);
  7381. });
  7382. });
  7383. // ── M5④ 附件渲染:TurnStarted.attachments → userInput row.attachments ──
  7384. describe("userInput 附件投影(M5④)", () => {
  7385. it("TurnStarted 携带附件元信息 → row.attachments 保真映射且 schema 合法", () => {
  7386. const log = new EventLog();
  7387. log.push(SessionEventType.SessionCreated, {
  7388. mode: "default",
  7389. contextWindow: 200_000,
  7390. });
  7391. log.push(
  7392. SessionEventType.TurnStarted,
  7393. {
  7394. turnNumber: 1,
  7395. input: "看看这张图",
  7396. inputId: "command-start-now",
  7397. intent: {
  7398. sourceCommandId: "command-start-now",
  7399. queueItemId: "queue_command-start-now",
  7400. clientId: "desktop-client",
  7401. kind: "sendText",
  7402. admissionSeq: 3,
  7403. admittedAt: 100,
  7404. requestedDelivery: "startNow",
  7405. admittedDelivery: "startNow",
  7406. },
  7407. attachments: [
  7408. {
  7409. fileName: "screenshot.png",
  7410. mime: "image/png",
  7411. bytes: 12345,
  7412. ref: "/tmp/screenshot.png",
  7413. },
  7414. // 无稳定引用(data URL 内联):ref 缺省 → 投影生成行内占位。
  7415. { fileName: "notes.md", mime: "text/markdown", bytes: 42 },
  7416. ],
  7417. },
  7418. { turnId: "turn-1" },
  7419. );
  7420. const { projection } = runAll(log.events);
  7421. const snapshot = projection.getSnapshot();
  7422. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  7423. const userInput = snapshot.rows.window.find((row) => row.kind === "userInput");
  7424. expect(userInput).toBeDefined();
  7425. expect(userInput).toMatchObject({
  7426. sourceCommandId: "command-start-now",
  7427. clientId: "desktop-client",
  7428. });
  7429. const attachments = userInput?.kind === "userInput" ? userInput.attachments : undefined;
  7430. expect(attachments).toHaveLength(2);
  7431. expect(attachments?.[0]).toEqual({
  7432. ref: "/tmp/screenshot.png",
  7433. fileName: "screenshot.png",
  7434. mime: "image/png",
  7435. bytes: 12345,
  7436. });
  7437. expect(attachments?.[1]).toMatchObject({
  7438. fileName: "notes.md",
  7439. mime: "text/markdown",
  7440. bytes: 42,
  7441. });
  7442. expect(attachments?.[1]?.ref).toMatch(/^turn-attachment\//);
  7443. });
  7444. it("无附件的 TurnStarted:row 不带 attachments 键(缺省语义)", () => {
  7445. const log = new EventLog();
  7446. basicTurnEvents(log);
  7447. const { projection } = runAll(log.events);
  7448. const userInput = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput");
  7449. expect(userInput?.kind === "userInput" ? "attachments" in userInput : null).toBe(false);
  7450. });
  7451. });
  7452. // R-19(10 §4.2.3):config 种子——投影初值 = runtime 真值,种子不产 delta / 不 bump
  7453. // revision,事件触碰过的字段不接受种子覆盖("最终值以日志为准")。
  7454. // Bug 背景(2026-07-07 v4 桌面首测):初始 config 写死空 provider/model + mode=build,
  7455. // 导致新会话模型选择器显示空、持久化 mode=yolo 时 UI 停在 build 且点 yolo 静默 no-op。
  7456. describe("config 种子(R-19)", () => {
  7457. const SEED = {
  7458. provider: "prov-a",
  7459. model: "model-1",
  7460. thought: "high",
  7461. thoughtLevels: ["high", "max", "nothink"],
  7462. mode: "yolo",
  7463. };
  7464. it("种子填充空初值:config 就位、revision/seq 不动、schema 合法", () => {
  7465. const projection = new ProductProjection("session-1", "epoch-1");
  7466. projection.seedConfig(SEED);
  7467. const snapshot = projection.getSnapshot();
  7468. expect(snapshot.config).toMatchObject({
  7469. provider: "prov-a",
  7470. model: "model-1",
  7471. thought: "high",
  7472. thoughtLevels: ["high", "max", "nothink"],
  7473. mode: "yolo",
  7474. });
  7475. expect(snapshot.revision).toBe(0);
  7476. expect(snapshot.seq).toBe(0);
  7477. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  7478. });
  7479. it("种子后事件覆盖:ModelSelected / SessionModeChanged 的日志值优先", () => {
  7480. const projection = new ProductProjection("session-1", "epoch-1");
  7481. projection.seedConfig(SEED);
  7482. const log = new EventLog();
  7483. log.push(SessionEventType.ModelSelected, {
  7484. modelSelection: {
  7485. providerId: "prov-b",
  7486. modelId: "model-2",
  7487. options: { reasoningLevel: "low" },
  7488. },
  7489. supportedThoughtLevels: ["low", "high"],
  7490. });
  7491. log.push(SessionEventType.SessionModeChanged, {
  7492. mode: "plan",
  7493. previousMode: "yolo",
  7494. source: "command",
  7495. });
  7496. for (const event of log.events) projection.applyEvent(event);
  7497. expect(projection.getSnapshot().config).toMatchObject({
  7498. provider: "prov-b",
  7499. model: "model-2",
  7500. thought: "low",
  7501. thoughtLevels: ["low", "high"],
  7502. mode: "plan",
  7503. });
  7504. projection.seedConfig({ ...SEED, thoughtLevels: ["disabled"] });
  7505. expect(projection.getSnapshot().config.thoughtLevels).toEqual(["low", "high"]);
  7506. });
  7507. it("事件后种子不覆盖:冷恢复重放序在前时日志值保持权威", () => {
  7508. const projection = new ProductProjection("session-1", "epoch-1");
  7509. const log = new EventLog();
  7510. log.push(SessionEventType.ModelSelected, {
  7511. modelSelection: { providerId: "prov-b", modelId: "model-2" },
  7512. });
  7513. log.push(SessionEventType.SessionModeChanged, {
  7514. mode: "plan",
  7515. previousMode: "build",
  7516. source: "tool",
  7517. });
  7518. for (const event of log.events) projection.applyEvent(event);
  7519. projection.seedConfig(SEED);
  7520. expect(projection.getSnapshot().config).toMatchObject({
  7521. provider: "prov-b",
  7522. model: "model-2",
  7523. thoughtLevels: ["high", "max", "nothink"],
  7524. mode: "plan",
  7525. });
  7526. });
  7527. it("分区独立:只有 mode 被事件触碰时,模型区仍接受种子(反之亦然)", () => {
  7528. const projection = new ProductProjection("session-1", "epoch-1");
  7529. const log = new EventLog();
  7530. log.push(SessionEventType.SessionModeChanged, {
  7531. mode: "plan",
  7532. previousMode: "build",
  7533. source: "command",
  7534. });
  7535. for (const event of log.events) projection.applyEvent(event);
  7536. projection.seedConfig(SEED);
  7537. const config = projection.getSnapshot().config;
  7538. // mode 由日志裁决,模型区来自种子(历史会话恢复:resume 已把上次选型写回 runtime)。
  7539. expect(config.mode).toBe("plan");
  7540. expect(config).toMatchObject({
  7541. provider: "prov-a",
  7542. model: "model-1",
  7543. thought: "high",
  7544. thoughtLevels: ["high", "max", "nothink"],
  7545. });
  7546. });
  7547. it("相同种子幂等,明确留空的恢复结果清除旧模型", () => {
  7548. const projection = new ProductProjection("session-1", "epoch-1");
  7549. projection.seedConfig(SEED);
  7550. const first = projection.getSnapshot();
  7551. projection.seedConfig(SEED);
  7552. expect(projection.getSnapshot()).toBe(first);
  7553. // 恢复结果明确留空,不能继续显示历史消息留下的模型。
  7554. projection.seedConfig({ provider: "", model: "", mode: "" });
  7555. expect(projection.getSnapshot().config).toMatchObject({
  7556. provider: "",
  7557. model: "",
  7558. });
  7559. });
  7560. it("分享上下文导入种子只写只读来源元数据,不生成可见对话行", () => {
  7561. const projection = new ProductProjection("session-1", "epoch-1");
  7562. const before = projection.getSnapshot();
  7563. projection.seedSharedContextImport({ title: "筛选近一年收益前10%的偏股混合基金" });
  7564. const snapshot = projection.getSnapshot();
  7565. expect(snapshot.sharedContextImport).toEqual({
  7566. title: "筛选近一年收益前10%的偏股混合基金",
  7567. });
  7568. expect(snapshot.rows.window).toEqual([]);
  7569. expect(snapshot.revision).toBe(before.revision);
  7570. expect(snapshot.seq).toBe(before.seq);
  7571. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  7572. });
  7573. });
  7574. // ── 16-timeline-authority-plan P2:productTurn 切分 / goalVerify 身份与落位 ──
  7575. describe("P2 productTurn 切分(S1/S3/S5)", () => {
  7576. const drainScenario = (delivery: "queue" | "guide") => {
  7577. const log = new EventLog();
  7578. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7579. log.push(
  7580. SessionEventType.TurnStarted,
  7581. { turnNumber: 1, input: "问题一" },
  7582. { turnId: "turn-1" },
  7583. );
  7584. log.push(
  7585. SessionEventType.ModelStreaming,
  7586. { kind: "text_start", delta: "", done: false },
  7587. { turnId: "turn-1" },
  7588. );
  7589. log.push(
  7590. SessionEventType.ModelStreaming,
  7591. { kind: "text_delta", delta: "回答一", done: false },
  7592. { turnId: "turn-1" },
  7593. );
  7594. log.push(
  7595. SessionEventType.ModelStreaming,
  7596. { kind: "text_end", delta: "", done: false },
  7597. { turnId: "turn-1" },
  7598. );
  7599. log.push(
  7600. SessionEventType.TurnSteerQueued,
  7601. {
  7602. pendingInputId: "p-q2",
  7603. input: "问题二",
  7604. inputPreview: "问题二",
  7605. inputSize: 9,
  7606. delivery,
  7607. targetTurnId: "turn-1",
  7608. queueLength: 1,
  7609. },
  7610. { turnId: "turn-1" },
  7611. );
  7612. log.push(
  7613. SessionEventType.TurnSteerDrained,
  7614. {
  7615. pendingInputIds: ["p-q2"],
  7616. injectedMessageIds: ["msg-q2"],
  7617. drainedInputs: [
  7618. {
  7619. pendingInputId: "p-q2",
  7620. messageId: "msg-q2",
  7621. text: "问题二",
  7622. delivery,
  7623. intent: {
  7624. sourceCommandId: "command-q2",
  7625. queueItemId: "p-q2",
  7626. clientId: "desktop-continuous",
  7627. kind: delivery === "guide" ? "sendGoalCommand" : "sendText",
  7628. text: "问题二",
  7629. admissionSeq: 2,
  7630. admittedAt: 1_700_000_006_000,
  7631. requestedDelivery: "auto",
  7632. admittedDelivery: delivery,
  7633. fallbackReasonCode: "runtime.turnBusy",
  7634. attachmentRefs: [
  7635. {
  7636. ref: "artifact://q2",
  7637. fileName: "q2.txt",
  7638. mime: "text/plain",
  7639. bytes: 3,
  7640. },
  7641. ],
  7642. provenance: {
  7643. sourceCommandId: "command-q2-original",
  7644. queueItemId: "p-q2-original",
  7645. clientId: "desktop-continuous",
  7646. },
  7647. },
  7648. },
  7649. ],
  7650. targetTurnId: "turn-1",
  7651. },
  7652. { turnId: "turn-1" },
  7653. );
  7654. log.push(
  7655. SessionEventType.ModelStreaming,
  7656. { kind: "text_start", delta: "", done: false },
  7657. { turnId: "turn-1" },
  7658. );
  7659. log.push(
  7660. SessionEventType.ModelStreaming,
  7661. { kind: "text_delta", delta: "回答二", done: false },
  7662. { turnId: "turn-1" },
  7663. );
  7664. log.push(
  7665. SessionEventType.ModelStreaming,
  7666. { kind: "text_end", delta: "", done: false },
  7667. { turnId: "turn-1" },
  7668. );
  7669. log.push(
  7670. SessionEventType.TurnComplete,
  7671. { response: "", tokenCount: 0, toolCallCount: 0, duration: 9000, resultType: "success" },
  7672. { turnId: "turn-1" },
  7673. );
  7674. return runAll(log.events);
  7675. };
  7676. it("QD-node:queue drain 切新 productTurn,两段回复都可见、工时按边界拆分(Case A 根修)", () => {
  7677. const { projection } = drainScenario("queue");
  7678. const snapshot = projection.getSnapshot();
  7679. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  7680. const rows = snapshot.rows.window;
  7681. // 两个 turnHeader:首轮 legacy runtime id 与 promoted user messageId(稳定 productTurn)。
  7682. const headers = rows.filter((row) => row.kind === "turnHeader");
  7683. expect(headers.map((row) => row.turnId)).toEqual(["turn-1", "msg-q2"]);
  7684. // 第一段 header 在 drain 边界收口:activeMs = drain(7s) - start(2s)。
  7685. expect(headers[0]).toMatchObject({ state: "completedSuccess", activeMs: 5000 });
  7686. // 第二段 header 在 TurnComplete 收口:activeMs = complete(11s) - drain(7s),
  7687. // 不再是整段 runtime duration(9000)。
  7688. expect(headers[1]).toMatchObject({ state: "completedSuccess", activeMs: 4000 });
  7689. // 两段 assistant 正文都在,各归自己的 productTurn——A1 不再被折进上一轮 history。
  7690. const assistantRows = rows.filter((row) => row.kind === "assistantText");
  7691. expect(
  7692. assistantRows.map((row) => [row.turnId, row.kind === "assistantText" ? row.text : ""]),
  7693. ).toEqual([
  7694. ["turn-1", "回答一"],
  7695. ["msg-q2", "回答二"],
  7696. ]);
  7697. // drained user 行归新 productTurn,并原子登记 message/entity/edit target。
  7698. const drainedUser = rows.find((row) => row.kind === "userInput" && row.text === "问题二");
  7699. expect(drainedUser?.turnId).toBe("msg-q2");
  7700. expect(projection.getMessageIdForRow(drainedUser!.rowId)).toBe("msg-q2");
  7701. expect(projection.getEntityIdForRow(drainedUser!.rowId)).toBe("msg-q2");
  7702. expect(drainedUser?.actions).toMatchObject({ canEdit: true, editDisposition: "rewind" });
  7703. expect(
  7704. projection.resolveRowActionTarget(
  7705. { rowId: drainedUser!.rowId, entityId: drainedUser!.entityId },
  7706. "editUserQuery",
  7707. ),
  7708. ).toMatchObject({
  7709. ok: true,
  7710. editTarget: {
  7711. entityId: "msg-q2",
  7712. productTurnId: "msg-q2",
  7713. transcriptMessageId: "msg-q2",
  7714. intent: {
  7715. kind: "sendText",
  7716. text: "问题二",
  7717. sourceCommandId: "command-q2",
  7718. queueItemId: "p-q2",
  7719. clientId: "desktop-continuous",
  7720. admissionSeq: 2,
  7721. admittedAt: 1_700_000_006_000,
  7722. requestedDelivery: "auto",
  7723. admittedDelivery: "queue",
  7724. fallbackReasonCode: "runtime.turnBusy",
  7725. attachments: [
  7726. {
  7727. ref: "artifact://q2",
  7728. fileName: "q2.txt",
  7729. mime: "text/plain",
  7730. bytes: 3,
  7731. },
  7732. ],
  7733. provenance: {
  7734. sourceCommandId: "command-q2-original",
  7735. queueItemId: "p-q2-original",
  7736. clientId: "desktop-continuous",
  7737. },
  7738. },
  7739. },
  7740. });
  7741. const coldLog = new EventLog();
  7742. coldLog.push(
  7743. SessionEventType.TurnStarted,
  7744. { turnNumber: 2, input: "问题二", messageId: "msg-q2" },
  7745. { turnId: "hydrate-turn-2" },
  7746. );
  7747. const coldUser = runAll(coldLog.events)
  7748. .projection.getSnapshot()
  7749. .rows.window.find((row) => row.kind === "userInput");
  7750. // 同一 promoted user transcript 在 live drain 与 cold TurnStarted 中使用同一 productTurnId。
  7751. expect(coldUser?.turnId).toBe(drainedUser?.turnId);
  7752. expect(snapshot.queue.items).toEqual([]);
  7753. });
  7754. it("P06:guide steer 内联不切轮,但 accepted guide 开启独立可恢复工时段", () => {
  7755. const { projection } = drainScenario("guide");
  7756. const snapshot = projection.getSnapshot();
  7757. const rows = snapshot.rows.window;
  7758. const headers = rows.filter((row) => row.kind === "turnHeader");
  7759. expect(headers.map((row) => row.turnId)).toEqual(["turn-1"]);
  7760. expect(headers[0]).toMatchObject({
  7761. state: "completedSuccess",
  7762. activeMs: 9000,
  7763. workSegments: [
  7764. {
  7765. segmentId: "turn-1:initial",
  7766. startedAt: 1_700_000_002_000,
  7767. endedAt: 1_700_000_007_000,
  7768. activeMs: 5000,
  7769. },
  7770. {
  7771. segmentId: "msg-q2",
  7772. triggerEntityId: "msg-q2",
  7773. startedAt: 1_700_000_007_000,
  7774. endedAt: 1_700_000_011_000,
  7775. activeMs: 4000,
  7776. },
  7777. ],
  7778. });
  7779. const steerUser = rows.find((row) => row.kind === "userInput" && row.text === "问题二");
  7780. expect(steerUser?.turnId).toBe("turn-1");
  7781. expect(steerUser?.actions).toMatchObject({ canEdit: true, editDisposition: "rewind" });
  7782. expect(
  7783. projection.resolveRowActionTarget(
  7784. { rowId: steerUser!.rowId, entityId: steerUser!.entityId },
  7785. "editUserQuery",
  7786. ),
  7787. ).toMatchObject({
  7788. ok: true,
  7789. editTarget: {
  7790. entityId: "msg-q2",
  7791. productTurnId: "turn-1",
  7792. transcriptMessageId: "msg-q2",
  7793. intent: {
  7794. kind: "sendGoalCommand",
  7795. text: "问题二",
  7796. sourceCommandId: "command-q2",
  7797. queueItemId: "p-q2",
  7798. admittedDelivery: "guide",
  7799. },
  7800. },
  7801. });
  7802. // 内联位置:在 A1 之后、A2 之前。
  7803. const order = rows
  7804. .filter((row) => row.kind === "assistantText" || row.kind === "userInput")
  7805. .map((row) => (row.kind === "assistantText" || row.kind === "userInput" ? row.text : ""));
  7806. expect(order).toEqual(["问题一", "回答一", "问题二", "回答二"]);
  7807. });
  7808. it("兼容:旧 runtime 事件(无 drainedInputs/delivery)回退 queue 查表,按 followupMode 兜底切轮", () => {
  7809. const log = new EventLog();
  7810. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7811. log.push(
  7812. SessionEventType.TurnStarted,
  7813. { turnNumber: 1, input: "问题一" },
  7814. { turnId: "turn-1" },
  7815. );
  7816. log.push(
  7817. SessionEventType.TurnSteerQueued,
  7818. {
  7819. pendingInputId: "p-legacy",
  7820. input: "老事件文本",
  7821. inputPreview: "老事件文本",
  7822. inputSize: 15,
  7823. targetTurnId: "turn-1",
  7824. queueLength: 1,
  7825. },
  7826. { turnId: "turn-1" },
  7827. );
  7828. log.push(
  7829. SessionEventType.TurnSteerDrained,
  7830. {
  7831. pendingInputIds: ["p-legacy"],
  7832. injectedMessageIds: ["msg-legacy"],
  7833. targetTurnId: "turn-1",
  7834. },
  7835. { turnId: "turn-1" },
  7836. );
  7837. const { projection } = runAll(log.events);
  7838. const rows = projection.getSnapshot().rows.window;
  7839. const drained = rows.find((row) => row.kind === "userInput" && row.text === "老事件文本");
  7840. // followupMode 默认 queue → 切轮;旧事件虽无 drainedInputs,injectedMessageIds
  7841. // 仍是 promotion 后的持久 user 身份,因此 product turn 也稳定使用该 messageId。
  7842. expect(drained?.turnId).toBe("msg-legacy");
  7843. expect(projection.getMessageIdForRow(drained!.rowId)).toBe("msg-legacy");
  7844. });
  7845. it("PV4-10 防御:drain 缺持久 messageId 时不暴露无法执行的 edit action", () => {
  7846. const log = new EventLog();
  7847. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7848. log.push(
  7849. SessionEventType.TurnStarted,
  7850. { turnNumber: 1, input: "问题一" },
  7851. { turnId: "turn-1" },
  7852. );
  7853. log.push(
  7854. SessionEventType.TurnSteerQueued,
  7855. {
  7856. pendingInputId: "p-no-message",
  7857. input: "缺少持久身份",
  7858. inputPreview: "缺少持久身份",
  7859. inputSize: 18,
  7860. targetTurnId: "turn-1",
  7861. queueLength: 1,
  7862. },
  7863. { turnId: "turn-1" },
  7864. );
  7865. log.push(
  7866. SessionEventType.TurnSteerDrained,
  7867. { pendingInputIds: ["p-no-message"], targetTurnId: "turn-1" },
  7868. { turnId: "turn-1" },
  7869. );
  7870. const { projection } = runAll(log.events);
  7871. const drained = projection
  7872. .getSnapshot()
  7873. .rows.window.find((row) => row.kind === "userInput" && row.text === "缺少持久身份");
  7874. expect(drained?.actions?.canEdit).not.toBe(true);
  7875. expect(
  7876. projection.resolveRowActionTarget(
  7877. { rowId: drained!.rowId, entityId: drained!.entityId },
  7878. "editUserQuery",
  7879. ),
  7880. ).toEqual({
  7881. ok: false,
  7882. status: "rejected",
  7883. reasonCode: "guard.actionUnavailable",
  7884. });
  7885. });
  7886. });
  7887. describe("P2 goalVerify 身份与落位(GV-identity / GV-terminal-only / GV-late-anchor)", () => {
  7888. it("同 targetId+iteration 的重试(新 verificationId)复用同一 marker,不长第二个", () => {
  7889. const log = new EventLog();
  7890. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  7891. log.push(SessionEventType.TargetCompletionVerification, {
  7892. targetId: "target-1",
  7893. status: "started",
  7894. verificationId: "attempt-1",
  7895. goalIteration: 1,
  7896. });
  7897. log.push(SessionEventType.TargetCompletionVerification, {
  7898. targetId: "target-1",
  7899. status: "started",
  7900. verificationId: "attempt-2",
  7901. goalIteration: 1,
  7902. });
  7903. log.push(SessionEventType.TargetCompletionVerification, {
  7904. targetId: "target-1",
  7905. status: "completed",
  7906. verificationId: "attempt-2",
  7907. goalIteration: 1,
  7908. verification: { passed: true, reason: "ok" },
  7909. });
  7910. const { projection } = runAll(log.events);
  7911. const markers = projection
  7912. .getSnapshot()
  7913. .rows.window.filter(
  7914. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  7915. );
  7916. expect(markers).toHaveLength(1);
  7917. expect(markers[0]).toMatchObject({ marker: { iteration: 1, outcome: "pass" } });
  7918. });
  7919. it("GV-terminal-only:终态先到(无 started、无 goal 状态)也能创建 boundary", () => {
  7920. const log = new EventLog();
  7921. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  7922. log.push(SessionEventType.TargetCompletionVerification, {
  7923. targetId: "target-1",
  7924. status: "completed",
  7925. verificationId: "only-terminal",
  7926. goalIteration: 3,
  7927. verification: { passed: false, reason: "还差测试" },
  7928. });
  7929. const { projection } = runAll(log.events);
  7930. const marker = projection
  7931. .getSnapshot()
  7932. .rows.window.find((row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify");
  7933. expect(marker).toMatchObject({
  7934. marker: { iteration: 3, outcome: "notSatisfied", detail: "还差测试" },
  7935. });
  7936. });
  7937. it("GV-late-anchor:verify 迟到到下一轮之后,按 anchorTurnId 锚回被验证的轮", () => {
  7938. const log = new EventLog();
  7939. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  7940. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "Q1" }, { turnId: "turn-1" });
  7941. log.push(
  7942. SessionEventType.TurnComplete,
  7943. { response: "", tokenCount: 0, toolCallCount: 0, duration: 100, resultType: "success" },
  7944. { turnId: "turn-1" },
  7945. );
  7946. log.push(SessionEventType.TurnStarted, { turnNumber: 2, input: "Q2" }, { turnId: "turn-2" });
  7947. // 迟到的 verify:事件本身归属 turn-2 期间,但 payload 锚定 turn-1。
  7948. log.push(SessionEventType.TargetCompletionVerification, {
  7949. targetId: "target-1",
  7950. status: "started",
  7951. verificationId: "late-1",
  7952. goalIteration: 1,
  7953. anchorTurnId: "turn-1",
  7954. });
  7955. const { projection } = runAll(log.events);
  7956. const marker = projection
  7957. .getSnapshot()
  7958. .rows.window.find((row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify");
  7959. // UI 按 turnId 分组:锚回 turn-1 而不是落进 turn-2 或 "turn-unknown"。
  7960. expect(marker?.turnId).toBe("turn-1");
  7961. });
  7962. });
  7963. describe("Desktop Hook invocation projection", () => {
  7964. it("keeps the shared Hook event enum aligned with Coding contracts", () => {
  7965. expect(new Set(hookInvocationRowSchema.shape.hookEventName.options)).toEqual(
  7966. new Set(Object.values(HookEventName)),
  7967. );
  7968. });
  7969. const descriptor = {
  7970. clientVisible: true as const,
  7971. sourceKind: "user" as const,
  7972. sourcePath: "/Users/example/.zcode/cli/config.json",
  7973. executionType: "process" as const,
  7974. executionMode: "foreground" as const,
  7975. commandDisplay: "node hooks/check.mjs",
  7976. timeoutMs: 5_000,
  7977. };
  7978. it("HK08/HK10 projects safe Hook summaries into the authoritative real turn", () => {
  7979. const log = new EventLog();
  7980. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1_000 });
  7981. log.push(
  7982. SessionEventType.HookRunStarted,
  7983. {
  7984. descriptor,
  7985. hookEventName: "SessionStart",
  7986. hookIndex: 0,
  7987. hookCount: 1,
  7988. hookInvocationId: "startup-hook",
  7989. hookRunId: "startup-run",
  7990. startedAt: 1_700_000_002_000,
  7991. },
  7992. { turnId: "runtime-turn-before-product-mapping" },
  7993. );
  7994. log.push(
  7995. SessionEventType.HookRunCompleted,
  7996. {
  7997. descriptor,
  7998. durationMs: 10,
  7999. hookEventName: "SessionStart",
  8000. hookIndex: 0,
  8001. hookCount: 1,
  8002. hookInvocationId: "startup-hook",
  8003. hookRunId: "startup-run",
  8004. outcome: "success",
  8005. startedAt: 1_700_000_002_000,
  8006. },
  8007. { turnId: "runtime-turn-before-product-mapping" },
  8008. );
  8009. const beforeTurn = runAll(log.events).projection.getSnapshot();
  8010. expect(beforeTurn.rows.window.some((row) => row.kind === "hookInvocation")).toBe(false);
  8011. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  8012. log.push(
  8013. SessionEventType.HookRunStarted,
  8014. {
  8015. descriptor,
  8016. hookEventName: "PreToolUse",
  8017. hookIndex: 0,
  8018. hookCount: 1,
  8019. hookInvocationId: "tool-hook",
  8020. hookRunId: "tool-run",
  8021. startedAt: 1_700_000_003_000,
  8022. toolCallId: "tool-1",
  8023. toolName: "Write",
  8024. },
  8025. { turnId: "turn-1" },
  8026. );
  8027. log.push(
  8028. SessionEventType.HookRunCompleted,
  8029. {
  8030. descriptor,
  8031. durationMs: 20,
  8032. hookEventName: "PreToolUse",
  8033. hookIndex: 0,
  8034. hookCount: 1,
  8035. hookInvocationId: "tool-hook",
  8036. hookRunId: "tool-run",
  8037. outcome: "success",
  8038. startedAt: 1_700_000_003_000,
  8039. toolCallId: "tool-1",
  8040. toolName: "Write",
  8041. },
  8042. { turnId: "turn-1" },
  8043. );
  8044. const { projection } = runAll(log.events);
  8045. const hookRows = projection
  8046. .getSnapshot()
  8047. .rows.window.filter((row) => row.kind === "hookInvocation");
  8048. expect(hookRows.map((row) => row.turnId)).toEqual(["turn-1", "turn-1"]);
  8049. expect(hookRows[0]).toMatchObject({
  8050. hookEventName: "SessionStart",
  8051. executions: [
  8052. expect.objectContaining({
  8053. didExecute: true,
  8054. displayName: "node · check.mjs",
  8055. sourceKind: "user",
  8056. }),
  8057. ],
  8058. });
  8059. expect(hookRows[1]).toMatchObject({
  8060. hookEventName: "PreToolUse",
  8061. anchorToolCallId: "tool-1",
  8062. executions: [
  8063. expect.objectContaining({
  8064. didExecute: true,
  8065. displayName: "node · check.mjs",
  8066. sourceKind: "user",
  8067. toolName: "Write",
  8068. }),
  8069. ],
  8070. });
  8071. expect(JSON.stringify(hookRows)).not.toMatch(/commandDisplay|sourcePath/u);
  8072. expect(projection.getSnapshot().rows.window.map((row) => row.turnId)).not.toContain(
  8073. "session-hooks:session-1",
  8074. );
  8075. });
  8076. it("HK09 distinguishes admission-only blocked from a Hook that executed and blocked", () => {
  8077. const log = new EventLog();
  8078. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8079. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  8080. log.push(
  8081. SessionEventType.HookRunBlocked,
  8082. {
  8083. descriptor,
  8084. hookEventName: "PreToolUse",
  8085. hookIndex: 0,
  8086. hookCount: 2,
  8087. hookInvocationId: "mixed-hook",
  8088. hookRunId: "admission-blocked",
  8089. outcome: "blocked",
  8090. startedAt: 1_700_000_003_000,
  8091. },
  8092. { turnId: "turn-1" },
  8093. );
  8094. log.push(
  8095. SessionEventType.HookRunStarted,
  8096. {
  8097. descriptor,
  8098. hookEventName: "PreToolUse",
  8099. hookIndex: 1,
  8100. hookCount: 2,
  8101. hookInvocationId: "mixed-hook",
  8102. hookRunId: "executed-block",
  8103. startedAt: 1_700_000_003_010,
  8104. },
  8105. { turnId: "turn-1" },
  8106. );
  8107. log.push(
  8108. SessionEventType.HookRunBlocked,
  8109. {
  8110. descriptor,
  8111. durationMs: 8,
  8112. hookEventName: "PreToolUse",
  8113. hookIndex: 1,
  8114. hookCount: 2,
  8115. hookInvocationId: "mixed-hook",
  8116. hookRunId: "executed-block",
  8117. blockReason: "blocked by workspace policy",
  8118. outcome: "blocked",
  8119. startedAt: 1_700_000_003_010,
  8120. },
  8121. { turnId: "turn-1" },
  8122. );
  8123. const row = runAll(log.events)
  8124. .projection.getSnapshot()
  8125. .rows.window.find((candidate) => candidate.kind === "hookInvocation");
  8126. expect(row).toMatchObject({
  8127. state: "completed",
  8128. executions: [
  8129. expect.objectContaining({ hookRunId: "admission-blocked", didExecute: false }),
  8130. expect.objectContaining({
  8131. hookRunId: "executed-block",
  8132. didExecute: true,
  8133. outcome: "blocked",
  8134. blockReason: "blocked by workspace policy",
  8135. }),
  8136. ],
  8137. });
  8138. });
  8139. it("HK-UP-02 projects an executed UserPromptSubmit block into the chat error", () => {
  8140. const log = new EventLog();
  8141. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1_000 });
  8142. log.push(
  8143. SessionEventType.TurnStarted,
  8144. { turnNumber: 1, input: "blocked prompt" },
  8145. { turnId: "turn-1" },
  8146. );
  8147. log.push(
  8148. SessionEventType.HookRunStarted,
  8149. {
  8150. descriptor,
  8151. hookEventName: "UserPromptSubmit",
  8152. hookIndex: 0,
  8153. hookCount: 1,
  8154. hookInvocationId: "prompt-hook",
  8155. hookRunId: "prompt-run",
  8156. startedAt: 1_700_000_003_000,
  8157. },
  8158. { turnId: "turn-1" },
  8159. );
  8160. log.push(
  8161. SessionEventType.HookRunBlocked,
  8162. {
  8163. descriptor,
  8164. durationMs: 12,
  8165. hookEventName: "UserPromptSubmit",
  8166. hookIndex: 0,
  8167. hookCount: 1,
  8168. hookInvocationId: "prompt-hook",
  8169. hookRunId: "prompt-run",
  8170. blockReason: "hooks_prompt_block",
  8171. errorMessage:
  8172. "python3: can't open file '/workspace/a.py': [Errno 2] No such file or directory",
  8173. stderrPreview:
  8174. "python3: can't open file '/workspace/a.py': [Errno 2] No such file or directory",
  8175. outcome: "blocked",
  8176. startedAt: 1_700_000_003_000,
  8177. },
  8178. { turnId: "turn-1" },
  8179. );
  8180. log.push(
  8181. SessionEventType.TurnComplete,
  8182. {
  8183. response: "HOOK_PROMPT_BLOCK_REASON",
  8184. tokenCount: 0,
  8185. toolCallCount: 0,
  8186. duration: 12,
  8187. resultType: "success",
  8188. },
  8189. { turnId: "turn-1" },
  8190. );
  8191. const { projection } = runAll(log.events);
  8192. const snapshot = projection.getSnapshot();
  8193. expect(snapshot.control.phase).toBe("completedSuccess");
  8194. expect(snapshot.control.lastError).toMatchObject({
  8195. code: "fault.runtime.hookBlocked",
  8196. message:
  8197. "hooks_prompt_block: python3: can't open file '/workspace/a.py': [Errno 2] No such file or directory",
  8198. detail:
  8199. "Hook block reason: hooks_prompt_block\nHook error: python3: can't open file '/workspace/a.py': [Errno 2] No such file or directory",
  8200. recoverable: false,
  8201. source: "runtime",
  8202. traceId: "trace-1",
  8203. attribution: { source: "runtime", reason: "hook_blocked" },
  8204. });
  8205. });
  8206. it.each([
  8207. [SessionEventType.HookRunCompleted, "success"],
  8208. [SessionEventType.HookRunFailed, "failed"],
  8209. ] as const)("HK09 keeps terminal-only %s as not executed", (terminalType, outcome) => {
  8210. const log = new EventLog();
  8211. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8212. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  8213. log.push(
  8214. terminalType,
  8215. {
  8216. descriptor,
  8217. durationMs: 20,
  8218. hookEventName: "PreToolUse",
  8219. hookIndex: 0,
  8220. hookCount: 1,
  8221. hookInvocationId: `terminal-only-${outcome}`,
  8222. hookRunId: `terminal-only-run-${outcome}`,
  8223. outcome,
  8224. startedAt: 1_700_000_003_000,
  8225. },
  8226. { turnId: "turn-1", timestampMs: 1_700_000_003_020 },
  8227. );
  8228. const row = runAll(log.events)
  8229. .projection.getSnapshot()
  8230. .rows.window.find((candidate) => candidate.kind === "hookInvocation");
  8231. expect(row).toMatchObject({
  8232. executions: [expect.objectContaining({ didExecute: false, outcome })],
  8233. });
  8234. });
  8235. it("HK13 updates a late async terminal in place without reopening the completed turn", () => {
  8236. const log = new EventLog();
  8237. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8238. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  8239. log.push(
  8240. SessionEventType.HookRunStarted,
  8241. {
  8242. descriptor: { ...descriptor, executionMode: "background" },
  8243. hookEventName: "UserPromptSubmit",
  8244. hookIndex: 0,
  8245. hookCount: 1,
  8246. hookInvocationId: "async-hook",
  8247. hookRunId: "async-run",
  8248. startedAt: 1_700_000_003_000,
  8249. },
  8250. { turnId: "turn-1", timestampMs: 1_700_000_003_000 },
  8251. );
  8252. log.push(
  8253. SessionEventType.TurnComplete,
  8254. { response: "done", tokenCount: 1, toolCallCount: 0, duration: 10, resultType: "success" },
  8255. { turnId: "turn-1", timestampMs: 1_700_000_003_010 },
  8256. );
  8257. log.push(
  8258. SessionEventType.HookRunCompleted,
  8259. {
  8260. descriptor: { ...descriptor, executionMode: "background" },
  8261. durationMs: 50,
  8262. hookEventName: "UserPromptSubmit",
  8263. hookIndex: 0,
  8264. hookCount: 1,
  8265. hookInvocationId: "async-hook",
  8266. hookRunId: "async-run",
  8267. outcome: "success",
  8268. startedAt: 1_700_000_003_000,
  8269. },
  8270. { turnId: "turn-1", timestampMs: 1_700_000_003_050 },
  8271. );
  8272. const { deltasPerEvent, projection } = runAll(log.events);
  8273. expect(deltasPerEvent[4]).toContainEqual(
  8274. expect.objectContaining({
  8275. op: "row.upserted",
  8276. row: expect.objectContaining({ hookInvocationId: "async-hook", state: "completed" }),
  8277. }),
  8278. );
  8279. expect(projection.getSnapshot().control.phase).toBe("completedSuccess");
  8280. expect(
  8281. projection
  8282. .getSnapshot()
  8283. .rows.window.filter(
  8284. (row) => row.kind === "hookInvocation" && row.hookInvocationId === "async-hook",
  8285. ),
  8286. ).toHaveLength(1);
  8287. });
  8288. it("HK13 closes an attached started-only execution on a real runtime resume", () => {
  8289. const log = new EventLog();
  8290. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8291. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  8292. log.push(
  8293. SessionEventType.HookRunStarted,
  8294. {
  8295. descriptor,
  8296. hookEventName: "PreToolUse",
  8297. hookIndex: 0,
  8298. hookCount: 1,
  8299. hookInvocationId: "started-only-hook",
  8300. hookRunId: "started-only-run",
  8301. startedAt: 1_700_000_002_000,
  8302. },
  8303. { turnId: "turn-1", timestampMs: 1_700_000_002_000 },
  8304. );
  8305. log.push(SessionEventType.SessionResumed, {}, { timestampMs: 1_700_000_003_000 });
  8306. const row = runAll(log.events)
  8307. .projection.getSnapshot()
  8308. .rows.window.find((candidate) => candidate.kind === "hookInvocation");
  8309. expect(row).toMatchObject({
  8310. state: "failed",
  8311. executions: [
  8312. {
  8313. didExecute: true,
  8314. state: "failed",
  8315. outcome: "cancelled",
  8316. durationMs: 1_000,
  8317. },
  8318. ],
  8319. });
  8320. });
  8321. it("HK17 does not flush a pending SessionStart summary onto a model-only compact turn", () => {
  8322. // Bug 根因:Runtime 的 runSessionStartHooks 先于 /compact 输入解析执行,首条输入即
  8323. // /compact 时 SessionStart Hook 真实执行且携带 compact 的 runtime turnId;投影层
  8324. // flush 只看「下一条 TurnStarted」,把摘要挂到了 model-only 维护 turn 上。
  8325. const log = new EventLog();
  8326. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  8327. log.push(
  8328. SessionEventType.HookRunStarted,
  8329. {
  8330. descriptor,
  8331. hookEventName: "SessionStart",
  8332. hookIndex: 0,
  8333. hookCount: 1,
  8334. hookInvocationId: "startup-hook",
  8335. hookRunId: "startup-run",
  8336. startedAt: 1_700_000_002_000,
  8337. },
  8338. { turnId: "turn-1", timestampMs: 1_700_000_002_000 },
  8339. );
  8340. log.push(
  8341. SessionEventType.HookRunCompleted,
  8342. {
  8343. descriptor,
  8344. durationMs: 10,
  8345. hookEventName: "SessionStart",
  8346. hookIndex: 0,
  8347. hookCount: 1,
  8348. hookInvocationId: "startup-hook",
  8349. hookRunId: "startup-run",
  8350. outcome: "success",
  8351. startedAt: 1_700_000_002_000,
  8352. },
  8353. { turnId: "turn-1", timestampMs: 1_700_000_002_010 },
  8354. );
  8355. // compact 维护 turn:inputVisibility=model-only,无 user bubble。
  8356. log.push(
  8357. SessionEventType.TurnStarted,
  8358. { turnNumber: 1, input: "/compact", inputVisibility: "model-only" },
  8359. { turnId: "turn-1", timestampMs: 1_700_000_003_000 },
  8360. );
  8361. log.push(
  8362. SessionEventType.CompactStarted,
  8363. {
  8364. operationId: "op-1",
  8365. messageId: "msg-compact",
  8366. status: "started",
  8367. trigger: "manual",
  8368. display: "separator",
  8369. },
  8370. { turnId: "turn-1", timestampMs: 1_700_000_003_050 },
  8371. );
  8372. log.push(
  8373. SessionEventType.CompactCompleted,
  8374. {
  8375. operationId: "op-1",
  8376. messageId: "msg-compact",
  8377. status: "completed",
  8378. trigger: "manual",
  8379. display: "separator",
  8380. },
  8381. { turnId: "turn-1", timestampMs: 1_700_000_004_000 },
  8382. );
  8383. log.push(
  8384. SessionEventType.TurnComplete,
  8385. {
  8386. response: "compacted",
  8387. tokenCount: 1,
  8388. toolCallCount: 0,
  8389. duration: 1_000,
  8390. resultType: "success",
  8391. },
  8392. { turnId: "turn-1", timestampMs: 1_700_000_004_050 },
  8393. );
  8394. const afterCompact = runAll(log.events).projection.getSnapshot();
  8395. // compact 维护 turn 不承载 SessionStart 摘要:不得出现挂在 turn-1 的 hook row。
  8396. expect(afterCompact.rows.window.filter((row) => row.kind === "hookInvocation")).toHaveLength(0);
  8397. // 下一条真实 user-visible turn 才是合法收口目标。
  8398. log.push(
  8399. SessionEventType.TurnStarted,
  8400. { turnNumber: 2, input: "next real prompt" },
  8401. { turnId: "turn-2", timestampMs: 1_700_000_005_000 },
  8402. );
  8403. const afterRealTurn = runAll(log.events).projection.getSnapshot();
  8404. const hookRows = afterRealTurn.rows.window.filter((row) => row.kind === "hookInvocation");
  8405. expect(hookRows).toHaveLength(1);
  8406. expect(hookRows[0]).toMatchObject({
  8407. hookEventName: "SessionStart",
  8408. turnId: "turn-2",
  8409. executions: [expect.objectContaining({ didExecute: true })],
  8410. });
  8411. });
  8412. it("HK17 keeps a SessionStart summary pending when a compact turn is the last turn", () => {
  8413. // 只有 /compact 且无后续输入:摘要保持 pending,不挂 compact marker,也不制造
  8414. // 可见时间线内容(session-hooks:* synthetic turn 禁止)。
  8415. const log = new EventLog();
  8416. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  8417. log.push(
  8418. SessionEventType.HookRunStarted,
  8419. {
  8420. descriptor,
  8421. hookEventName: "SessionStart",
  8422. hookIndex: 0,
  8423. hookCount: 1,
  8424. hookInvocationId: "startup-hook",
  8425. hookRunId: "startup-run",
  8426. startedAt: 1_700_000_002_000,
  8427. },
  8428. { turnId: "turn-1", timestampMs: 1_700_000_002_000 },
  8429. );
  8430. log.push(
  8431. SessionEventType.HookRunCompleted,
  8432. {
  8433. descriptor,
  8434. durationMs: 10,
  8435. hookEventName: "SessionStart",
  8436. hookIndex: 0,
  8437. hookCount: 1,
  8438. hookInvocationId: "startup-hook",
  8439. hookRunId: "startup-run",
  8440. outcome: "success",
  8441. startedAt: 1_700_000_002_000,
  8442. },
  8443. { turnId: "turn-1", timestampMs: 1_700_000_002_010 },
  8444. );
  8445. log.push(
  8446. SessionEventType.TurnStarted,
  8447. { turnNumber: 1, input: "/compact", inputVisibility: "model-only" },
  8448. { turnId: "turn-1", timestampMs: 1_700_000_003_000 },
  8449. );
  8450. log.push(
  8451. SessionEventType.TurnComplete,
  8452. {
  8453. response: "compacted",
  8454. tokenCount: 1,
  8455. toolCallCount: 0,
  8456. duration: 1_000,
  8457. resultType: "success",
  8458. },
  8459. { turnId: "turn-1", timestampMs: 1_700_000_004_000 },
  8460. );
  8461. const snapshot = runAll(log.events).projection.getSnapshot();
  8462. expect(snapshot.rows.window.filter((row) => row.kind === "hookInvocation")).toHaveLength(0);
  8463. expect(snapshot.rows.window.map((row) => row.turnId)).not.toContain("session-hooks:session-1");
  8464. });
  8465. it("HK17 keeps tool Hooks of a model-only real agent turn attached to that turn", () => {
  8466. // 回归背景(2026-08-28 review):model-only ≠ 维护 turn。background_task 通知轮
  8467. // (runtime-command-queue)、subagent_message 轮、goal continuation 轮都是
  8468. // inputVisibility="model-only" 但会真实跑工具的 agent 轮。HK17 首版把直挂 gate
  8469. // 无差别地按 currentTurnStartedModelOnly 拦截,导致这些轮的 PreToolUse/PostToolUse
  8470. // 被 pending 吞掉、错误 flush 到下一个不相关用户轮。维护 turn 排除只属于
  8471. // SessionStart;工具 Hook 必须按 event.turnId 直挂原轮,与 cold merge 对齐。
  8472. const log = new EventLog();
  8473. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8474. log.push(
  8475. SessionEventType.TurnStarted,
  8476. {
  8477. turnNumber: 1,
  8478. input: "background task completed, continue",
  8479. inputVisibility: "model-only",
  8480. },
  8481. { turnId: "turn-bg", timestampMs: 1_700_000_001_000 },
  8482. );
  8483. log.push(
  8484. SessionEventType.HookRunStarted,
  8485. {
  8486. descriptor,
  8487. hookEventName: "PreToolUse",
  8488. hookIndex: 0,
  8489. hookCount: 1,
  8490. hookInvocationId: "bg-tool-hook",
  8491. hookRunId: "bg-tool-run",
  8492. startedAt: 1_700_000_002_000,
  8493. toolCallId: "tool-bg",
  8494. toolName: "Write",
  8495. },
  8496. { turnId: "turn-bg", timestampMs: 1_700_000_002_000 },
  8497. );
  8498. log.push(
  8499. SessionEventType.HookRunCompleted,
  8500. {
  8501. descriptor,
  8502. durationMs: 15,
  8503. hookEventName: "PreToolUse",
  8504. hookIndex: 0,
  8505. hookCount: 1,
  8506. hookInvocationId: "bg-tool-hook",
  8507. hookRunId: "bg-tool-run",
  8508. outcome: "success",
  8509. startedAt: 1_700_000_002_000,
  8510. toolCallId: "tool-bg",
  8511. toolName: "Write",
  8512. },
  8513. { turnId: "turn-bg", timestampMs: 1_700_000_002_015 },
  8514. );
  8515. log.push(
  8516. SessionEventType.TurnStarted,
  8517. { turnNumber: 2, input: "unrelated user question" },
  8518. { turnId: "turn-user", timestampMs: 1_700_000_003_000 },
  8519. );
  8520. const hookRows = runAll(log.events)
  8521. .projection.getSnapshot()
  8522. .rows.window.filter((row) => row.kind === "hookInvocation");
  8523. expect(hookRows).toHaveLength(1);
  8524. // 工具 Hook 留在 model-only 真实 agent 轮,不被 pending 迁移到用户轮。
  8525. expect(hookRows[0]).toMatchObject({
  8526. hookEventName: "PreToolUse",
  8527. turnId: "turn-bg",
  8528. anchorToolCallId: "tool-bg",
  8529. executions: [expect.objectContaining({ didExecute: true })],
  8530. });
  8531. });
  8532. it.each([
  8533. {
  8534. caseName: "TurnError",
  8535. terminal: (log: EventLog, turnId: string, at: number) =>
  8536. log.push(
  8537. SessionEventType.TurnError,
  8538. { error: { type: "ProviderError", message: "rate limited" }, turnPhase: "model" },
  8539. { turnId, timestampMs: at },
  8540. ),
  8541. },
  8542. {
  8543. caseName: "TurnComplete(cancelled)",
  8544. terminal: (log: EventLog, turnId: string, at: number) =>
  8545. log.push(
  8546. SessionEventType.TurnComplete,
  8547. {
  8548. response: "",
  8549. tokenCount: 0,
  8550. toolCallCount: 0,
  8551. duration: 100,
  8552. resultType: "cancelled",
  8553. },
  8554. { turnId, timestampMs: at },
  8555. ),
  8556. },
  8557. ])(
  8558. "HK17 keeps a pending SessionStart summary off an abnormally terminated model-only turn ($caseName)",
  8559. ({ terminal }) => {
  8560. // SG-01:currentTurnId / currentTurnStartedModelOnly 是 reducer 内部侧表,
  8561. // 异常终态是最容易遗漏的生命周期边界。TurnError 非 controlOnly 路径不清侧表、
  8562. // TurnComplete(cancelled) 清侧表,两条收口路径必须等价:pending SessionStart
  8563. // 不泄漏到异常 turn、不直挂死 turn、只归位下一条真实用户 turn。
  8564. const sessionStartLifecycle = (log: EventLog, invocationId: string, at: number) => {
  8565. log.push(
  8566. SessionEventType.HookRunStarted,
  8567. {
  8568. descriptor,
  8569. hookEventName: "SessionStart",
  8570. hookIndex: 0,
  8571. hookCount: 1,
  8572. hookInvocationId: invocationId,
  8573. hookRunId: `${invocationId}-run`,
  8574. startedAt: at,
  8575. },
  8576. { turnId: "turn-mt", timestampMs: at },
  8577. );
  8578. log.push(
  8579. SessionEventType.HookRunCompleted,
  8580. {
  8581. descriptor,
  8582. durationMs: 5,
  8583. hookEventName: "SessionStart",
  8584. hookIndex: 0,
  8585. hookCount: 1,
  8586. hookInvocationId: invocationId,
  8587. hookRunId: `${invocationId}-run`,
  8588. outcome: "success",
  8589. startedAt: at,
  8590. },
  8591. { turnId: "turn-mt", timestampMs: at + 5 },
  8592. );
  8593. };
  8594. const log = new EventLog();
  8595. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  8596. // model-only goal continuation 轮(executionKind 缺省为 agent,异常走非 controlOnly)。
  8597. log.push(
  8598. SessionEventType.TurnStarted,
  8599. { turnNumber: 1, input: "continue goal", inputVisibility: "model-only" },
  8600. { turnId: "turn-mt", timestampMs: 1_700_000_001_000 },
  8601. );
  8602. sessionStartLifecycle(log, "startup-hook", 1_700_000_002_000);
  8603. terminal(log, "turn-mt", 1_700_000_003_000);
  8604. // 异常收口瞬间:pending 保留,不挂异常 turn,也不泄漏成可见 row。
  8605. const afterTerminal = runAll(log.events).projection.getSnapshot();
  8606. expect(afterTerminal.rows.window.filter((row) => row.kind === "hookInvocation")).toHaveLength(
  8607. 0,
  8608. );
  8609. expect(afterTerminal.rows.window.map((row) => row.turnId)).not.toContain(
  8610. "session-hooks:session-1",
  8611. );
  8612. // 终态后紧接的下一个 SessionStart(resume epoch)同样必须 pending,
  8613. // 不得直挂已终止的死 turn。
  8614. sessionStartLifecycle(log, "resume-hook", 1_700_000_004_000);
  8615. const afterResumeHook = runAll(log.events).projection.getSnapshot();
  8616. expect(
  8617. afterResumeHook.rows.window.filter((row) => row.kind === "hookInvocation"),
  8618. ).toHaveLength(0);
  8619. // 下一条真实用户 turn 收口两条 pending 摘要,且只出现在该轮。
  8620. log.push(
  8621. SessionEventType.TurnStarted,
  8622. { turnNumber: 2, input: "real question" },
  8623. { turnId: "turn-real", timestampMs: 1_700_000_005_000 },
  8624. );
  8625. const finalRows = runAll(log.events)
  8626. .projection.getSnapshot()
  8627. .rows.window.filter((row) => row.kind === "hookInvocation");
  8628. expect(finalRows.map((row) => [row.hookInvocationId, row.turnId])).toEqual([
  8629. ["startup-hook", "turn-real"],
  8630. ["resume-hook", "turn-real"],
  8631. ]);
  8632. },
  8633. );
  8634. it.each([
  8635. [SessionEventType.HookRunCompleted, { durationMs: 20, outcome: "success" }],
  8636. [SessionEventType.HookRunFailed, { durationMs: 20, outcome: "failed" }],
  8637. ] as const)(
  8638. "HK14 ignores late %s after its Hook branch was rewound",
  8639. (terminalType, terminal) => {
  8640. const log = new EventLog();
  8641. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8642. log.push(
  8643. SessionEventType.TurnStarted,
  8644. { turnNumber: 1, input: "run", messageId: "user-1" },
  8645. { turnId: "turn-1" },
  8646. );
  8647. log.push(
  8648. SessionEventType.ModelStreaming,
  8649. { kind: "text_start", delta: "", done: false, assistantMessageId: "assistant-1" },
  8650. { turnId: "turn-1" },
  8651. );
  8652. log.push(
  8653. SessionEventType.HookRunStarted,
  8654. {
  8655. descriptor,
  8656. hookEventName: "PreToolUse",
  8657. hookIndex: 0,
  8658. hookCount: 1,
  8659. hookInvocationId: "rewound-hook",
  8660. hookRunId: "rewound-run",
  8661. startedAt: 1_700_000_003_000,
  8662. },
  8663. { turnId: "turn-1", timestampMs: 1_700_000_003_000 },
  8664. );
  8665. log.push(SessionEventType.RewindTriggered, {
  8666. targetMessageId: "assistant-1",
  8667. scope: "conversation",
  8668. createdMessageId: "rewind-notice",
  8669. });
  8670. log.push(
  8671. terminalType,
  8672. {
  8673. descriptor,
  8674. hookEventName: "PreToolUse",
  8675. hookIndex: 0,
  8676. hookCount: 1,
  8677. hookInvocationId: "rewound-hook",
  8678. hookRunId: "rewound-run",
  8679. startedAt: 1_700_000_003_000,
  8680. ...terminal,
  8681. },
  8682. { turnId: "turn-1", timestampMs: 1_700_000_003_020 },
  8683. );
  8684. const { deltasPerEvent, projection } = runAll(log.events);
  8685. expect(deltasPerEvent[4]).toContainEqual({
  8686. op: "row.removed",
  8687. fromRowId: expect.any(Number),
  8688. });
  8689. expect(
  8690. projection
  8691. .getSnapshot()
  8692. .rows.window.some(
  8693. (row) => row.kind === "hookInvocation" && row.hookInvocationId === "rewound-hook",
  8694. ),
  8695. ).toBe(false);
  8696. expect(deltasPerEvent[5]).not.toContainEqual(
  8697. expect.objectContaining({
  8698. op: "row.appended",
  8699. row: expect.objectContaining({ hookInvocationId: "rewound-hook" }),
  8700. }),
  8701. );
  8702. },
  8703. );
  8704. it("projects workspace Hook review only as Settings-centered pending interaction", () => {
  8705. const log = new EventLog();
  8706. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8707. const request = {
  8708. kind: "workspaceHookReview",
  8709. reviewFlowId: "flow-1",
  8710. generation: 1,
  8711. interactionId: "interaction-1",
  8712. sessionId: "session-1",
  8713. taskId: "session-1",
  8714. runId: "run-1",
  8715. workspaceIdentity: "local:/workspace",
  8716. workspaceLabel: "workspace",
  8717. bundleDigest: "a".repeat(64),
  8718. createdAt: 1_700_000_001_000,
  8719. deadlineAt: 1_700_000_601_000,
  8720. sourceFiles: [
  8721. {
  8722. path: "/workspace/.zcode/config.json",
  8723. displayPath: ".zcode/config.json",
  8724. editable: true,
  8725. },
  8726. ],
  8727. summary: { eventCount: 1, hookCount: 1, pendingCount: 1 },
  8728. items: [
  8729. {
  8730. reviewItemId: "item-0",
  8731. event: "SessionStart",
  8732. matcher: "startup",
  8733. type: "command",
  8734. displayName: "SessionStart · startup",
  8735. displayCommand: "echo project",
  8736. sourcePath: ".zcode/config.json",
  8737. resolvedTimeoutMs: 60_000,
  8738. resolvedMaxOutputBytes: 32_768,
  8739. executionMode: "foreground",
  8740. configuredEnabled: true,
  8741. editable: true,
  8742. trustState: "pending_trust",
  8743. },
  8744. ],
  8745. warningCode: "workspace_hooks_execute_code",
  8746. } as const;
  8747. log.push(SessionEventType.WorkspaceHookReviewRequested, { request });
  8748. const { projection } = runAll(log.events);
  8749. expect(projection.getSnapshot().pendingInteractions).toEqual([
  8750. {
  8751. interactionId: "interaction-1",
  8752. kind: "workspaceHookReview",
  8753. anchorRowId: null,
  8754. createdAt: request.createdAt,
  8755. payload: request,
  8756. },
  8757. ]);
  8758. log.push(SessionEventType.WorkspaceHookReviewSettled, {
  8759. interactionId: "interaction-1",
  8760. state: "resolved",
  8761. });
  8762. projection.applyEvent(log.events.at(-1)!);
  8763. expect(projection.getSnapshot().pendingInteractions).toEqual([]);
  8764. });
  8765. it("superseded review generation removes only the stale interaction", () => {
  8766. const log = new EventLog();
  8767. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8768. const base = {
  8769. kind: "workspaceHookReview",
  8770. reviewFlowId: "flow-1",
  8771. sessionId: "session-1",
  8772. taskId: "session-1",
  8773. runId: "run-1",
  8774. workspaceIdentity: "local:/workspace",
  8775. workspaceLabel: "workspace",
  8776. createdAt: 1_700_000_001_000,
  8777. deadlineAt: 1_700_000_601_000,
  8778. sourceFiles: [],
  8779. summary: { eventCount: 0, hookCount: 0, pendingCount: 0 },
  8780. items: [],
  8781. warningCode: "workspace_hooks_execute_code",
  8782. } as const;
  8783. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  8784. request: {
  8785. ...base,
  8786. generation: 1,
  8787. interactionId: "interaction-1",
  8788. bundleDigest: "a".repeat(64),
  8789. },
  8790. });
  8791. log.push(SessionEventType.WorkspaceHookReviewSuperseded, {
  8792. interactionId: "interaction-1",
  8793. supersededByInteractionId: "interaction-2",
  8794. });
  8795. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  8796. request: {
  8797. ...base,
  8798. generation: 2,
  8799. interactionId: "interaction-2",
  8800. bundleDigest: "b".repeat(64),
  8801. },
  8802. });
  8803. const { projection } = runAll(log.events);
  8804. expect(projection.getSnapshot().pendingInteractions.map((item) => item.interactionId)).toEqual([
  8805. "interaction-2",
  8806. ]);
  8807. });
  8808. it("treats SessionResumed and the next requested review as a new runtime authority", () => {
  8809. const log = new EventLog();
  8810. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8811. const base = {
  8812. kind: "workspaceHookReview",
  8813. sessionId: "session-1",
  8814. taskId: "session-1",
  8815. runId: "run-1",
  8816. workspaceIdentity: "local:/workspace",
  8817. workspaceLabel: "workspace",
  8818. createdAt: 1_700_000_001_000,
  8819. deadlineAt: 1_700_000_601_000,
  8820. sourceFiles: [],
  8821. summary: { eventCount: 0, hookCount: 0, pendingCount: 0 },
  8822. items: [],
  8823. warningCode: "workspace_hooks_execute_code",
  8824. } as const;
  8825. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  8826. request: {
  8827. ...base,
  8828. reviewFlowId: "old-runtime-flow",
  8829. generation: 7,
  8830. interactionId: "old-runtime-interaction",
  8831. bundleDigest: "a".repeat(64),
  8832. },
  8833. });
  8834. log.push(SessionEventType.SessionResumed, {});
  8835. const { projection } = runAll(log.events);
  8836. expect(projection.getSnapshot().pendingInteractions).toEqual([]);
  8837. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  8838. request: {
  8839. ...base,
  8840. reviewFlowId: "new-runtime-flow",
  8841. generation: 1,
  8842. interactionId: "new-runtime-interaction",
  8843. bundleDigest: "b".repeat(64),
  8844. createdAt: 1_700_000_002_000,
  8845. deadlineAt: 1_700_000_602_000,
  8846. },
  8847. });
  8848. projection.applyEvent(log.events.at(-1)!);
  8849. expect(projection.getSnapshot().pendingInteractions.map((item) => item.interactionId)).toEqual([
  8850. "new-runtime-interaction",
  8851. ]);
  8852. });
  8853. it("ignores a different review flow until SessionResumed establishes a new runtime epoch", () => {
  8854. const log = new EventLog();
  8855. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8856. const base = {
  8857. kind: "workspaceHookReview",
  8858. generation: 1,
  8859. sessionId: "session-1",
  8860. taskId: "session-1",
  8861. runId: "run-1",
  8862. workspaceIdentity: "local:/workspace",
  8863. workspaceLabel: "workspace",
  8864. createdAt: 1_700_000_001_000,
  8865. deadlineAt: 1_700_000_601_000,
  8866. sourceFiles: [],
  8867. summary: { eventCount: 0, hookCount: 0, pendingCount: 0 },
  8868. items: [],
  8869. warningCode: "workspace_hooks_execute_code",
  8870. } as const;
  8871. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  8872. request: {
  8873. ...base,
  8874. reviewFlowId: "old-flow",
  8875. interactionId: "old-interaction",
  8876. bundleDigest: "a".repeat(64),
  8877. },
  8878. });
  8879. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  8880. request: {
  8881. ...base,
  8882. reviewFlowId: "new-flow",
  8883. interactionId: "new-interaction",
  8884. bundleDigest: "b".repeat(64),
  8885. createdAt: 1_700_000_002_000,
  8886. deadlineAt: 1_700_000_602_000,
  8887. },
  8888. });
  8889. const { projection } = runAll(log.events);
  8890. expect(projection.getSnapshot().pendingInteractions.map((item) => item.interactionId)).toEqual([
  8891. "old-interaction",
  8892. ]);
  8893. });
  8894. it("ignores equal-generation workspace Hook review requests with a conflicting interaction", () => {
  8895. const log = new EventLog();
  8896. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8897. const base = {
  8898. kind: "workspaceHookReview",
  8899. reviewFlowId: "flow-1",
  8900. generation: 3,
  8901. sessionId: "session-1",
  8902. taskId: "session-1",
  8903. runId: "run-1",
  8904. workspaceIdentity: "local:/workspace",
  8905. workspaceLabel: "workspace",
  8906. createdAt: 1_700_000_001_000,
  8907. deadlineAt: 1_700_000_601_000,
  8908. sourceFiles: [],
  8909. summary: { eventCount: 0, hookCount: 0, pendingCount: 0 },
  8910. items: [],
  8911. warningCode: "workspace_hooks_execute_code",
  8912. } as const;
  8913. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  8914. request: {
  8915. ...base,
  8916. interactionId: "interaction-authority",
  8917. bundleDigest: "a".repeat(64),
  8918. },
  8919. });
  8920. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  8921. request: {
  8922. ...base,
  8923. interactionId: "interaction-conflict",
  8924. bundleDigest: "b".repeat(64),
  8925. },
  8926. });
  8927. const { projection } = runAll(log.events);
  8928. expect(projection.getSnapshot().pendingInteractions.map((item) => item.interactionId)).toEqual([
  8929. "interaction-authority",
  8930. ]);
  8931. });
  8932. it("does not project hidden internal or legacy lifecycle events", () => {
  8933. const log = new EventLog();
  8934. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8935. log.push(SessionEventType.HookRunStarted, {
  8936. descriptor: {
  8937. ...descriptor,
  8938. clientVisible: false,
  8939. sourceKind: "internal",
  8940. },
  8941. hookEventName: "SessionStart",
  8942. hookIndex: 0,
  8943. hookCount: 0,
  8944. hookInvocationId: "mailbox-hook",
  8945. hookRunId: "mailbox-run",
  8946. startedAt: 1_700_000_002_000,
  8947. });
  8948. log.push(SessionEventType.HookRunStarted, {
  8949. hookEventName: "SessionStart",
  8950. hookIndex: 0,
  8951. hookRunId: "legacy-run",
  8952. });
  8953. const { projection } = runAll(log.events);
  8954. expect(projection.getSnapshot().rows.window).not.toContainEqual(
  8955. expect.objectContaining({ kind: "hookInvocation" }),
  8956. );
  8957. });
  8958. });
  8959. describe("软门禁(D2): workspaceHookAdmission snapshot 投影", () => {
  8960. it("WorkspaceHookAdmissionUpdated pendingCount>0 写入 snapshot.workspaceHookAdmission", () => {
  8961. const log = new EventLog();
  8962. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8963. log.push(SessionEventType.WorkspaceHookAdmissionUpdated, {
  8964. pendingCount: 2,
  8965. bundleDigest: "a".repeat(64),
  8966. workspaceIdentity: "local:/workspace",
  8967. });
  8968. const { projection } = runAll(log.events);
  8969. expect(projection.getSnapshot().workspaceHookAdmission).toEqual({
  8970. pendingCount: 2,
  8971. bundleDigest: "a".repeat(64),
  8972. workspaceIdentity: "local:/workspace",
  8973. });
  8974. });
  8975. it("WorkspaceHookAdmissionUpdated pendingCount===0 → 置 null(提示条消失)", () => {
  8976. const log = new EventLog();
  8977. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8978. // 先有 pending
  8979. log.push(SessionEventType.WorkspaceHookAdmissionUpdated, {
  8980. pendingCount: 1,
  8981. bundleDigest: "a".repeat(64),
  8982. });
  8983. // settle 后清零
  8984. log.push(SessionEventType.WorkspaceHookAdmissionUpdated, {
  8985. pendingCount: 0,
  8986. bundleDigest: "a".repeat(64),
  8987. });
  8988. const { projection } = runAll(log.events);
  8989. expect(projection.getSnapshot().workspaceHookAdmission).toBeNull();
  8990. });
  8991. it("SessionResumed epoch 清理 → workspaceHookAdmission 置 null(resume 后 activate 重新上报)", () => {
  8992. const log = new EventLog();
  8993. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8994. log.push(SessionEventType.WorkspaceHookAdmissionUpdated, {
  8995. pendingCount: 3,
  8996. bundleDigest: "a".repeat(64),
  8997. workspaceIdentity: "local:/workspace",
  8998. });
  8999. log.push(SessionEventType.SessionResumed, {});
  9000. const { projection } = runAll(log.events);
  9001. expect(projection.getSnapshot().workspaceHookAdmission).toBeNull();
  9002. });
  9003. it("workspaceIdentity 可选:缺失时 snapshot 字段不含 workspaceIdentity", () => {
  9004. const log = new EventLog();
  9005. log.push(SessionEventType.SessionCreated, { mode: "default" });
  9006. log.push(SessionEventType.WorkspaceHookAdmissionUpdated, {
  9007. pendingCount: 1,
  9008. bundleDigest: "b".repeat(64),
  9009. });
  9010. const { projection } = runAll(log.events);
  9011. expect(projection.getSnapshot().workspaceHookAdmission).toEqual({
  9012. pendingCount: 1,
  9013. bundleDigest: "b".repeat(64),
  9014. });
  9015. expect(projection.getSnapshot().workspaceHookAdmission).not.toHaveProperty("workspaceIdentity");
  9016. });
  9017. });
  9018. // ── CreateWorkflow 运行确认(docs/dynamic-workflow/launch.md)──
  9019. describe("workflow 运行确认的 ask 预览", () => {
  9020. const causalityGraph = {
  9021. steps: [
  9022. {
  9023. id: "ask#1",
  9024. kind: "ask" as const,
  9025. label: "a",
  9026. line: 2,
  9027. column: 11,
  9028. lane: "actor#1",
  9029. },
  9030. ],
  9031. lanes: [{ id: "actor#1", name: "a" }],
  9032. // 第二层是子代理导向:每阶段一张参与者卡 + 交接边(docs/dynamic-workflow/presentation.md)。
  9033. participants: [
  9034. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] },
  9035. ],
  9036. handoffs: [],
  9037. sink: ["ask#1"],
  9038. };
  9039. function permissionRequestedLog(display?: unknown, toolName = "CreateWorkflow"): EventLog {
  9040. const turnId = "turn-1";
  9041. const log = new EventLog();
  9042. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  9043. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run it" }, { turnId });
  9044. log.push(
  9045. SessionEventType.ToolCallScheduled,
  9046. {
  9047. toolCallId: "tc-1",
  9048. toolName,
  9049. input: { script: "return 1;" },
  9050. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  9051. },
  9052. { turnId },
  9053. );
  9054. log.push(
  9055. SessionEventType.PermissionRequested,
  9056. {
  9057. requestId: "req-1",
  9058. toolCallId: "tc-1",
  9059. toolName,
  9060. riskLevel: "low",
  9061. reason: "createWorkflow.runConfirmation: user must confirm running the analyzed script",
  9062. input: { script: "return 1;" },
  9063. // CreateWorkflow 自 2026-09-11(第 7 轮)起声明会话作用域的免确认;Bash 用例只借
  9064. // 这条日志的形状,策略对它无意义(投影不看工具声明,只看事件上的策略)。
  9065. optionsPolicy: "session-always-allow",
  9066. ...(display === undefined ? {} : { display }),
  9067. },
  9068. { turnId },
  9069. );
  9070. return log;
  9071. }
  9072. it("把事件上的 display 投到 pendingInteraction,并按 optionsPolicy 把 always allow 换成会话免确认", () => {
  9073. const log = permissionRequestedLog({
  9074. kind: "create_workflow",
  9075. ok: true,
  9076. errorCount: 0,
  9077. diagnostics: [],
  9078. causalityGraph,
  9079. });
  9080. const snapshot = runAll(log.events).projection.getSnapshot();
  9081. const toolRow = snapshot.rows.window.find((row) => row.kind === "toolCall");
  9082. expect(toolRow).toMatchObject({
  9083. status: "pendingApproval",
  9084. approvalInteractionId: "req-1",
  9085. });
  9086. expect(snapshot.pendingInteractions).toHaveLength(1);
  9087. const payload = snapshot.pendingInteractions[0]?.payload;
  9088. expect(payload).toMatchObject({
  9089. kind: "permission",
  9090. display: { kind: "create_workflow", ok: true, causalityGraph },
  9091. });
  9092. // 产品裁决:项目级 always allow 被 optionsPolicy 裁掉,第 7 轮换成会话作用域的
  9093. // 免确认;第 4 轮在 v4 追加 Refine(拒绝并附修改意见),列表 = Run / Session / Deny / Refine。
  9094. expect(
  9095. payload?.kind === "permission" && payload.options.map((option) => option.optionId),
  9096. ).toEqual(["allowOnce", "allowSession", "deny", "workflowRefine"]);
  9097. const sessionOption =
  9098. payload?.kind === "permission"
  9099. ? payload.options.find((option) => option.optionId === "allowSession")
  9100. : undefined;
  9101. // wire 上的 kind 是闭集:会话选项映为 allowAlways(GUI 按 name 本地化);optionId 原样,
  9102. // broker 靠它精确命中。response 不带 permissionUpdates(strict schema,见 spec 第 7 轮)。
  9103. expect(sessionOption).toMatchObject({
  9104. kind: "allowAlways",
  9105. label: "Always allow in this session",
  9106. response: { decision: "allow" },
  9107. });
  9108. expect(sessionOption?.response).not.toHaveProperty("permissionUpdates");
  9109. expect(conversationSnapshotSchema.safeParse(snapshot).success).toBe(true);
  9110. const refineOption =
  9111. payload?.kind === "permission"
  9112. ? payload.options.find((option) => option.optionId === "workflowRefine")
  9113. : undefined;
  9114. // 静态 response 是普通 deny:不认识该选项的消费面(bot 直出、无 freeText 应答)
  9115. // 退化为拒绝;反馈升级只发生在 interaction-broker 的 freeText 特判。
  9116. expect(refineOption).toMatchObject({
  9117. kind: "custom",
  9118. label: "Refine",
  9119. response: { decision: "deny" },
  9120. });
  9121. });
  9122. it("Refine 选项只属于 CreateWorkflow:其他工具的权限 ask 不投放", () => {
  9123. const snapshot = runAll(
  9124. permissionRequestedLog(undefined, "Bash").events,
  9125. ).projection.getSnapshot();
  9126. const payload = snapshot.pendingInteractions[0]?.payload;
  9127. expect(payload?.kind).toBe("permission");
  9128. expect(
  9129. payload?.kind === "permission" && payload.options.map((option) => option.optionId),
  9130. ).toEqual(["allowOnce", "allowSession", "deny"]);
  9131. });
  9132. it("no-always-allow 策略(SaveWorkflow)仍只留 Run / Deny", () => {
  9133. const turnId = "turn-1";
  9134. const log = new EventLog();
  9135. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  9136. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "save it" }, { turnId });
  9137. log.push(
  9138. SessionEventType.PermissionRequested,
  9139. {
  9140. requestId: "req-1",
  9141. toolCallId: "tc-1",
  9142. toolName: "SaveWorkflow",
  9143. riskLevel: "low",
  9144. reason: "saveWorkflow.confirmation",
  9145. input: { name: "x", script: "return 1;" },
  9146. optionsPolicy: "no-always-allow",
  9147. },
  9148. { turnId },
  9149. );
  9150. const payload = runAll(log.events).projection.getSnapshot().pendingInteractions[0]?.payload;
  9151. expect(
  9152. payload?.kind === "permission" && payload.options.map((option) => option.optionId),
  9153. ).toEqual(["allowOnce", "deny"]);
  9154. });
  9155. it("没有 display 时保持纯文本 ask,pendingApproval 行为不变", () => {
  9156. const snapshot = runAll(permissionRequestedLog().events).projection.getSnapshot();
  9157. const payload = snapshot.pendingInteractions[0]?.payload;
  9158. expect(payload?.kind).toBe("permission");
  9159. expect(payload && "display" in payload).toBe(false);
  9160. expect(snapshot.rows.window.find((row) => row.kind === "toolCall")).toMatchObject({
  9161. status: "pendingApproval",
  9162. });
  9163. });
  9164. it("协议无法承载的 display kind 不进 ask 载荷", () => {
  9165. // file_diff 不在 v4 display 联合里;直接透传会让快照 schema 解析失败。
  9166. const log = permissionRequestedLog({
  9167. kind: "file_diff",
  9168. filePath: "/workspace/a.ts",
  9169. additions: 1,
  9170. deletions: 0,
  9171. structuredPatch: [],
  9172. });
  9173. const snapshot = runAll(log.events).projection.getSnapshot();
  9174. const payload = snapshot.pendingInteractions[0]?.payload;
  9175. expect(payload && "display" in payload).toBe(false);
  9176. expect(conversationSnapshotSchema.safeParse(snapshot).success).toBe(true);
  9177. });
  9178. });
  9179. // ── dwf 实时运行态:引擎事件 → 会话事件 → workflowRuns 状态键 ──
  9180. // 见 docs/dynamic-workflow/presentation.md「The run state the pane draws」「workflowRuns 形状与界」「终态权威 patch」。
  9181. describe("ProductProjection workflowRuns(dwf 进度投影)", () => {
  9182. const RUN_ID = "dwfrun-1";
  9183. function progress(
  9184. log: EventLog,
  9185. eventType: string,
  9186. payload: Record<string, unknown>,
  9187. extra: Record<string, unknown> = {},
  9188. ): SessionEvent {
  9189. return log.push(SessionEventType.DynamicWorkflowRunProgress, {
  9190. runId: RUN_ID,
  9191. toolCallId: "tc-1",
  9192. // sequence 是 journal sequence(appendEvent 从 0 起单调分配)。
  9193. sequence: (progressSequence[RUN_ID] = (progressSequence[RUN_ID] ?? -1) + 1),
  9194. eventType,
  9195. payload,
  9196. ...extra,
  9197. });
  9198. }
  9199. const progressSequence: Record<string, number> = {};
  9200. function startedLog(caps: Record<string, unknown> = { maxConcurrency: 4 }): EventLog {
  9201. progressSequence[RUN_ID] = -1;
  9202. const log = new EventLog();
  9203. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  9204. progress(log, "run-started", { runId: RUN_ID, caps });
  9205. return log;
  9206. }
  9207. function runsOf(log: EventLog) {
  9208. return runAll(log.events).projection.getSnapshot().workflowRuns;
  9209. }
  9210. it("run-started 建条目:状态 running,用量归零,快照过 strict schema", () => {
  9211. const log = startedLog({ maxConcurrency: 2 });
  9212. const snapshot = runAll(log.events).projection.getSnapshot();
  9213. expect(snapshot.workflowRuns).toMatchObject({
  9214. revision: 1,
  9215. runs: [
  9216. {
  9217. runId: RUN_ID,
  9218. toolCallId: "tc-1",
  9219. status: "running",
  9220. usage: { spentTokens: 0, nodesUsed: 0 },
  9221. actors: [],
  9222. nodes: [],
  9223. lastEventSequence: 0,
  9224. },
  9225. ],
  9226. });
  9227. expect(conversationSnapshotSchema.safeParse(snapshot).success).toBe(true);
  9228. });
  9229. it("节点相位按 (siteId, ordinal) upsert,不新增条目", () => {
  9230. const log = startedLog();
  9231. progress(log, "node-queued", {
  9232. instance: { siteId: "ask#1", ordinal: 1 },
  9233. kind: "ask",
  9234. actor: { siteId: "actor#1", ordinal: 1 },
  9235. actorSeq: 1,
  9236. });
  9237. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9238. progress(log, "node-repairing", {
  9239. instance: { siteId: "ask#1", ordinal: 1 },
  9240. attempt: 1,
  9241. violations: [],
  9242. });
  9243. progress(log, "node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" });
  9244. const runs = runsOf(log);
  9245. expect(runs?.runs[0]?.nodes).toEqual([
  9246. {
  9247. siteId: "ask#1",
  9248. ordinal: 1,
  9249. kind: "ask",
  9250. phase: "settled",
  9251. outcome: "ok",
  9252. actorSiteId: "actor#1",
  9253. actorOrdinal: 1,
  9254. },
  9255. ]);
  9256. });
  9257. it("cached 命中只发 node-settled(无 node-queued),kind 因此缺省而条目仍成立", () => {
  9258. const log = startedLog();
  9259. progress(log, "node-settled", {
  9260. instance: { siteId: "world-read#1", ordinal: 1 },
  9261. outcome: "ok",
  9262. cached: true,
  9263. });
  9264. expect(runsOf(log)?.runs[0]?.nodes).toEqual([
  9265. { siteId: "world-read#1", ordinal: 1, phase: "settled", outcome: "ok", cached: true },
  9266. ]);
  9267. });
  9268. it("actor-created 建 actor,其状态由自己的节点派生(三态:waiting / running / completed,决策 39)", () => {
  9269. const log = startedLog();
  9270. progress(
  9271. log,
  9272. "actor-created",
  9273. { actor: { siteId: "actor#1", ordinal: 1 }, name: "planner" },
  9274. { actorSessionId: "sess_dwf-1-actor.1" },
  9275. );
  9276. expect(runsOf(log)?.runs[0]?.actors).toEqual([
  9277. {
  9278. siteId: "actor#1",
  9279. ordinal: 1,
  9280. name: "planner",
  9281. sessionId: "sess_dwf-1-actor.1",
  9282. // 尚无节点且 run 未终态 → waiting("还没派到活"),不是 completed。
  9283. status: "waiting",
  9284. },
  9285. ]);
  9286. progress(log, "node-queued", {
  9287. instance: { siteId: "ask#1", ordinal: 1 },
  9288. kind: "ask",
  9289. actor: { siteId: "actor#1", ordinal: 1 },
  9290. });
  9291. // dispatched 只是会话就绪、请求尚未准入(docs/dynamic-workflow/concurrency.md「Protocol state」):仍是 waiting。
  9292. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9293. expect(runsOf(log)?.runs[0]?.actors[0]?.status).toBe("waiting");
  9294. // 模型请求真的发出去了 → running。
  9295. progress(log, "node-executing", { instance: { siteId: "ask#1", ordinal: 1 } });
  9296. expect(runsOf(log)?.runs[0]?.actors[0]?.status).toBe("running");
  9297. progress(log, "node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" });
  9298. expect(runsOf(log)?.runs[0]?.actors[0]?.status).toBe("completed");
  9299. });
  9300. it("用量:spentTokens 直接取 usage-updated 载荷,nodesUsed 按实例首次派发计数", () => {
  9301. // docs/dynamic-workflow/authoring.md:事件自带已花总量(不再是剩余量 + 派生字段),
  9302. // 步数由派发事件计数(不再从上限反算——没有上限了)。同一实例重复派发不重复计数。
  9303. const log = startedLog({ maxConcurrency: 4 });
  9304. progress(log, "usage-updated", { spentTokens: 1_234 });
  9305. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9306. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9307. progress(log, "node-dispatched", { instance: { siteId: "ask#2", ordinal: 1 } });
  9308. expect(runsOf(log)?.runs[0]?.usage).toEqual({
  9309. spentTokens: 1_234,
  9310. nodesUsed: 2,
  9311. });
  9312. });
  9313. /**
  9314. * 终态事件产**一条** `workflowRun.updated`,把这条 run 的结算事实(status / error)一次落地。
  9315. *
  9316. * 这里刻意不再断言「终态 patch 是整键替换、丢光中间态也能收口」:改成键级增量之后,丢失的
  9317. * 中间 op 不再被下一条事件顺带补回来——那份自愈让位给了帧的 seq 连续性判定与 snapshot 重同步
  9318. * (客户端 fromSeq 对不上就整份重取)。终态事实照旧在这一条 op 里,一条也没少。
  9319. */
  9320. it("run-settled 产一条该 run 的键级增量:结算事实一次落地", () => {
  9321. const log = startedLog();
  9322. progress(log, "node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" });
  9323. const settled = progress(log, "run-settled", {
  9324. status: "errored",
  9325. error: { code: "ReportCapExceeded", message: "报告条数超过上限" },
  9326. });
  9327. const { projection, deltasPerEvent } = runAll(log.events);
  9328. const terminalDeltas = deltasPerEvent[log.events.indexOf(settled)]!;
  9329. expect(terminalDeltas).toHaveLength(1);
  9330. const updated = terminalDeltas[0]!;
  9331. expect(updated.op).toBe("workflowRun.updated");
  9332. const op = updated as {
  9333. op: "workflowRun.updated";
  9334. runId: string;
  9335. revision: number;
  9336. run?: { status?: string; error?: string };
  9337. nodes?: unknown[];
  9338. };
  9339. expect(op.runId).toBe(RUN_ID);
  9340. expect(op.run).toMatchObject({ status: "errored", error: "报告条数超过上限" });
  9341. // 节点这一步没动,所以这条增量里一条节点都不带——线上的字节与**改动量**成正比。
  9342. expect(op.nodes).toBeUndefined();
  9343. expect(op.revision).toBe(projection.getSnapshot().workflowRuns?.revision);
  9344. const run = projection.getSnapshot().workflowRuns?.runs[0];
  9345. expect(run?.status).toBe("errored");
  9346. expect(run?.nodes).toHaveLength(1);
  9347. });
  9348. it("resume:同 runId 再收 run-started 时清掉上一世的 error(进程内 cancel→resume)", () => {
  9349. // run-started 分支原样展开旧条目:cancel → resume 不经重启时,run 以 running 重现
  9350. // 却还挂着上一世的结算错误——一个正在跑的 run 同时展示失败文案。
  9351. const log = startedLog();
  9352. progress(log, "run-settled", {
  9353. status: "stopped",
  9354. stopReason: "interrupted",
  9355. error: { code: "Interrupted", message: "owning process exited" },
  9356. });
  9357. progress(log, "run-started", { runId: RUN_ID, caps: { maxConcurrency: 4 } });
  9358. const runs = runsOf(log)?.runs ?? [];
  9359. expect(runs).toHaveLength(1);
  9360. expect(runs[0]).toMatchObject({ runId: RUN_ID, status: "running" });
  9361. expect(runs[0]?.error).toBeUndefined();
  9362. expect(runs[0]?.resultPreview).toBeUndefined();
  9363. });
  9364. it("revision 单调,lastEventSequence 随 journal sequence 抬升", () => {
  9365. const log = startedLog();
  9366. progress(log, "node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" });
  9367. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9368. const { snapshots } = runAll(log.events);
  9369. const revisions = snapshots
  9370. .map((snapshot) => snapshot.workflowRuns?.revision)
  9371. .filter((revision): revision is number => revision !== undefined);
  9372. expect(revisions).toEqual([1, 2, 3]);
  9373. expect(snapshots.at(-1)?.workflowRuns?.runs[0]?.lastEventSequence).toBe(2);
  9374. });
  9375. it("四个数组的界:nodes 超上限置 truncated 且不再增长,被拒实例进计数器", () => {
  9376. const rejected = 5;
  9377. const log = startedLog();
  9378. for (let ordinal = 1; ordinal <= WORKFLOW_RUNS_LIMITS.maxNodes + rejected; ordinal += 1) {
  9379. progress(log, "node-queued", { instance: { siteId: "ask#1", ordinal }, kind: "ask" });
  9380. }
  9381. const run = runsOf(log)?.runs[0];
  9382. expect(run?.nodes).toHaveLength(WORKFLOW_RUNS_LIMITS.maxNodes);
  9383. expect(run?.truncated).toBe(true);
  9384. // `truncated` 只说得出「有东西没进来」;到底少了几步要靠计数器,否则读面上的步数
  9385. // 会比真实步数小,而且小多少没人说得清。
  9386. expect(run?.usage.nodesUnlisted).toBe(rejected);
  9387. expect(run?.usage.nodesUnlistedSettled).toBeUndefined();
  9388. // 读面唯一允许的步数读法 = 表内 + 表外。
  9389. expect(workflowRunStepCounts(run!)).toEqual({
  9390. total: WORKFLOW_RUNS_LIMITS.maxNodes + rejected,
  9391. settled: 0,
  9392. });
  9393. // 已在表内的实例仍可继续更新相位(超界只拒绝**新**实例)。
  9394. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9395. expect(runsOf(log)?.runs[0]?.nodes[0]?.phase).toBe("dispatched");
  9396. // 表外实例的结算同样要数得出来:它一条节点行都没有,只能落在第二个计数器上。
  9397. progress(log, "node-settled", {
  9398. instance: { siteId: "ask#1", ordinal: WORKFLOW_RUNS_LIMITS.maxNodes + 1 },
  9399. outcome: "ok",
  9400. });
  9401. const settledRun = runsOf(log)!.runs[0]!;
  9402. expect(settledRun.usage.nodesUnlistedSettled).toBe(1);
  9403. expect(workflowRunStepCounts(settledRun)).toEqual({
  9404. total: WORKFLOW_RUNS_LIMITS.maxNodes + rejected,
  9405. settled: 1,
  9406. });
  9407. });
  9408. /**
  9409. * 一条引擎事件 → **一条**该 run 的键级增量,且只带动过的那条节点。
  9410. *
  9411. * 这一条是整次改造的验收点:旧编码在这里会重发整张表(此处 16 条节点),线上的字节因此与
  9412. * 状态大小成正比而不是与改动量成正比——O(N) 字节/事件、O(N²)/run,节点上界与宽 fan-out
  9413. * 撞界丢实例都是这笔账的下游。
  9414. */
  9415. it("一条事件只发动过的那条节点,别的 run 一个字节都不带", () => {
  9416. const log = startedLog();
  9417. for (let ordinal = 1; ordinal <= 16; ordinal += 1) {
  9418. progress(log, "node-queued", { instance: { siteId: "ask#1", ordinal }, kind: "ask" });
  9419. }
  9420. // 第二条 run:它这一步没变化,所以不该出现在增量里。
  9421. log.push(SessionEventType.DynamicWorkflowRunProgress, {
  9422. runId: "dwfrun-other",
  9423. sequence: 0,
  9424. eventType: "run-started",
  9425. payload: { runId: "dwfrun-other", caps: { maxConcurrency: 1 } },
  9426. });
  9427. const dispatched = progress(log, "node-dispatched", {
  9428. instance: { siteId: "ask#1", ordinal: 7 },
  9429. });
  9430. const { deltasPerEvent, projection } = runAll(log.events);
  9431. const deltas = deltasPerEvent[log.events.indexOf(dispatched)]!;
  9432. expect(deltas).toHaveLength(1);
  9433. const op = deltas[0] as {
  9434. op: string;
  9435. runId: string;
  9436. nodes?: { siteId: string; ordinal: number; phase: string; kind?: string }[];
  9437. run?: Record<string, unknown>;
  9438. actors?: unknown[];
  9439. };
  9440. expect(op.op).toBe("workflowRun.updated");
  9441. expect(op.runId).toBe(RUN_ID);
  9442. expect(op.nodes).toEqual([{ siteId: "ask#1", ordinal: 7, kind: "ask", phase: "dispatched" }]);
  9443. expect(op.actors).toBeUndefined();
  9444. // header 只带真的动过的键(水位与派发计数),不含 nodes/actors 之外的整表。
  9445. expect(Object.keys(op.run ?? {}).toSorted()).toEqual(["lastEventSequence", "usage"]);
  9446. // 增量应用回去之后,权威状态仍是归约本身的产物(契约:逐字节一致)。
  9447. const authoritative = projection.getSnapshot().workflowRuns!;
  9448. expect(authoritative.runs.map((run) => run.runId)).toEqual([RUN_ID, "dwfrun-other"]);
  9449. expect(authoritative.runs[0]!.nodes).toHaveLength(16);
  9450. expect(authoritative.runs[0]!.nodes[6]).toEqual({
  9451. siteId: "ask#1",
  9452. ordinal: 7,
  9453. kind: "ask",
  9454. phase: "dispatched",
  9455. });
  9456. });
  9457. it("run 被条数界淘汰时发 workflowRun.removed(只有生产者淘汰,而且必须说出来)", () => {
  9458. const log = new EventLog();
  9459. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  9460. for (let index = 0; index <= WORKFLOW_RUNS_LIMITS.maxRuns; index += 1) {
  9461. log.push(SessionEventType.DynamicWorkflowRunProgress, {
  9462. runId: `dwfrun-${index}`,
  9463. sequence: 0,
  9464. eventType: "run-started",
  9465. payload: { runId: `dwfrun-${index}`, caps: { maxConcurrency: 1 } },
  9466. });
  9467. }
  9468. const { deltasPerEvent } = runAll(log.events);
  9469. // 第 9 条 run 出生的那一条事件同时淘汰了第 1 条:淘汰先发,出生随后。
  9470. const evicting = deltasPerEvent.at(-1)!;
  9471. expect(evicting.map((delta) => delta.op)).toEqual([
  9472. "workflowRun.removed",
  9473. "workflowRun.updated",
  9474. ]);
  9475. expect((evicting[0] as { runId: string }).runId).toBe("dwfrun-0");
  9476. expect((evicting[1] as { runId: string }).runId).toBe(`dwfrun-${WORKFLOW_RUNS_LIMITS.maxRuns}`);
  9477. });
  9478. it("runs ≤ 8 且按最旧淘汰", () => {
  9479. const log = new EventLog();
  9480. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  9481. for (let index = 0; index < WORKFLOW_RUNS_LIMITS.maxRuns + 3; index += 1) {
  9482. log.push(SessionEventType.DynamicWorkflowRunProgress, {
  9483. runId: `dwfrun-${index}`,
  9484. sequence: 0,
  9485. eventType: "run-started",
  9486. payload: { runId: `dwfrun-${index}`, caps: { maxConcurrency: 1 } },
  9487. });
  9488. }
  9489. const runs = runAll(log.events).projection.getSnapshot().workflowRuns?.runs ?? [];
  9490. expect(runs.map((run) => run.runId)).toEqual([
  9491. "dwfrun-3",
  9492. "dwfrun-4",
  9493. "dwfrun-5",
  9494. "dwfrun-6",
  9495. "dwfrun-7",
  9496. "dwfrun-8",
  9497. "dwfrun-9",
  9498. "dwfrun-10",
  9499. ]);
  9500. });
  9501. it("log 与 usage 事件不进图:它们没有 site id,只进事件日志", () => {
  9502. const log = startedLog();
  9503. progress(log, "log", { message: "开始" });
  9504. const run = runsOf(log)?.runs[0];
  9505. expect(run?.nodes).toEqual([]);
  9506. expect(run?.actors).toEqual([]);
  9507. // 但它仍抬升 lastEventSequence——事件日志需要知道有新内容可取。
  9508. expect(run?.lastEventSequence).toBe(1);
  9509. });
  9510. // R-10:两个 profile 的终态必须逐字节一致,所以 workflowRuns 的增量一条都不能被 profile 过滤
  9511. // 掉(`profiles.ts` 只滤 row.delta)。桌面 continuous 与手机 replayable 收到的是同一串 op。
  9512. it("键级增量不受 delivery profile 门控(记录在案的偏离)", () => {
  9513. const log = startedLog();
  9514. const dispatched = progress(log, "node-dispatched", {
  9515. instance: { siteId: "ask#1", ordinal: 1 },
  9516. });
  9517. const { deltasPerEvent } = runAll(log.events);
  9518. const deltas = deltasPerEvent[log.events.indexOf(dispatched)]!;
  9519. expect(deltas.some((delta) => delta.op === "workflowRun.updated")).toBe(true);
  9520. for (const profile of Object.values(DELIVERY_PROFILES) as DeliveryProfile[]) {
  9521. expect(filterConversationDeltasForProfile(deltas, profile)).toEqual(deltas);
  9522. }
  9523. });
  9524. it("同一 run 的重复事件幂等:内容不变不产 delta", () => {
  9525. const log = startedLog();
  9526. progress(log, "node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" });
  9527. const { projection } = runAll(log.events);
  9528. const before = projection.getSnapshot().workflowRuns?.revision;
  9529. // 同一条事件重放(同 sequence、同内容)。
  9530. const replay = log.events.at(-1)!;
  9531. expect(projection.applyEvent(replay)).toEqual([]);
  9532. expect(projection.getSnapshot().workflowRuns?.revision).toBe(before);
  9533. });
  9534. // ── report 事件 → reports[](docs/dynamic-workflow/presentation.md「The run pane」)──
  9535. // 数据面是详情页 Results 区的全部输入;Results 区本身在 packages/ui 的 jsdom 用例里钉。
  9536. it("report 事件按顺序追加进 reports[]:string 原样,object 走 pretty JSON", () => {
  9537. const log = startedLog();
  9538. progress(log, "report", {
  9539. instance: { siteId: "report#1", ordinal: 1 },
  9540. item: "3 stale imports",
  9541. });
  9542. progress(log, "report", {
  9543. instance: { siteId: "report#2", ordinal: 1 },
  9544. item: { file: "a.ts", severity: "warn" },
  9545. });
  9546. const snapshot = runAll(log.events).projection.getSnapshot();
  9547. expect(snapshot.workflowRuns?.runs[0]?.reports).toEqual([
  9548. { siteId: "report#1", ordinal: 1, preview: "3 stale imports" },
  9549. {
  9550. siteId: "report#2",
  9551. ordinal: 1,
  9552. preview: '{\n "file": "a.ts",\n "severity": "warn"\n}',
  9553. },
  9554. ]);
  9555. expect(conversationSnapshotSchema.safeParse(snapshot).success).toBe(true);
  9556. });
  9557. it("零条 report 时 reports 键整个缺席(Results 区据此整区不渲染)", () => {
  9558. const log = startedLog();
  9559. progress(log, "node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" });
  9560. expect(runsOf(log)?.runs[0]).not.toHaveProperty("reports");
  9561. });
  9562. /**
  9563. * 这一条是 report 与 node 分类的凭证:report 有 site 身份、进 journal、有自己的 RunEvent,
  9564. * 但它**不是 step**。混进 nodes[] 的代价是可观测的——紧凑卡与任务岛的 `settled/observed`
  9565. * 步数读的就是 nodes,一个报得勤的工作流会显得步数虚高,状态叠加也会多亮一格。
  9566. */
  9567. it("report 不进 nodes[]/actors,也不动 nodesUsed;但抬升 lastEventSequence", () => {
  9568. const log = startedLog({ maxConcurrency: 4 });
  9569. progress(log, "node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" });
  9570. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9571. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: "a finding" });
  9572. const run = runsOf(log)?.runs[0];
  9573. expect(run?.nodes.map((node) => node.siteId)).toEqual(["ask#1"]);
  9574. expect(run?.actors).toEqual([]);
  9575. expect(run?.usage.nodesUsed).toBe(1);
  9576. expect(run?.reports).toHaveLength(1);
  9577. // 事件日志要知道有新内容可取,所以水位照常抬升。
  9578. expect(run?.lastEventSequence).toBe(3);
  9579. });
  9580. it("失败结算之后 reports 原样留着:捞回半途产物正是 report 存在的理由", () => {
  9581. const log = startedLog();
  9582. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: "finding 1" });
  9583. progress(log, "run-settled", {
  9584. status: "errored",
  9585. error: { code: "DriverError", message: "boom" },
  9586. });
  9587. const run = runsOf(log)?.runs[0];
  9588. expect(run?.status).toBe("errored");
  9589. expect(run?.reports).toEqual([{ siteId: "report#1", ordinal: 1, preview: "finding 1" }]);
  9590. });
  9591. it("同一 report 事件重放(同 sequence 同内容)不产 delta、不重复条目", () => {
  9592. const log = startedLog();
  9593. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: "once" });
  9594. const { projection } = runAll(log.events);
  9595. const before = projection.getSnapshot().workflowRuns?.revision;
  9596. expect(projection.applyEvent(log.events.at(-1)!)).toEqual([]);
  9597. expect(projection.getSnapshot().workflowRuns?.revision).toBe(before);
  9598. expect(projection.getSnapshot().workflowRuns?.runs[0]?.reports).toHaveLength(1);
  9599. });
  9600. /**
  9601. * 去重键是实例(siteId × ordinal),不是事件 sequence——脚本 replay 时每个 report 调用都会
  9602. * 重跑。所以一条**新 sequence** 却带已见实例的事件只抬水位,绝不把同一条产物列两次。
  9603. */
  9604. it("新 sequence 带已见实例键:水位抬升,条目不重复", () => {
  9605. const log = startedLog();
  9606. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: "once" });
  9607. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: "once" });
  9608. const run = runsOf(log)?.runs[0];
  9609. expect(run?.reports).toEqual([{ siteId: "report#1", ordinal: 1, preview: "once" }]);
  9610. expect(run?.lastEventSequence).toBe(2);
  9611. });
  9612. it("reports 触到 64 条上限:拒绝新条目并置 truncated,已有条目照常更新", () => {
  9613. const log = startedLog();
  9614. for (let ordinal = 1; ordinal <= WORKFLOW_RUNS_LIMITS.maxReports + 3; ordinal += 1) {
  9615. progress(log, "report", {
  9616. instance: { siteId: "report#1", ordinal },
  9617. item: `finding ${ordinal}`,
  9618. });
  9619. }
  9620. const run = runsOf(log)?.runs[0];
  9621. expect(run?.reports).toHaveLength(WORKFLOW_RUNS_LIMITS.maxReports);
  9622. expect(run?.truncated).toBe(true);
  9623. // 先到的条目不被后来的挤掉(淘汰会让读者以为早期发现丢了;界的语义是拒新)。
  9624. expect(run?.reports?.[0]?.preview).toBe("finding 1");
  9625. // 触界之后其余键照常更新:结算与水位都不受影响。
  9626. progress(log, "run-settled", { status: "completed" });
  9627. const settled = runsOf(log)?.runs[0];
  9628. expect(settled?.status).toBe("completed");
  9629. expect(settled?.reports).toHaveLength(WORKFLOW_RUNS_LIMITS.maxReports);
  9630. });
  9631. it("单条预览超界即截断(带省略号),仍过 strict schema", () => {
  9632. const log = startedLog();
  9633. // 载荷有界化已经把单个字符串削到 2048,所以真正会超界的是「键多的对象展开成 pretty JSON」。
  9634. const wide: Record<string, string> = {};
  9635. for (let index = 0; index < 64; index += 1) wide[`key${index}`] = "x".repeat(64);
  9636. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: wide });
  9637. const snapshot = runAll(log.events).projection.getSnapshot();
  9638. const preview = snapshot.workflowRuns?.runs[0]?.reports?.[0]?.preview ?? "";
  9639. expect(preview.length).toBe(WORKFLOW_RUNS_LIMITS.maxReportPreviewLength);
  9640. expect(preview.endsWith("…")).toBe(true);
  9641. expect(conversationSnapshotSchema.safeParse(snapshot).success).toBe(true);
  9642. });
  9643. it("instance 缺失的 report 事件被忽略(不造无身份条目),但仍抬水位", () => {
  9644. const log = startedLog();
  9645. progress(log, "report", { item: "orphan" });
  9646. const run = runsOf(log)?.runs[0];
  9647. expect(run).not.toHaveProperty("reports");
  9648. expect(run?.lastEventSequence).toBe(1);
  9649. });
  9650. });
  9651. // 中枢直接启动已保存工作流(docs/dynamic-workflow/launch.md):controlOnly 启动轮的活投影。
  9652. // TurnStarted(workflow_launch) → turnHeader/userInput 双行 origin=workflowLaunch + 同一份元数据,
  9653. // 无助手行;TurnComplete 收口后 header 变 completed(controlOnly 不下发 running/工时)。
  9654. describe("workflow-direct-launch 启动轮投影", () => {
  9655. const workflowLaunch = {
  9656. runId: "dwfrun-9",
  9657. toolCallId: "launch-abc",
  9658. name: "deep-research",
  9659. scope: "global" as const,
  9660. path: "/home/u/.zcode/workflows/deep-research.ts",
  9661. args: { topic: "adaptive concurrency" },
  9662. description: "Deep-dive a topic",
  9663. };
  9664. function launchEvents(): SessionEvent[] {
  9665. const log = new EventLog();
  9666. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  9667. log.push(
  9668. SessionEventType.TurnStarted,
  9669. {
  9670. turnNumber: 1,
  9671. input: 'Started the saved workflow "deep-research" (global) as run dwfrun-9.',
  9672. messageId: "message-launch-1",
  9673. executionKind: "controlOnly",
  9674. inputSource: "workflow_launch",
  9675. workflowLaunch,
  9676. },
  9677. { turnId: "turn-launch" },
  9678. );
  9679. log.push(
  9680. SessionEventType.TurnComplete,
  9681. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  9682. { turnId: "turn-launch" },
  9683. );
  9684. return log.events;
  9685. }
  9686. it("双行 origin=workflowLaunch 且都带启动元数据,无助手行", () => {
  9687. const snapshot = runAll(launchEvents()).projection.getSnapshot();
  9688. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  9689. const rows = snapshot.rows.window;
  9690. expect(rows.map((row) => row.kind)).toEqual(["turnHeader", "userInput"]);
  9691. const header = rows.find((row) => row.kind === "turnHeader");
  9692. expect(header).toMatchObject({
  9693. origin: "workflowLaunch",
  9694. executionKind: "controlOnly",
  9695. state: "completedSuccess",
  9696. workflowLaunch,
  9697. });
  9698. const userInput = rows.find((row) => row.kind === "userInput");
  9699. expect(userInput).toMatchObject({
  9700. origin: "workflowLaunch",
  9701. text: 'Started the saved workflow "deep-research" (global) as run dwfrun-9.',
  9702. workflowLaunch,
  9703. });
  9704. // controlOnly:不残留 running / activeWorks(旧 UI 会把 0ms 误显示成「已工作 1 秒」)。
  9705. expect(snapshot.control.activeWorks).toEqual([]);
  9706. });
  9707. it("启动轮收口让会话离开 draft:phase 成终态,sessions-index 摘要不再被当 draft 丢弃", () => {
  9708. // 2026-09-14 实机:只有一条 controlOnly 启动轮的会话活投影恒为 draft,task-index syncer 丢弃 draft
  9709. // 摘要,侧栏要等重启(store 种子给出终态 phase)才出现。冷热必须同形。
  9710. const events = launchEvents();
  9711. const { projection } = runAll(events.slice(0, 2));
  9712. expect(projection.getSnapshot().control.phase).toBe("draft");
  9713. projection.applyEvent(events[2]!);
  9714. const control = projection.getSnapshot().control;
  9715. expect(control.phase).toBe("completedSuccess");
  9716. expect(control.sessionEnded).toBe(true);
  9717. expect(control.canStop).toBe(false);
  9718. expect(control.activeWorks).toEqual([]);
  9719. });
  9720. it("非 draft 会话上的 controlOnly 轮照旧不碰 session control", () => {
  9721. const log = new EventLog();
  9722. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  9723. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  9724. log.push(
  9725. SessionEventType.TurnComplete,
  9726. { response: "", tokenCount: 0, toolCallCount: 0, duration: 5, resultType: "cancelled" },
  9727. { turnId: "turn-1" },
  9728. );
  9729. log.push(
  9730. SessionEventType.TurnStarted,
  9731. { turnNumber: 2, input: "/goal x", executionKind: "controlOnly" },
  9732. { turnId: "turn-2" },
  9733. );
  9734. log.push(
  9735. SessionEventType.TurnComplete,
  9736. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  9737. { turnId: "turn-2" },
  9738. );
  9739. const snapshot = runAll(log.events).projection.getSnapshot();
  9740. // 上一轮的中断终态保留,控制轮的 success 不改写它。
  9741. expect(snapshot.control.phase).toBe("completedInterrupted");
  9742. });
  9743. });
  9744. // docs/dynamic-workflow/transcript-and-notifications.md:TurnStarted 上的 epilogueStart 原样落到
  9745. // userInput 行;缺席时行上没有这个键(老转录逐字不变)。
  9746. describe("userInput 行的 epilogueStart(热路径)", () => {
  9747. it("透传 TurnStarted.epilogueStart;缺席不写键", () => {
  9748. const log = new EventLog();
  9749. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  9750. log.push(
  9751. SessionEventType.TurnStarted,
  9752. { turnNumber: 1, input: "Summarize\n\n---\nStandard", epilogueStart: 9 },
  9753. { turnId: "turn-1" },
  9754. );
  9755. log.push(SessionEventType.TurnStarted, { turnNumber: 2, input: "plain" }, { turnId: "turn-2" });
  9756. const { projection } = runAll(log.events);
  9757. const rows = projection.getSnapshot().rows.window.filter((row) => row.kind === "userInput");
  9758. expect(rows[0]).toMatchObject({ text: "Summarize\n\n---\nStandard", epilogueStart: 9 });
  9759. expect(rows[1]).not.toHaveProperty("epilogueStart");
  9760. });
  9761. });