product-projection.test.ts 348 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172
  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. { response: "done", tokenCount: 20, toolCallCount: 1, duration: 3_000, resultType: "success" },
  238. { turnId, timestampMs: 1_700_000_003_000 },
  239. );
  240. const header = runAll(log.events).projection.getSnapshot().rows.window.find(
  241. (row) => row.kind === "turnHeader",
  242. );
  243. expect(header).toMatchObject({
  244. activeMs: 3_000,
  245. modelDurationMs: 400,
  246. toolDurationMs: 900,
  247. otherDurationMs: 1_700,
  248. });
  249. });
  250. it("Highspeed 卡失效降级后只记录 fallback 时间,不改变分享资格", () => {
  251. const log = new EventLog();
  252. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  253. log.push(
  254. SessionEventType.TurnStarted,
  255. {
  256. turnNumber: 1,
  257. input: "accelerated prompt",
  258. messageId: "user-highspeed-expired",
  259. inputId: "command-highspeed-expired",
  260. intent: {
  261. sourceCommandId: "command-highspeed-expired",
  262. queueItemId: "queue-highspeed-expired",
  263. clientId: "desktop",
  264. kind: "sendText",
  265. text: "accelerated prompt",
  266. admissionSeq: 1,
  267. admittedAt: 1_700_000_000_000,
  268. requestedDelivery: "startNow",
  269. admittedDelivery: "startNow",
  270. highspeed: {
  271. schemaVersion: 1,
  272. cardId: "hsc-expired",
  273. taskId: "session-1",
  274. provider: "builtin:bigmodel-coding-plan",
  275. model: "GLM-5.3",
  276. issuedAt: 1_700_000_000_000,
  277. expiresAt: 1_700_000_300_000,
  278. regularTps: 80,
  279. },
  280. },
  281. },
  282. { turnId: "turn-highspeed-expired" },
  283. );
  284. log.push(
  285. SessionEventType.TurnExecutionModelFallback,
  286. {
  287. inputId: "command-highspeed-expired",
  288. reason: "highspeed_card_expired",
  289. fromModelSelection: { providerId: "account:bigmodel-highspeed-card", modelId: "GLM-5.3" },
  290. toModelSelection: { providerId: "builtin:bigmodel-coding-plan", modelId: "GLM-5.3" },
  291. },
  292. { timestampMs: 1_700_000_301_000, turnId: "turn-highspeed-expired" },
  293. );
  294. const { projection } = runAll(log.events);
  295. const row = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput");
  296. expect(row).toMatchObject({
  297. highspeed: { fallbackAt: 1_700_000_301_000, fallbackReason: "highspeed_card_expired" },
  298. });
  299. expect(row?.highspeed).not.toHaveProperty("shareExcludedReason");
  300. });
  301. it("加速请求其他失败的降级同样写入 fallbackAt,并以 fallbackReason 区分提示文案", () => {
  302. // spec §2.2:任何失败都退回;Renderer 按 fallbackReason 选择“卡已到期”或“加速服务不可用”文案。
  303. const log = new EventLog();
  304. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  305. log.push(
  306. SessionEventType.TurnStarted,
  307. {
  308. turnNumber: 1,
  309. input: "accelerated prompt",
  310. messageId: "user-highspeed-failed",
  311. inputId: "command-highspeed-failed",
  312. intent: {
  313. sourceCommandId: "command-highspeed-failed",
  314. queueItemId: "queue-highspeed-failed",
  315. clientId: "desktop",
  316. kind: "sendText",
  317. text: "accelerated prompt",
  318. admissionSeq: 1,
  319. admittedAt: 1_700_000_000_000,
  320. requestedDelivery: "startNow",
  321. admittedDelivery: "startNow",
  322. highspeed: {
  323. schemaVersion: 1,
  324. cardId: "hsc-failed",
  325. taskId: "session-1",
  326. provider: "builtin:bigmodel-coding-plan",
  327. model: "GLM-5.3",
  328. issuedAt: 1_700_000_000_000,
  329. expiresAt: 1_700_000_300_000,
  330. },
  331. },
  332. },
  333. { turnId: "turn-highspeed-failed" },
  334. );
  335. log.push(
  336. SessionEventType.TurnExecutionModelFallback,
  337. {
  338. inputId: "command-highspeed-failed",
  339. reason: "highspeed_request_failed",
  340. fromModelSelection: { providerId: "account:bigmodel-highspeed-card", modelId: "GLM-5.3" },
  341. toModelSelection: { providerId: "builtin:bigmodel-coding-plan", modelId: "GLM-5.3" },
  342. },
  343. { timestampMs: 1_700_000_002_000, turnId: "turn-highspeed-failed" },
  344. );
  345. const { projection } = runAll(log.events);
  346. const row = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput");
  347. expect(row).toMatchObject({
  348. highspeed: { fallbackAt: 1_700_000_002_000, fallbackReason: "highspeed_request_failed" },
  349. });
  350. });
  351. it("Highspeed 流式输出降级时中断废弃内容,并让原模型从新行继续", () => {
  352. const log = new EventLog();
  353. const turnId = "turn-highspeed-stream-fallback";
  354. const projection = new ProductProjection("session-1", "epoch-1");
  355. const apply = (type: SessionEventTypeUnion, payload: unknown): void => {
  356. projection.applyEvent(log.push(type, payload, { turnId }));
  357. };
  358. apply(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  359. apply(SessionEventType.TurnStarted, {
  360. turnNumber: 1,
  361. input: "accelerated prompt",
  362. messageId: "user-highspeed-stream-fallback",
  363. inputId: "command-highspeed-stream-fallback",
  364. intent: {
  365. sourceCommandId: "command-highspeed-stream-fallback",
  366. kind: "sendText",
  367. text: "accelerated prompt",
  368. requestedDelivery: "startNow",
  369. highspeed: {
  370. schemaVersion: 1,
  371. cardId: "hsc-stream-fallback",
  372. taskId: "session-1",
  373. provider: "builtin:bigmodel-coding-plan",
  374. model: "GLM-5.3",
  375. issuedAt: 1_700_000_000_000,
  376. expiresAt: 1_700_000_300_000,
  377. },
  378. },
  379. });
  380. apply(SessionEventType.ModelStreaming, {
  381. kind: "reasoning_delta",
  382. delta: "discarded reasoning",
  383. done: false,
  384. });
  385. apply(SessionEventType.ModelStreaming, {
  386. kind: "text_delta",
  387. delta: "discarded accelerated output",
  388. done: false,
  389. });
  390. apply(SessionEventType.ModelStreaming, {
  391. kind: "tool_input_start",
  392. delta: "",
  393. done: false,
  394. toolCallId: "tool-highspeed-orphan",
  395. toolName: "CreateWorkflow",
  396. });
  397. apply(SessionEventType.ModelStreaming, {
  398. kind: "tool_input_delta",
  399. delta: '{"script":"unfinished',
  400. done: false,
  401. toolCallId: "tool-highspeed-orphan",
  402. });
  403. apply(SessionEventType.TurnExecutionModelFallback, {
  404. inputId: "command-highspeed-stream-fallback",
  405. reason: "highspeed_request_failed",
  406. fromModelSelection: { providerId: "account:zai-highspeed-card", modelId: "GLM-5.3" },
  407. toModelSelection: { providerId: "user-provider", modelId: "user-model" },
  408. });
  409. const discardedRows = projection.getSnapshot().rows.window;
  410. expect(discardedRows.find((row) => row.kind === "reasoning")).toMatchObject({
  411. state: "interrupted",
  412. text: "discarded reasoning",
  413. });
  414. expect(discardedRows.find((row) => row.kind === "assistantText")).toMatchObject({
  415. state: "interrupted",
  416. text: "discarded accelerated output",
  417. });
  418. expect(
  419. discardedRows.find(
  420. (row) => row.kind === "toolCall" && row.toolCallId === "tool-highspeed-orphan",
  421. ),
  422. ).toMatchObject({ status: "cancelled", inputText: '{"script":"unfinished' });
  423. // 部分 provider 不发送 text_start;降级事件也必须清空旧 row identity,避免 delta 拼进废弃输出。
  424. apply(SessionEventType.ModelStreaming, {
  425. kind: "text_delta",
  426. delta: "fresh session-model output",
  427. done: false,
  428. });
  429. expect(
  430. projection
  431. .getSnapshot()
  432. .rows.window.filter((row) => row.kind === "assistantText")
  433. .map((row) => ({ state: row.state, text: row.text })),
  434. ).toEqual([
  435. { state: "interrupted", text: "discarded accelerated output" },
  436. { state: "streaming", text: "fresh session-model output" },
  437. ]);
  438. });
  439. it("终态指标更新是增量合并,不清除同一 Turn 已产生的 fallbackAt", () => {
  440. // CR-02 回归:Highspeed 请求 3402 → TurnExecutionModelFallback 写入 fallbackAt → 普通模型跑完 →
  441. // persistHighspeedTiming 发 HighspeedMetricsUpdated。旧实现整体替换 row.highspeed,payload 又不含
  442. // live 才有的 fallbackAt,降级 Toast 依赖的字段被清掉。
  443. const highspeedMeta = {
  444. schemaVersion: 1,
  445. cardId: "hsc-expired",
  446. taskId: "session-1",
  447. provider: "builtin:bigmodel-coding-plan",
  448. model: "GLM-5.3",
  449. issuedAt: 1_700_000_000_000,
  450. expiresAt: 1_700_000_300_000,
  451. regularTps: 80,
  452. };
  453. const log = new EventLog();
  454. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  455. log.push(
  456. SessionEventType.TurnStarted,
  457. {
  458. turnNumber: 1,
  459. input: "accelerated prompt",
  460. messageId: "user-highspeed-expired",
  461. inputId: "command-highspeed-expired",
  462. intent: {
  463. sourceCommandId: "command-highspeed-expired",
  464. queueItemId: "queue-highspeed-expired",
  465. clientId: "desktop",
  466. kind: "sendText",
  467. text: "accelerated prompt",
  468. admissionSeq: 1,
  469. admittedAt: 1_700_000_000_000,
  470. requestedDelivery: "startNow",
  471. admittedDelivery: "startNow",
  472. highspeed: highspeedMeta,
  473. },
  474. },
  475. { turnId: "turn-highspeed-expired" },
  476. );
  477. log.push(
  478. SessionEventType.TurnExecutionModelFallback,
  479. {
  480. inputId: "command-highspeed-expired",
  481. reason: "highspeed_card_expired",
  482. fromModelSelection: { providerId: "account:bigmodel-highspeed-card", modelId: "GLM-5.3" },
  483. toModelSelection: { providerId: "builtin:bigmodel-coding-plan", modelId: "GLM-5.3" },
  484. },
  485. { timestampMs: 1_700_000_301_000, turnId: "turn-highspeed-expired" },
  486. );
  487. log.push(
  488. SessionEventType.HighspeedMetricsUpdated,
  489. {
  490. entityId: "user-highspeed-expired",
  491. highspeed: {
  492. ...highspeedMeta,
  493. outputTokens: 120,
  494. durationMs: 3_000,
  495. modelDurationMs: 400,
  496. toolDurationMs: 900,
  497. otherDurationMs: 1_700,
  498. },
  499. },
  500. { timestampMs: 1_700_000_305_000, turnId: "turn-highspeed-expired" },
  501. );
  502. const { projection } = runAll(log.events);
  503. const row = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput");
  504. expect(row).toMatchObject({
  505. highspeed: {
  506. fallbackAt: 1_700_000_301_000,
  507. outputTokens: 120,
  508. durationMs: 3_000,
  509. modelDurationMs: 400,
  510. toolDurationMs: 900,
  511. otherDurationMs: 1_700,
  512. },
  513. });
  514. });
  515. it("CUA response 的 reasoning、text 与 tool row 共享 assistantResponseId", () => {
  516. const log = new EventLog();
  517. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  518. log.push(
  519. SessionEventType.TurnStarted,
  520. { turnNumber: 1, input: "检查权限", messageId: "user-cua" },
  521. { turnId: "turn-cua" },
  522. );
  523. log.push(
  524. SessionEventType.ModelStreaming,
  525. {
  526. kind: "reasoning_start",
  527. delta: "",
  528. done: false,
  529. assistantMessageId: "assistant-cua",
  530. partId: "reasoning-cua",
  531. },
  532. { turnId: "turn-cua" },
  533. );
  534. log.push(
  535. SessionEventType.ModelStreaming,
  536. {
  537. kind: "text_start",
  538. delta: "",
  539. done: false,
  540. assistantMessageId: "assistant-cua",
  541. partId: "text-cua",
  542. },
  543. { turnId: "turn-cua" },
  544. );
  545. log.push(
  546. SessionEventType.ModelStreaming,
  547. {
  548. kind: "tool_input_start",
  549. delta: "",
  550. done: false,
  551. assistantMessageId: "assistant-cua",
  552. toolCallId: "call-cua",
  553. toolName: "mcp__computer-use__request_access",
  554. },
  555. { turnId: "turn-cua" },
  556. );
  557. log.push(
  558. SessionEventType.ToolCallScheduled,
  559. {
  560. toolCallId: "call-cua",
  561. assistantMessageId: "assistant-cua",
  562. toolName: "mcp__computer-use__request_access",
  563. input: {},
  564. schedule: { parallelGroups: [["call-cua"]], executionOrder: ["call-cua"] },
  565. },
  566. { turnId: "turn-cua" },
  567. );
  568. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  569. expect(rows.find((row) => row.kind === "reasoning")?.assistantResponseId).toBe("assistant-cua");
  570. expect(rows.find((row) => row.kind === "assistantText")?.assistantResponseId).toBe(
  571. "assistant-cua",
  572. );
  573. expect(rows.find((row) => row.kind === "toolCall")?.assistantResponseId).toBe("assistant-cua");
  574. });
  575. it("preserves topic originals and attachment ownership when replaying accepted turn events", () => {
  576. const source = {
  577. provider: "feishu", botId: "bot", chatId: "group", threadId: "topic",
  578. senderId: "b", senderName: "Bob", messageId: "second",
  579. messages: [
  580. { messageId: "first", senderId: "a", senderName: "Alice", text: "First", attachmentIndexes: [0], conversationQuotes: [{ text: "Root", senderName: "Root author" }] },
  581. { messageId: "second", senderId: "b", senderName: "Bob", text: "Second", attachmentIndexes: [1] },
  582. ],
  583. };
  584. const log = new EventLog();
  585. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  586. log.push(SessionEventType.TurnStarted, {
  587. turnNumber: 1, input: "combined", messageId: "accepted", inputId: "command",
  588. intent: {
  589. sourceCommandId: "command", kind: "sendText", text: "combined", admissionSeq: 1, admittedAt: 10,
  590. requestedDelivery: "startNow", admittedDelivery: "startNow", botGroupSource: source,
  591. attachmentRefs: [{ ref: "artifact://first", fileName: "first.txt", mime: "text/plain", bytes: 1 },
  592. { ref: "artifact://second", fileName: "second.txt", mime: "text/plain", bytes: 1 }],
  593. },
  594. }, { turnId: "topic-turn" });
  595. const restored = log.events.map((event) => ({ ...event, payload: JSON.parse(JSON.stringify(event.payload)) }));
  596. const snapshot = conversationSnapshotSchema.parse(runAll(restored).projection.getSnapshot());
  597. expect(snapshot.rows.window.find((row) => row.kind === "userInput")).toMatchObject({
  598. botGroupSource: source, attachments: [{ ref: "artifact://first" }, { ref: "artifact://second" }],
  599. });
  600. });
  601. it("TEL06:edit/rerun user row 保留 canonical root sourceCommandId", () => {
  602. const log = new EventLog();
  603. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  604. log.push(
  605. SessionEventType.TurnStarted,
  606. {
  607. turnNumber: 1,
  608. input: "retry prompt",
  609. messageId: "user-retry",
  610. inputId: "command-edit",
  611. foregroundExecutionId: "foreground-edit",
  612. intent: {
  613. sourceCommandId: "command-edit",
  614. queueItemId: "queue-edit",
  615. clientId: "desktop",
  616. kind: "sendText",
  617. text: "retry prompt",
  618. admissionSeq: 2,
  619. admittedAt: 1_700_000_000_000,
  620. requestedDelivery: "startNow",
  621. admittedDelivery: "startNow",
  622. provenance: { sourceCommandId: "command-original" },
  623. },
  624. },
  625. { turnId: "turn-retry" },
  626. );
  627. const { projection } = runAll(log.events);
  628. expect(conversationSnapshotSchema.parse(projection.getSnapshot()).control.activeWorks).toEqual([
  629. expect.objectContaining({
  630. foregroundExecutionId: "foreground-edit",
  631. sourceCommandId: "command-edit",
  632. }),
  633. ]);
  634. expect(
  635. projection.getSnapshot().rows.window.find((row) => row.kind === "userInput"),
  636. ).toMatchObject({
  637. sourceCommandId: "command-edit",
  638. rootSourceCommandId: "command-original",
  639. productTurnId: "user-retry",
  640. });
  641. });
  642. it("PV4-08:只给 completedSuccess 轮尾 assistant 下发 canFork,后续 turn running 时仍稳定", () => {
  643. const log = new EventLog();
  644. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  645. log.push(
  646. SessionEventType.TurnStarted,
  647. { turnNumber: 1, input: "first", messageId: "user-1" },
  648. { turnId: "turn-1" },
  649. );
  650. log.push(
  651. SessionEventType.ModelStreaming,
  652. { kind: "text_start", delta: "", done: false, assistantMessageId: "assistant-1" },
  653. { turnId: "turn-1" },
  654. );
  655. log.push(
  656. SessionEventType.ModelStreaming,
  657. { kind: "text_end", delta: "", done: false },
  658. { turnId: "turn-1" },
  659. );
  660. log.push(
  661. SessionEventType.TurnComplete,
  662. { response: "done", tokenCount: 1, toolCallCount: 0, duration: 1, resultType: "success" },
  663. { turnId: "turn-1" },
  664. );
  665. log.push(
  666. SessionEventType.TurnStarted,
  667. { turnNumber: 2, input: "second", messageId: "user-2" },
  668. { turnId: "turn-2" },
  669. );
  670. const { projection } = runAll(log.events);
  671. const firstAssistant = projection
  672. .getSnapshot()
  673. .rows.window.find((row) => row.kind === "assistantText" && row.turnId === "user-1");
  674. expect(firstAssistant?.actions).toEqual({ canFork: true });
  675. expect(projection.resolveStableForkCandidate(firstAssistant!.rowId)).toEqual({
  676. ok: true,
  677. candidate: {
  678. boundaryMessageId: "assistant-1",
  679. productTurnId: "user-1",
  680. startMessageId: "user-1",
  681. transcriptTurnId: "turn-1",
  682. },
  683. });
  684. expect(projection.getSnapshot().control.phase).toBe("running");
  685. });
  686. it("PV4-08:成功轮固化 fork 能力时不复制并反转完整 rows 窗口", () => {
  687. const log = new EventLog();
  688. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  689. log.push(
  690. SessionEventType.TurnStarted,
  691. { turnNumber: 1, input: "first", messageId: "user-1" },
  692. { turnId: "turn-1" },
  693. );
  694. log.push(
  695. SessionEventType.ModelStreaming,
  696. { kind: "text_start", delta: "", done: false, assistantMessageId: "assistant-1" },
  697. { turnId: "turn-1" },
  698. );
  699. log.push(
  700. SessionEventType.ModelStreaming,
  701. { kind: "text_end", delta: "", done: false },
  702. { turnId: "turn-1" },
  703. );
  704. const { projection } = runAll(log.events);
  705. const reverse = vi.spyOn(Array.prototype, "reverse").mockImplementation(() => {
  706. throw new Error("TurnComplete must not reverse the full rows window");
  707. });
  708. try {
  709. projection.applyEvent(
  710. log.push(
  711. SessionEventType.TurnComplete,
  712. {
  713. response: "done",
  714. tokenCount: 1,
  715. toolCallCount: 0,
  716. duration: 1,
  717. resultType: "success",
  718. },
  719. { turnId: "turn-1" },
  720. ),
  721. );
  722. } finally {
  723. reverse.mockRestore();
  724. }
  725. const assistant = projection
  726. .getSnapshot()
  727. .rows.window.find((row) => row.kind === "assistantText");
  728. expect(assistant?.actions?.canFork).toBe(true);
  729. });
  730. it("PV4-08:中间 assistant 段和 interrupted turn 都不可 fork", () => {
  731. const log = new EventLog();
  732. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  733. log.push(
  734. SessionEventType.TurnStarted,
  735. { turnNumber: 1, input: "first", messageId: "user-1" },
  736. { turnId: "turn-1" },
  737. );
  738. log.push(
  739. SessionEventType.ModelStreaming,
  740. { kind: "text_start", delta: "", done: false, assistantMessageId: "assistant-1a" },
  741. { turnId: "turn-1" },
  742. );
  743. log.push(
  744. SessionEventType.ModelStreaming,
  745. { kind: "text_end", delta: "", done: false },
  746. { turnId: "turn-1" },
  747. );
  748. log.push(
  749. SessionEventType.ModelStreaming,
  750. { kind: "text_start", delta: "", done: false, assistantMessageId: "assistant-1b" },
  751. { turnId: "turn-1" },
  752. );
  753. log.push(
  754. SessionEventType.TurnComplete,
  755. {
  756. response: "partial",
  757. tokenCount: 1,
  758. toolCallCount: 0,
  759. duration: 1,
  760. resultType: "cancelled",
  761. },
  762. { turnId: "turn-1" },
  763. );
  764. const { projection } = runAll(log.events);
  765. const assistants = projection
  766. .getSnapshot()
  767. .rows.window.filter((row) => row.kind === "assistantText");
  768. expect(assistants.every((row) => row.actions?.canFork !== true)).toBe(true);
  769. expect(projection.resolveStableForkCandidate(assistants[0]!.rowId)).toEqual({
  770. ok: false,
  771. reasonCode: "guard.forkTargetNotStable",
  772. });
  773. expect(projection.resolveStableForkCandidate(assistants[1]!.rowId)).toEqual({
  774. ok: false,
  775. reasonCode: "guard.forkTargetNotStable",
  776. });
  777. });
  778. it("OTC08:同一 turn 的 output-limit Continue 只投影一条累计 assistantText", () => {
  779. const log = new EventLog();
  780. const turnId = "turn-output-continue";
  781. const appendAssistantResponse = (
  782. assistantMessageId: string,
  783. partId: string,
  784. text: string,
  785. stopReason: "length" | "end_turn",
  786. ) => {
  787. log.push(
  788. SessionEventType.ModelStreaming,
  789. {
  790. kind: "text_start",
  791. delta: "",
  792. done: false,
  793. assistantMessageId,
  794. partId,
  795. },
  796. { turnId },
  797. );
  798. log.push(
  799. SessionEventType.ModelStreaming,
  800. { kind: "text_delta", delta: text, done: false, assistantMessageId, partId },
  801. { turnId },
  802. );
  803. log.push(
  804. SessionEventType.ModelStreaming,
  805. { kind: "text_end", delta: "", done: false, assistantMessageId, partId },
  806. { turnId },
  807. );
  808. log.push(
  809. SessionEventType.ModelComplete,
  810. {
  811. content: text,
  812. stopReason,
  813. querySource: "main_turn",
  814. toolCallCount: 0,
  815. usage: {
  816. inputTokens: 1,
  817. outputTokens: 1,
  818. cacheReadTokens: 0,
  819. cacheWriteTokens: 0,
  820. },
  821. },
  822. { turnId },
  823. );
  824. };
  825. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  826. log.push(
  827. SessionEventType.TurnStarted,
  828. { turnNumber: 1, input: "写一段长回复", messageId: "user-output-continue" },
  829. { turnId },
  830. );
  831. appendAssistantResponse("assistant-p1", "part-p1", "即使底层已经", "length");
  832. appendAssistantResponse("assistant-p2", "part-p2", "发起新的请求并停在", "length");
  833. appendAssistantResponse("assistant-p3", "part-p3", "一个尚未完成的位置。", "end_turn");
  834. log.push(
  835. SessionEventType.TurnComplete,
  836. {
  837. response: "一个尚未完成的位置。",
  838. tokenCount: 3,
  839. toolCallCount: 0,
  840. duration: 3_000,
  841. resultType: "success",
  842. },
  843. { turnId },
  844. );
  845. const { projection, deltasPerEvent } = runAll(log.events);
  846. const assistantRows = projection
  847. .getSnapshot()
  848. .rows.window.filter((row) => row.kind === "assistantText");
  849. expect(assistantRows).toHaveLength(1);
  850. expect(assistantRows[0]).toMatchObject({
  851. text: "即使底层已经发起新的请求并停在一个尚未完成的位置。",
  852. state: "complete",
  853. assistantResponseId: "assistant-p3",
  854. entityId: "assistant-p3",
  855. actions: { canFork: true },
  856. });
  857. expect(
  858. deltasPerEvent
  859. .flat()
  860. .filter((delta) => delta.op === "row.appended" && delta.row.kind === "assistantText"),
  861. ).toHaveLength(1);
  862. expect(projection.getMessageIdForRow(assistantRows[0]!.rowId)).toBe("assistant-p3");
  863. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  864. expect(projection.getMessageIdsForTurnRow(header!.rowId)).toEqual(
  865. expect.arrayContaining([
  866. "user-output-continue",
  867. "assistant-p1",
  868. "assistant-p2",
  869. "assistant-p3",
  870. ]),
  871. );
  872. });
  873. it("OTC08:异步 session-title ModelComplete 不清除主 turn 的 Continue 资格", () => {
  874. const log = new EventLog();
  875. const turnId = "turn-output-continue-with-title-sidecar";
  876. const appendAssistantResponse = (
  877. assistantMessageId: string,
  878. text: string,
  879. stopReason: "length" | "end_turn",
  880. ) => {
  881. log.push(
  882. SessionEventType.ModelStreaming,
  883. { kind: "text_start", delta: "", done: false, assistantMessageId },
  884. { turnId },
  885. );
  886. log.push(
  887. SessionEventType.ModelStreaming,
  888. { kind: "text_delta", delta: text, done: false, assistantMessageId },
  889. { turnId },
  890. );
  891. log.push(
  892. SessionEventType.ModelStreaming,
  893. { kind: "text_end", delta: "", done: false, assistantMessageId },
  894. { turnId },
  895. );
  896. log.push(
  897. SessionEventType.ModelComplete,
  898. {
  899. content: text,
  900. querySource: "main_turn",
  901. stopReason,
  902. toolCallCount: 0,
  903. usage: {},
  904. },
  905. { turnId },
  906. );
  907. };
  908. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  909. log.push(
  910. SessionEventType.TurnStarted,
  911. { turnNumber: 1, input: "写一段长回复", messageId: "user-output-title-sidecar" },
  912. { turnId },
  913. );
  914. appendAssistantResponse("assistant-title-p1", "主 turn 第一段", "length");
  915. log.push(
  916. SessionEventType.ModelComplete,
  917. {
  918. content: "标题",
  919. querySource: "session_title",
  920. stopReason: "end_turn",
  921. toolCallCount: 0,
  922. usage: {},
  923. },
  924. { turnId },
  925. );
  926. appendAssistantResponse("assistant-title-p2", "继续拼接完成。", "end_turn");
  927. const { projection } = runAll(log.events);
  928. const assistantRows = projection
  929. .getSnapshot()
  930. .rows.window.filter((row) => row.kind === "assistantText");
  931. expect(assistantRows).toHaveLength(1);
  932. expect(assistantRows[0]).toMatchObject({
  933. text: "主 turn 第一段继续拼接完成。",
  934. assistantResponseId: "assistant-title-p2",
  935. state: "complete",
  936. });
  937. });
  938. it.each([
  939. { label: "含工具边界", stopReason: "length", toolCallCount: 1 },
  940. { label: "缺少明确 zero-tool 事实", stopReason: "length", toolCallCount: undefined },
  941. { label: "不是 output-limit", stopReason: "end_turn", toolCallCount: 0 },
  942. ] as const)("OTC08:$label 时不复用 assistantText row", ({ stopReason, toolCallCount }) => {
  943. const log = new EventLog();
  944. const turnId = `turn-output-boundary-${stopReason}-${String(toolCallCount)}`;
  945. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  946. log.push(
  947. SessionEventType.TurnStarted,
  948. { turnNumber: 1, input: "执行工具", messageId: "user-output-tool-boundary" },
  949. { turnId },
  950. );
  951. log.push(
  952. SessionEventType.ModelStreaming,
  953. {
  954. kind: "text_start",
  955. delta: "",
  956. done: false,
  957. assistantMessageId: "assistant-before-tool",
  958. },
  959. { turnId },
  960. );
  961. log.push(
  962. SessionEventType.ModelStreaming,
  963. { kind: "text_delta", delta: "先执行工具。", done: false },
  964. { turnId },
  965. );
  966. log.push(
  967. SessionEventType.ModelStreaming,
  968. { kind: "text_end", delta: "", done: false },
  969. { turnId },
  970. );
  971. log.push(
  972. SessionEventType.ModelComplete,
  973. {
  974. content: "先执行工具。",
  975. stopReason,
  976. querySource: "main_turn",
  977. ...(toolCallCount === undefined ? {} : { toolCallCount }),
  978. usage: {},
  979. },
  980. { turnId },
  981. );
  982. log.push(
  983. SessionEventType.ModelStreaming,
  984. {
  985. kind: "text_start",
  986. delta: "",
  987. done: false,
  988. assistantMessageId: "assistant-after-tool",
  989. },
  990. { turnId },
  991. );
  992. const { projection } = runAll(log.events);
  993. expect(
  994. projection.getSnapshot().rows.window.filter((row) => row.kind === "assistantText"),
  995. ).toHaveLength(2);
  996. });
  997. it("A:完整成功 turn —— rows 结构、phase、usage、schema 合法", () => {
  998. const log = new EventLog();
  999. basicTurnEvents(log);
  1000. const { projection } = runAll(log.events);
  1001. const snapshot = projection.getSnapshot();
  1002. // schema 合法性(M1 数据模型被 reducer 锤炼的第一道闸)。
  1003. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  1004. const kinds = snapshot.rows.window.map((row) => row.kind);
  1005. expect(kinds).toEqual(["turnHeader", "userInput", "assistantText"]);
  1006. const [header, userInput, assistant] = snapshot.rows.window;
  1007. expect(header).toMatchObject({
  1008. kind: "turnHeader",
  1009. origin: "userInput",
  1010. state: "completedSuccess",
  1011. activeMs: 5000,
  1012. });
  1013. expect(userInput).toMatchObject({
  1014. kind: "userInput",
  1015. text: "写一个 hello world",
  1016. origin: "realUser",
  1017. });
  1018. expect(assistant).toMatchObject({
  1019. kind: "assistantText",
  1020. text: "Hello world",
  1021. state: "complete",
  1022. });
  1023. expect(snapshot.control.phase).toBe("completedSuccess");
  1024. expect(snapshot.control.sessionEnded).toBe(true);
  1025. expect(snapshot.control.canStop).toBe(false);
  1026. expect(snapshot.inputRouting.mode).toBe("startNow");
  1027. expect(snapshot.usage.contextWindow).toEqual({
  1028. usedTokens: 150,
  1029. maxTokens: 200_000,
  1030. autoCompactThresholdTokens: null,
  1031. });
  1032. expect(snapshot.usage.cumulative.inputTokens).toBe(120);
  1033. expect(snapshot.seq).toBe(log.events.length);
  1034. });
  1035. it("A:主轮次 usage 保留 cache 命中率和 context breakdown", () => {
  1036. const log = new EventLog();
  1037. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  1038. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  1039. log.push(
  1040. SessionEventType.ModelComplete,
  1041. {
  1042. content: "done",
  1043. stopReason: "end_turn",
  1044. querySource: "main_turn",
  1045. contextWindow: 200_000,
  1046. usage: {
  1047. inputTokens: 100,
  1048. outputTokens: 20,
  1049. cacheReadTokens: 80,
  1050. cacheWriteTokens: 10,
  1051. },
  1052. cacheHit: {
  1053. inputTokens: 100,
  1054. cacheReadTokens: 80,
  1055. cacheWriteTokens: 10,
  1056. latestHitRate: 0.8,
  1057. hitRate: 0.8,
  1058. hitRateRequestCount: 1,
  1059. totalInputTokens: 100,
  1060. totalCacheReadTokens: 80,
  1061. totalCacheWriteTokens: 10,
  1062. },
  1063. contextUsageBreakdown: [
  1064. { source: "messages", chars: 900 },
  1065. { source: "system_tool_schemas", chars: 100 },
  1066. ],
  1067. },
  1068. { turnId: "turn-1" },
  1069. );
  1070. const { projection } = runAll(log.events);
  1071. const contextWindow = projection.getSnapshot().usage.contextWindow;
  1072. expect(contextWindow?.usedTokens).toBe(120);
  1073. expect(contextWindow?.maxTokens).toBe(200_000);
  1074. expect(contextWindow?.cache).toMatchObject({ hitRate: 0.8, totalCacheReadTokens: 80 });
  1075. expect(contextWindow?.breakdown).toEqual([
  1076. { source: "messages", chars: 900 },
  1077. { source: "system_tool_schemas", chars: 100 },
  1078. ]);
  1079. });
  1080. it("A:sidecar usage 不覆盖输入栏 context cache 和 breakdown", () => {
  1081. const log = new EventLog();
  1082. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  1083. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  1084. log.push(
  1085. SessionEventType.ModelComplete,
  1086. {
  1087. content: "title",
  1088. stopReason: "end_turn",
  1089. querySource: "session_title",
  1090. contextWindow: 200_000,
  1091. usage: {
  1092. inputTokens: 100,
  1093. outputTokens: 20,
  1094. cacheReadTokens: 80,
  1095. cacheWriteTokens: 10,
  1096. },
  1097. cacheHit: {
  1098. inputTokens: 100,
  1099. cacheReadTokens: 80,
  1100. cacheWriteTokens: 10,
  1101. latestHitRate: 0.8,
  1102. hitRate: 0.8,
  1103. hitRateRequestCount: 1,
  1104. totalInputTokens: 100,
  1105. totalCacheReadTokens: 80,
  1106. totalCacheWriteTokens: 10,
  1107. },
  1108. contextUsageBreakdown: [{ source: "messages", chars: 900 }],
  1109. },
  1110. { turnId: "turn-1" },
  1111. );
  1112. const { projection } = runAll(log.events);
  1113. expect(projection.getSnapshot().usage.contextWindow).toBeNull();
  1114. });
  1115. it("A:running 期 inputRouting=enqueue,完成后 startNow", () => {
  1116. const log = new EventLog();
  1117. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1118. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  1119. const { projection } = runAll(log.events);
  1120. expect(projection.getSnapshot().inputRouting.mode).toBe("enqueue");
  1121. // 回归原因:busy 期间 compact 已改为进入 typed FIFO,旧黄金断言仍按直接执行
  1122. // 门禁判为不可用;这里同时补齐标题承诺的完成态路由收口。
  1123. expect(projection.getSnapshot().availability.compact.allowed).toBe(true);
  1124. projection.applyEvent(
  1125. log.push(
  1126. SessionEventType.TurnComplete,
  1127. {
  1128. response: "done",
  1129. tokenCount: 1,
  1130. toolCallCount: 0,
  1131. duration: 100,
  1132. resultType: "success",
  1133. },
  1134. { turnId: "turn-1" },
  1135. ),
  1136. );
  1137. expect(projection.getSnapshot().inputRouting.mode).toBe("startNow");
  1138. });
  1139. it("A:model-only 输入(goal continuation 等)不产生 userInput row", () => {
  1140. const log = new EventLog();
  1141. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1142. log.push(
  1143. SessionEventType.TurnStarted,
  1144. {
  1145. turnNumber: 1,
  1146. input: "continue the goal",
  1147. inputSource: "goal-continuation",
  1148. inputVisibility: "model-only",
  1149. },
  1150. { turnId: "turn-1" },
  1151. );
  1152. const { projection } = runAll(log.events);
  1153. const kinds = projection.getSnapshot().rows.window.map((row) => row.kind);
  1154. expect(kinds).toEqual(["turnHeader"]);
  1155. expect(projection.getSnapshot().rows.window[0]).toMatchObject({
  1156. origin: "goalContinuation",
  1157. });
  1158. });
  1159. it("BG27/BG28:background model-only turn 把结构化标题投影到 turnHeader", () => {
  1160. const log = new EventLog();
  1161. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1162. log.push(
  1163. SessionEventType.TurnStarted,
  1164. {
  1165. turnNumber: 1,
  1166. input: "background result",
  1167. inputSource: "background_task",
  1168. inputVisibility: "model-only",
  1169. originMeta: {
  1170. backgroundSource: "subagent",
  1171. title: "Review the projection chain",
  1172. workId: "agent-review",
  1173. },
  1174. } as never,
  1175. { turnId: "turn-background" },
  1176. );
  1177. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  1178. expect(rows).toHaveLength(1);
  1179. expect(rows[0]).toMatchObject({
  1180. kind: "turnHeader",
  1181. origin: "backgroundResult",
  1182. originMeta: {
  1183. backgroundSource: "subagent",
  1184. title: "Review the projection chain",
  1185. workId: "agent-review",
  1186. },
  1187. });
  1188. });
  1189. it("workflow 终态通知:manifest 载荷随 originMeta 投影到 turnHeader(BG27 姊妹)", () => {
  1190. const log = new EventLog();
  1191. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1192. const workflowNotification = {
  1193. kind: "terminal" as const,
  1194. status: "completed" as const,
  1195. summary: "nightly audit",
  1196. result: "final artifact",
  1197. resultForm: "prose" as const,
  1198. reports: { count: 2, shown: 1, preview: ["第一步"] },
  1199. durationMs: 5_000,
  1200. };
  1201. log.push(
  1202. SessionEventType.TurnStarted,
  1203. {
  1204. turnNumber: 1,
  1205. input: "workflow result",
  1206. inputSource: "background_task",
  1207. inputVisibility: "model-only",
  1208. originMeta: {
  1209. backgroundSource: "workflow",
  1210. title: "nightly audit",
  1211. workId: "dwfrun-proj",
  1212. workflowNotification,
  1213. },
  1214. } as never,
  1215. { turnId: "turn-workflow" },
  1216. );
  1217. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  1218. expect(rows).toHaveLength(1);
  1219. // originMeta 被投影层整体拷贝——manifest 载荷免费搭车,不被逐字段重构剥掉。
  1220. expect(rows[0]).toMatchObject({
  1221. kind: "turnHeader",
  1222. origin: "backgroundResult",
  1223. originMeta: {
  1224. backgroundSource: "workflow",
  1225. title: "nightly audit",
  1226. workId: "dwfrun-proj",
  1227. workflowNotification,
  1228. },
  1229. });
  1230. });
  1231. it("BG26:background Agent 失败通知按 tool-use-id 覆盖 launch ACK 终态", () => {
  1232. const turnId = "turn-agent-launch";
  1233. const toolCallId = "tool-agent-rate-limit";
  1234. const error = "Requests are too frequent. Request id: bg26";
  1235. const result = `Agent general-purpose task \"分析世界杯\" failed. ${error}`;
  1236. const notification = [
  1237. "<task-notification>",
  1238. `<tool-use-id>${toolCallId}</tool-use-id>`,
  1239. "<status>failed</status>",
  1240. `<result>${result}</result>`,
  1241. `<error>${error}</error>`,
  1242. "</task-notification>",
  1243. ].join("\n");
  1244. const log = new EventLog();
  1245. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1246. log.push(
  1247. SessionEventType.TurnStarted,
  1248. { turnNumber: 1, input: "launch agent", messageId: "user-agent-launch" },
  1249. { turnId },
  1250. );
  1251. log.push(
  1252. SessionEventType.ToolCallScheduled,
  1253. {
  1254. toolCallId,
  1255. toolName: "Agent",
  1256. input: {
  1257. description: "分析世界杯",
  1258. run_in_background: true,
  1259. subagent_type: "general-purpose",
  1260. },
  1261. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1262. },
  1263. { turnId },
  1264. );
  1265. log.push(
  1266. SessionEventType.ToolCallStarted,
  1267. { toolCallId, toolName: "Agent", startedAt: new Date(1_700_000_003_000) },
  1268. { turnId },
  1269. );
  1270. log.push(
  1271. SessionEventType.ToolCallResult,
  1272. {
  1273. toolCallId,
  1274. result: { success: true, content: "Async agent launched successfully." },
  1275. duration: 1,
  1276. },
  1277. { turnId },
  1278. );
  1279. log.push(
  1280. SessionEventType.TurnComplete,
  1281. { response: "", tokenCount: 0, toolCallCount: 1, duration: 1, resultType: "success" },
  1282. { turnId },
  1283. );
  1284. log.push(
  1285. SessionEventType.TurnStarted,
  1286. {
  1287. turnNumber: 2,
  1288. input: notification,
  1289. inputSource: "background_task",
  1290. inputVisibility: "model-only",
  1291. messageId: "user-agent-notification",
  1292. },
  1293. { turnId: "turn-agent-notification" },
  1294. );
  1295. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  1296. expect(rows.filter((row) => row.kind === "userInput")).toHaveLength(1);
  1297. expect(
  1298. rows.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  1299. ).toMatchObject({
  1300. error: {
  1301. code: "fault.runtime.backgroundTaskFailed",
  1302. message: error,
  1303. },
  1304. output: { text: result },
  1305. status: "error",
  1306. });
  1307. });
  1308. // ── B 组:stop / 迟到终态 ──
  1309. it("B:cancelled turn —— streaming 行收口为 interrupted,phase=completedInterrupted", () => {
  1310. const log = new EventLog();
  1311. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1312. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  1313. log.push(
  1314. SessionEventType.ModelStreaming,
  1315. { kind: "text_start", delta: "", done: false },
  1316. { turnId: "turn-1" },
  1317. );
  1318. log.push(
  1319. SessionEventType.ModelStreaming,
  1320. { kind: "text_delta", delta: "partial", done: false },
  1321. { turnId: "turn-1" },
  1322. );
  1323. log.push(
  1324. SessionEventType.TurnComplete,
  1325. { response: "", tokenCount: 0, toolCallCount: 0, duration: 1000, resultType: "cancelled" },
  1326. { turnId: "turn-1" },
  1327. );
  1328. const { projection } = runAll(log.events);
  1329. const snapshot = projection.getSnapshot();
  1330. expect(snapshot.control.phase).toBe("completedInterrupted");
  1331. const assistant = snapshot.rows.window.find((row) => row.kind === "assistantText");
  1332. expect(assistant).toMatchObject({ text: "partial", state: "interrupted" });
  1333. const header = snapshot.rows.window.find((row) => row.kind === "turnHeader");
  1334. expect(header).toMatchObject({ state: "completedInterrupted" });
  1335. });
  1336. it("B/结构性2:stop 后迟到的流式/工具终态被拒收,投影逐字节不变", () => {
  1337. const log = new EventLog();
  1338. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1339. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  1340. log.push(
  1341. SessionEventType.TurnComplete,
  1342. { response: "", tokenCount: 0, toolCallCount: 0, duration: 100, resultType: "cancelled" },
  1343. { turnId: "turn-1" },
  1344. );
  1345. const { projection } = runAll(log.events);
  1346. const before = structuredClone(projection.getSnapshot());
  1347. const late = new EventLog();
  1348. late.push(
  1349. SessionEventType.ModelStreaming,
  1350. { kind: "text_delta", delta: "ghost", done: false },
  1351. { turnId: "turn-1" },
  1352. );
  1353. late.push(
  1354. SessionEventType.ToolCallResult,
  1355. { toolCallId: "tc-1", result: { success: true, content: "ghost" }, duration: 1 },
  1356. { turnId: "turn-1" },
  1357. );
  1358. for (const event of late.events) {
  1359. expect(projection.applyEvent(event)).toEqual([]);
  1360. }
  1361. expect({ ...projection.getSnapshot(), seq: before.seq }).toEqual(before);
  1362. });
  1363. // ── O/Q 组:tool call 状态机与权限交互 ──
  1364. it("CUA:PID 工具按事件顺序固化最近一次成功 list_apps 快照", () => {
  1365. const turnId = "turn-cua-app-snapshot";
  1366. const log = new EventLog();
  1367. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1368. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "操作应用" }, { turnId });
  1369. const listApps = (id: string, name: string, success = true) => {
  1370. log.push(
  1371. SessionEventType.ToolCallScheduled,
  1372. {
  1373. toolCallId: id,
  1374. toolName: "mcp__computer-use__list_apps",
  1375. input: {},
  1376. schedule: { parallelGroups: [[id]], executionOrder: [id] },
  1377. },
  1378. { turnId },
  1379. );
  1380. log.push(
  1381. SessionEventType.ToolCallResult,
  1382. {
  1383. toolCallId: id,
  1384. result: {
  1385. success,
  1386. content: success
  1387. ? JSON.stringify([{ pid: 42, name, bundle_id: `com.example.${name}` }])
  1388. : "failed",
  1389. ...(!success ? { error: { type: "toolFailed", message: "failed" } } : {}),
  1390. },
  1391. duration: 1,
  1392. },
  1393. { turnId },
  1394. );
  1395. };
  1396. const scheduleKey = (
  1397. id: string,
  1398. toolName = "mcp__computer-use__key",
  1399. appRef: unknown = { pid: 42 },
  1400. ) =>
  1401. log.push(
  1402. SessionEventType.ToolCallScheduled,
  1403. {
  1404. toolCallId: id,
  1405. toolName,
  1406. input: { app_ref: appRef, key: "TAB" },
  1407. schedule: { parallelGroups: [[id]], executionOrder: [id] },
  1408. },
  1409. { turnId },
  1410. );
  1411. listApps("list-1", "One");
  1412. scheduleKey("key-1");
  1413. listApps("list-failed", "Ignored", false);
  1414. scheduleKey("key-after-failure");
  1415. listApps("list-2", "Two");
  1416. scheduleKey("key-2");
  1417. scheduleKey("bundle-only", "mcp__computer-use__get_app_state", {
  1418. bundle_id: "com.example.Two",
  1419. });
  1420. scheduleKey("serialized-pid", "mcp__computer-use__get_app_state", '{"pid":42}');
  1421. scheduleKey("lookalike", "mcp__other__computer-use__key");
  1422. const rows = runAll(log.events).projection.getSnapshot().rows.window;
  1423. const appOf = (id: string) => {
  1424. const row = rows.find(
  1425. (candidate) => candidate.kind === "toolCall" && candidate.toolCallId === id,
  1426. );
  1427. return row?.kind === "toolCall" ? row.cuaApp : undefined;
  1428. };
  1429. expect(appOf("key-1")).toEqual({ pid: 42, name: "One", bundleId: "com.example.One" });
  1430. expect(appOf("key-after-failure")).toEqual({
  1431. pid: 42,
  1432. name: "One",
  1433. bundleId: "com.example.One",
  1434. });
  1435. expect(appOf("key-2")).toEqual({ pid: 42, name: "Two", bundleId: "com.example.Two" });
  1436. expect(appOf("bundle-only")).toEqual({
  1437. pid: 42,
  1438. name: "Two",
  1439. bundleId: "com.example.Two",
  1440. });
  1441. expect(appOf("serialized-pid")).toEqual({
  1442. pid: 42,
  1443. name: "Two",
  1444. bundleId: "com.example.Two",
  1445. });
  1446. expect(appOf("lookalike")).toBeUndefined();
  1447. });
  1448. it("CUA:原子实时投影提交后保留 list_apps 快照", () => {
  1449. const turnId = "turn-cua-atomic-snapshot";
  1450. const log = new EventLog();
  1451. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1452. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "操作飞书" }, { turnId });
  1453. log.push(
  1454. SessionEventType.ToolCallScheduled,
  1455. {
  1456. toolCallId: "list-apps",
  1457. toolName: "mcp__computer-use__list_apps",
  1458. input: {},
  1459. schedule: { parallelGroups: [["list-apps"]], executionOrder: ["list-apps"] },
  1460. },
  1461. { turnId },
  1462. );
  1463. log.push(
  1464. SessionEventType.ToolCallResult,
  1465. {
  1466. toolCallId: "list-apps",
  1467. result: {
  1468. success: true,
  1469. content: JSON.stringify([{ pid: 691, name: "Feishu", bundle_id: "com.electron.lark" }]),
  1470. },
  1471. duration: 1,
  1472. },
  1473. { turnId },
  1474. );
  1475. log.push(
  1476. SessionEventType.ToolCallScheduled,
  1477. {
  1478. toolCallId: "get-app-state",
  1479. toolName: "mcp__computer-use__get_app_state",
  1480. input: { app_ref: '{"pid":691}', title: "查看飞书当前界面" },
  1481. schedule: {
  1482. parallelGroups: [["get-app-state"]],
  1483. executionOrder: ["get-app-state"],
  1484. },
  1485. },
  1486. { turnId },
  1487. );
  1488. const projection = new ProductProjection("session-1", "epoch-1");
  1489. for (const event of log.events) {
  1490. expect(projection.applyEventAtomically(event, () => true)).not.toBeNull();
  1491. }
  1492. const row = projection
  1493. .getSnapshot()
  1494. .rows.window.find(
  1495. (candidate) => candidate.kind === "toolCall" && candidate.toolCallId === "get-app-state",
  1496. );
  1497. expect(row?.kind === "toolCall" ? row.cuaApp : undefined).toEqual({
  1498. pid: 691,
  1499. name: "Feishu",
  1500. bundleId: "com.electron.lark",
  1501. });
  1502. });
  1503. it("BTA01:保留 turn-end Node REPL 图片 display 到 live tool row", () => {
  1504. const turnId = "turn-browser-shot";
  1505. const toolCallId = "tool-browser-shot";
  1506. const log = new EventLog();
  1507. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1508. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "打开页面" }, { turnId });
  1509. log.push(
  1510. SessionEventType.ToolCallScheduled,
  1511. {
  1512. toolCallId,
  1513. toolName: "mcp__node_repl__js",
  1514. input: { source: "browser_turn_end" },
  1515. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1516. },
  1517. { turnId },
  1518. );
  1519. log.push(
  1520. SessionEventType.ToolCallResult,
  1521. {
  1522. toolCallId,
  1523. result: {
  1524. success: true,
  1525. content: "",
  1526. display: {
  1527. kind: "node_repl_images",
  1528. source: "browser_turn_end",
  1529. images: [{ base64: "AAAA", mimeType: "image/png" }],
  1530. },
  1531. },
  1532. duration: 0,
  1533. },
  1534. { turnId },
  1535. );
  1536. const snapshot = runAll(log.events).projection.getSnapshot();
  1537. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  1538. expect(
  1539. snapshot.rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  1540. ).toMatchObject({
  1541. status: "success",
  1542. display: { kind: "node_repl_images", source: "browser_turn_end" },
  1543. });
  1544. });
  1545. it("CUA:保留实时工具结果的截图 display 到 output", () => {
  1546. const turnId = "turn-cua-screenshot";
  1547. const toolCallId = "tool-cua-screenshot";
  1548. const log = new EventLog();
  1549. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1550. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "截图" }, { turnId });
  1551. log.push(
  1552. SessionEventType.ToolCallScheduled,
  1553. {
  1554. toolCallId,
  1555. toolName: "mcp__computer-use__computer-use",
  1556. input: { action: "screenshot" },
  1557. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1558. },
  1559. { turnId },
  1560. );
  1561. log.push(
  1562. SessionEventType.ToolCallResult,
  1563. {
  1564. toolCallId,
  1565. result: {
  1566. success: true,
  1567. content: "[Attached image/jpeg: MCP image]",
  1568. display: {
  1569. kind: "cua",
  1570. schemaVersion: 1,
  1571. toolName: "computer-use",
  1572. status: "success",
  1573. input: '{"action":"screenshot"}',
  1574. media: [{ mimeType: "image/jpeg", data: "AAAA" }],
  1575. },
  1576. },
  1577. duration: 10,
  1578. },
  1579. { turnId },
  1580. );
  1581. expect(
  1582. runAll(log.events)
  1583. .projection.getSnapshot()
  1584. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  1585. ).toMatchObject({
  1586. status: "success",
  1587. output: {
  1588. text: "[Attached image/jpeg: MCP image]",
  1589. display: {
  1590. kind: "cua",
  1591. media: [{ mimeType: "image/jpeg", data: "AAAA" }],
  1592. },
  1593. },
  1594. });
  1595. });
  1596. it.each([
  1597. {
  1598. toolName: "TaskOutput",
  1599. display: {
  1600. kind: "task_output",
  1601. retrievalStatus: "not_ready",
  1602. taskStatus: "running",
  1603. output: "partial output",
  1604. } as const,
  1605. },
  1606. {
  1607. toolName: "RespondToCoordinator",
  1608. display: {
  1609. kind: "respond_to_coordinator",
  1610. status: "success",
  1611. } as const,
  1612. },
  1613. {
  1614. toolName: "CreateWorkflow",
  1615. display: {
  1616. kind: "create_workflow",
  1617. ok: true,
  1618. errorCount: 0,
  1619. diagnostics: [],
  1620. causalityGraph: {
  1621. steps: [
  1622. {
  1623. id: "ask#1",
  1624. kind: "ask",
  1625. label: "scout",
  1626. line: 3,
  1627. column: 20,
  1628. lane: "actor#1",
  1629. },
  1630. ],
  1631. lanes: [{ id: "actor#1", name: "scout", line: 3, column: 11 }],
  1632. // 第二层是子代理导向:每阶段一张参与者卡 + 交接边(docs/dynamic-workflow/presentation.md)。
  1633. participants: [
  1634. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] },
  1635. ],
  1636. handoffs: [],
  1637. sink: ["ask#1"],
  1638. },
  1639. } as const,
  1640. },
  1641. // 观察类工作流工具的五个 display kind(spec:docs/dynamic-workflow/launch.md「Run introspection tools」
  1642. // 「工具卡 display」、同文件「The model catalog」)——whitelist 不放行就整块被剥,UI 只能退回文本投影。
  1643. {
  1644. toolName: "GetWorkflowRun",
  1645. display: {
  1646. kind: "get_workflow_run",
  1647. runId: "wf_demo",
  1648. label: "demo",
  1649. status: "running",
  1650. usage: {
  1651. spentTokens: 1_000,
  1652. nodesObserved: 3,
  1653. nodesRunning: 1,
  1654. nodesCompleted: 2,
  1655. nodesFailed: 0,
  1656. },
  1657. actors: [{ siteId: "agent#1", ordinal: 1, name: "scout" }],
  1658. logTail: [{ sequence: 1, message: "started" }],
  1659. } as const,
  1660. },
  1661. {
  1662. toolName: "ListWorkflowRuns",
  1663. display: {
  1664. kind: "list_workflow_runs",
  1665. runs: [
  1666. {
  1667. runId: "wf_demo",
  1668. label: "demo",
  1669. labelSource: "name",
  1670. status: "completed",
  1671. ownedByThisSession: true,
  1672. createdAt: 1,
  1673. updatedAt: 2,
  1674. spentTokens: 42,
  1675. },
  1676. ],
  1677. } as const,
  1678. },
  1679. {
  1680. toolName: "EvalWorkflowSnippet",
  1681. display: {
  1682. kind: "eval_workflow_snippet",
  1683. ok: true,
  1684. diagnostics: [],
  1685. logs: ["glob matched 3 files"],
  1686. response: "3",
  1687. durationMs: 120,
  1688. } as const,
  1689. },
  1690. {
  1691. toolName: "ResumeWorkflowRun",
  1692. display: {
  1693. kind: "resume_workflow_run",
  1694. runId: "wf_demo",
  1695. } as const,
  1696. },
  1697. // 模型目录卡(spec:docs/dynamic-workflow/launch.md「The model catalog」):白名单漏了它,
  1698. // UI 只能退回那段以 providerId 开头的 `<models>` 文本。
  1699. {
  1700. toolName: "ListModels",
  1701. display: {
  1702. kind: "list_models",
  1703. current: "account:bigmodel-team-coding-plan/GLM-5.3-Flash",
  1704. models: [
  1705. {
  1706. id: "account:bigmodel-team-coding-plan/GLM-5.3-Flash",
  1707. providerId: "account:bigmodel-team-coding-plan",
  1708. modelId: "GLM-5.3-Flash",
  1709. providerLabel: "BigModel",
  1710. reasoningLevels: ["low", "medium", "high"],
  1711. defaultReasoningLevel: "high",
  1712. contextWindow: 128_000,
  1713. },
  1714. ],
  1715. } as const,
  1716. },
  1717. {
  1718. toolName: "ListSavedWorkflows",
  1719. display: {
  1720. kind: "saved_workflow_list",
  1721. workflows: [
  1722. {
  1723. name: "nightly-sync",
  1724. scope: "project",
  1725. path: ".zcode/workflows/nightly-sync.dwf.ts",
  1726. argNames: ["question"],
  1727. },
  1728. ],
  1729. } as const,
  1730. },
  1731. ])("保留 $toolName display 到 live tool row", ({ toolName, display }) => {
  1732. const turnId = `turn-${toolName}`;
  1733. const toolCallId = `tool-${toolName}`;
  1734. const log = new EventLog();
  1735. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1736. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run tool" }, { turnId });
  1737. log.push(
  1738. SessionEventType.ToolCallScheduled,
  1739. {
  1740. toolCallId,
  1741. toolName,
  1742. input: {},
  1743. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1744. },
  1745. { turnId },
  1746. );
  1747. log.push(
  1748. SessionEventType.ToolCallResult,
  1749. {
  1750. toolCallId,
  1751. result: {
  1752. success: true,
  1753. content: "provider content remains independent",
  1754. display,
  1755. },
  1756. duration: 0,
  1757. },
  1758. { turnId },
  1759. );
  1760. expect(
  1761. runAll(log.events)
  1762. .projection.getSnapshot()
  1763. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  1764. ).toMatchObject({
  1765. status: "success",
  1766. display,
  1767. output: { text: "provider content remains independent" },
  1768. });
  1769. });
  1770. it("不把未声明支持的 display kind 顺带开放到 V4 row", () => {
  1771. const turnId = "turn-file-diff-display";
  1772. const toolCallId = "tool-file-diff-display";
  1773. const log = new EventLog();
  1774. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1775. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "edit file" }, { turnId });
  1776. log.push(
  1777. SessionEventType.ToolCallScheduled,
  1778. {
  1779. toolCallId,
  1780. toolName: "Edit",
  1781. input: {},
  1782. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1783. },
  1784. { turnId },
  1785. );
  1786. log.push(
  1787. SessionEventType.ToolCallResult,
  1788. {
  1789. toolCallId,
  1790. result: {
  1791. success: true,
  1792. content: "updated",
  1793. display: {
  1794. kind: "file_diff",
  1795. filePath: "/workspace/app.ts",
  1796. additions: 1,
  1797. deletions: 0,
  1798. structuredPatch: [],
  1799. truncated: false,
  1800. },
  1801. },
  1802. duration: 0,
  1803. },
  1804. { turnId },
  1805. );
  1806. const row = runAll(log.events)
  1807. .projection.getSnapshot()
  1808. .rows.window.find((candidate) => candidate.kind === "toolCall");
  1809. expect(row).not.toHaveProperty("display");
  1810. });
  1811. it("不把 mirrored RespondToCoordinator 物化到父会话", () => {
  1812. const turnId = "turn-mirrored-response";
  1813. const toolCallId = "tool_subagent_agent-1_response";
  1814. const mirrored = {
  1815. agentId: "agent-1",
  1816. agentType: "general-purpose",
  1817. childSessionId: "session-child-1",
  1818. childToolCallId: "response",
  1819. parentToolCallId: "parent-agent-call",
  1820. source: "subagent",
  1821. };
  1822. const log = new EventLog();
  1823. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1824. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run child" }, { turnId });
  1825. log.push(
  1826. SessionEventType.ToolCallScheduled,
  1827. {
  1828. ...mirrored,
  1829. toolCallId,
  1830. toolName: "RespondToCoordinator",
  1831. input: { summary: "reply", message: "details" },
  1832. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1833. },
  1834. { turnId },
  1835. );
  1836. log.push(
  1837. SessionEventType.ToolCallResult,
  1838. {
  1839. ...mirrored,
  1840. toolCallId,
  1841. result: {
  1842. success: true,
  1843. content: "Response response-1 was queued for the coordinator.",
  1844. display: { kind: "respond_to_coordinator", status: "success" },
  1845. },
  1846. duration: 0,
  1847. },
  1848. { turnId },
  1849. );
  1850. expect(
  1851. runAll(log.events)
  1852. .projection.getSnapshot()
  1853. .rows.window.filter((row) => row.kind === "toolCall"),
  1854. ).toEqual([]);
  1855. });
  1856. it("MCP discovery 展示元数据进入 live tool row,不依赖合成工具名解析", () => {
  1857. const turnId = "turn-mcp-presentation";
  1858. const toolCallId = "tool-mcp-presentation";
  1859. const log = new EventLog();
  1860. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1861. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "查询 issue" }, { turnId });
  1862. log.push(
  1863. SessionEventType.ToolCallScheduled,
  1864. {
  1865. toolCallId,
  1866. toolName: "custom-provider-visible-name",
  1867. input: { query: "is:open" },
  1868. display: {
  1869. kind: "mcp_tool",
  1870. serverName: "company-github-prod",
  1871. toolName: "issue_query_v2",
  1872. description: "Query issues visible to the current user.",
  1873. },
  1874. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1875. },
  1876. { turnId },
  1877. );
  1878. const pendingRow = runAll(log.events.slice(0, 3))
  1879. .projection.getSnapshot()
  1880. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId);
  1881. expect(pendingRow).toMatchObject({
  1882. status: "inputStreaming",
  1883. display: { kind: "mcp_tool", toolName: "issue_query_v2" },
  1884. });
  1885. log.push(
  1886. SessionEventType.ToolCallResult,
  1887. {
  1888. toolCallId,
  1889. result: {
  1890. success: true,
  1891. content: "12 issues",
  1892. display: {
  1893. kind: "mcp_tool",
  1894. serverName: "company-github-prod",
  1895. toolName: "issue_query_v2",
  1896. description: "Query issues visible to the current user.",
  1897. },
  1898. },
  1899. duration: 12,
  1900. },
  1901. { turnId },
  1902. );
  1903. expect(
  1904. runAll(log.events)
  1905. .projection.getSnapshot()
  1906. .rows.window.find((row) => row.kind === "toolCall" && row.toolCallId === toolCallId),
  1907. ).toMatchObject({
  1908. toolName: "custom-provider-visible-name",
  1909. status: "success",
  1910. display: {
  1911. kind: "mcp_tool",
  1912. serverName: "company-github-prod",
  1913. toolName: "issue_query_v2",
  1914. },
  1915. });
  1916. });
  1917. it("MCP display 在 running、failed 与 stopped 生命周期更新中保持不变", () => {
  1918. const display = {
  1919. kind: "mcp_tool" as const,
  1920. serverName: "firebase",
  1921. toolName: "get_environment",
  1922. };
  1923. const createLog = () => {
  1924. const log = new EventLog();
  1925. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1926. log.push(
  1927. SessionEventType.TurnStarted,
  1928. { turnNumber: 1, input: "inspect" },
  1929. { turnId: "turn-mcp-lifecycle" },
  1930. );
  1931. log.push(
  1932. SessionEventType.ToolCallScheduled,
  1933. {
  1934. toolCallId: "mcp-lifecycle",
  1935. toolName: "opaque-name",
  1936. input: {},
  1937. display,
  1938. schedule: { parallelGroups: [["mcp-lifecycle"]], executionOrder: ["mcp-lifecycle"] },
  1939. },
  1940. { turnId: "turn-mcp-lifecycle" },
  1941. );
  1942. log.push(
  1943. SessionEventType.ToolCallStarted,
  1944. { toolCallId: "mcp-lifecycle", toolName: "opaque-name", startedAt: new Date() },
  1945. { turnId: "turn-mcp-lifecycle" },
  1946. );
  1947. return log;
  1948. };
  1949. const failedLog = createLog();
  1950. failedLog.push(
  1951. SessionEventType.ToolCallError,
  1952. { toolCallId: "mcp-lifecycle", error: { type: "tool_failed", message: "boom" } },
  1953. { turnId: "turn-mcp-lifecycle" },
  1954. );
  1955. const failedRow = runAll(failedLog.events).projection.getSnapshot().rows.window.at(-1);
  1956. expect(failedRow).toMatchObject({ status: "error", display });
  1957. const stoppedLog = createLog();
  1958. stoppedLog.push(
  1959. SessionEventType.TurnComplete,
  1960. { response: "", tokenCount: 0, toolCallCount: 1, duration: 1, resultType: "cancelled" },
  1961. { turnId: "turn-mcp-lifecycle" },
  1962. );
  1963. const stoppedRow = runAll(stoppedLog.events).projection.getSnapshot().rows.window.at(-1);
  1964. expect(stoppedRow).toMatchObject({ status: "cancelled", display });
  1965. });
  1966. it("工具主动取消错误直接投影为 cancelled,不等待 turn complete 纠正", () => {
  1967. const turnId = "turn-tool-cancelled";
  1968. const log = new EventLog();
  1969. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  1970. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run long bash" }, { turnId });
  1971. log.push(
  1972. SessionEventType.ToolCallScheduled,
  1973. {
  1974. toolCallId: "bash-cancelled",
  1975. toolName: "Bash",
  1976. input: { command: "sleep 60" },
  1977. schedule: { parallelGroups: [["bash-cancelled"]], executionOrder: ["bash-cancelled"] },
  1978. },
  1979. { turnId },
  1980. );
  1981. log.push(
  1982. SessionEventType.ToolCallStarted,
  1983. { toolCallId: "bash-cancelled", toolName: "Bash", startedAt: new Date() },
  1984. { turnId },
  1985. );
  1986. log.push(
  1987. SessionEventType.ToolCallError,
  1988. {
  1989. toolCallId: "bash-cancelled",
  1990. error: {
  1991. code: "TOOL_CANCELLED",
  1992. type: "tool_cancelled",
  1993. message: "Bash was cancelled and the child process was asked to stop",
  1994. },
  1995. },
  1996. { turnId },
  1997. );
  1998. const row = runAll(log.events).projection.getSnapshot().rows.window.at(-1);
  1999. expect(row).toMatchObject({ kind: "toolCall", status: "cancelled" });
  2000. });
  2001. it("O/Q:tool 输入流式 → 权限等待 → 放行执行 → 成功终态", () => {
  2002. const turnId = "turn-1";
  2003. const log = new EventLog();
  2004. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2005. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run ls" }, { turnId });
  2006. log.push(
  2007. SessionEventType.ModelStreaming,
  2008. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-1", toolName: "bash" },
  2009. { turnId },
  2010. );
  2011. log.push(
  2012. SessionEventType.ModelStreaming,
  2013. { kind: "tool_input_delta", delta: '{"command":"ls"}', done: false, toolCallId: "tc-1" },
  2014. { turnId },
  2015. );
  2016. log.push(
  2017. SessionEventType.ToolCallScheduled,
  2018. {
  2019. toolCallId: "tc-1",
  2020. toolName: "bash",
  2021. input: { command: "ls" },
  2022. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  2023. },
  2024. { turnId },
  2025. );
  2026. log.push(
  2027. SessionEventType.PermissionRequested,
  2028. {
  2029. requestId: "req-1",
  2030. toolCallId: "tc-1",
  2031. toolName: "bash",
  2032. riskLevel: "medium",
  2033. reason: "Run shell command",
  2034. input: { command: "ls" },
  2035. suggestedPermissionUpdates: [
  2036. {
  2037. behavior: "allow",
  2038. rules: [{ ruleContent: "pnpm run lint:*", toolName: "Bash" }],
  2039. type: "addRules",
  2040. },
  2041. ],
  2042. },
  2043. { turnId },
  2044. );
  2045. const { projection } = runAll(log.events);
  2046. const pending = projection.getSnapshot();
  2047. const toolRow = pending.rows.window.find((row) => row.kind === "toolCall");
  2048. expect(toolRow).toMatchObject({
  2049. status: "pendingApproval",
  2050. inputText: '{"command":"ls"}',
  2051. approvalInteractionId: "req-1",
  2052. });
  2053. expect(pending.pendingInteractions).toHaveLength(1);
  2054. expect(pending.pendingInteractions[0]).toMatchObject({
  2055. kind: "permission",
  2056. anchorRowId: toolRow?.rowId,
  2057. });
  2058. expect(pending.pendingInteractions[0]?.payload).toMatchObject({
  2059. freeText: true,
  2060. options: [
  2061. { optionId: "allowOnce", response: { decision: "allow" } },
  2062. {
  2063. optionId: "allowAlways",
  2064. response: {
  2065. decision: "allow",
  2066. permissionUpdates: [
  2067. {
  2068. behavior: "allow",
  2069. rules: [{ ruleContent: "pnpm run lint:*", toolName: "Bash" }],
  2070. type: "addRules",
  2071. },
  2072. ],
  2073. },
  2074. },
  2075. { optionId: "deny", response: { decision: "deny" } },
  2076. ],
  2077. });
  2078. const resume = new EventLog();
  2079. // EventLog seq 从 1 重新计数不影响断言主体(seq 水位单独断言于 A 组)。
  2080. resume.push(
  2081. SessionEventType.PermissionResolved,
  2082. { requestId: "req-1", toolCallId: "tc-1", decision: "allow" },
  2083. { turnId },
  2084. );
  2085. resume.push(
  2086. SessionEventType.ToolCallStarted,
  2087. { toolCallId: "tc-1", toolName: "bash", startedAt: new Date() },
  2088. { turnId },
  2089. );
  2090. resume.push(
  2091. SessionEventType.ToolCallResult,
  2092. { toolCallId: "tc-1", result: { success: true, content: "file-a\nfile-b" }, duration: 42 },
  2093. { turnId },
  2094. );
  2095. for (const event of resume.events) projection.applyEvent(event);
  2096. const done = projection.getSnapshot();
  2097. expect(done.pendingInteractions).toHaveLength(0);
  2098. const doneRow = done.rows.window.find((row) => row.kind === "toolCall");
  2099. expect(doneRow).toMatchObject({
  2100. status: "success",
  2101. output: { text: "file-a\nfile-b" },
  2102. });
  2103. expect(
  2104. doneRow && "approvalInteractionId" in doneRow && doneRow.approvalInteractionId,
  2105. ).toBeFalsy();
  2106. });
  2107. it.each([
  2108. { label: "空字符串", streamName: "" },
  2109. { label: "纯空白", streamName: " \t " },
  2110. ])("O/ETN:$label 工具名只参与恢复,不物化可见工具行", ({ streamName }) => {
  2111. const turnId = "turn-empty-tool-name";
  2112. const toolCallId = "call-empty-tool-name";
  2113. const log = new EventLog();
  2114. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2115. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "continue" }, { turnId });
  2116. log.push(
  2117. SessionEventType.ModelStreaming,
  2118. {
  2119. kind: "tool_input_start",
  2120. delta: "",
  2121. done: false,
  2122. toolCallId,
  2123. toolName: streamName,
  2124. },
  2125. { turnId },
  2126. );
  2127. log.push(
  2128. SessionEventType.ModelStreaming,
  2129. {
  2130. kind: "tool_input_delta",
  2131. delta: '{"value":1}',
  2132. done: false,
  2133. toolCallId,
  2134. },
  2135. { turnId },
  2136. );
  2137. log.push(
  2138. SessionEventType.ModelStreaming,
  2139. {
  2140. kind: "tool_call",
  2141. delta: "",
  2142. done: true,
  2143. input: { value: 1 },
  2144. toolCallId,
  2145. toolName: streamName,
  2146. },
  2147. { turnId },
  2148. );
  2149. log.push(
  2150. SessionEventType.ToolCallError,
  2151. {
  2152. toolCallId,
  2153. error: {
  2154. type: "fault.runtime.toolFailed",
  2155. message: "Model returned an invalid tool call: tool name is empty.",
  2156. },
  2157. },
  2158. { turnId },
  2159. );
  2160. log.push(
  2161. SessionEventType.ModelStreaming,
  2162. { kind: "text_start", delta: "", done: false },
  2163. { turnId },
  2164. );
  2165. log.push(
  2166. SessionEventType.ModelStreaming,
  2167. { kind: "text_delta", delta: "continued", done: false },
  2168. { turnId },
  2169. );
  2170. log.push(
  2171. SessionEventType.ModelStreaming,
  2172. { kind: "text_end", delta: "", done: false },
  2173. { turnId },
  2174. );
  2175. log.push(
  2176. SessionEventType.TurnComplete,
  2177. {
  2178. response: "continued",
  2179. tokenCount: 1,
  2180. toolCallCount: 1,
  2181. duration: 10,
  2182. resultType: "success",
  2183. },
  2184. { turnId },
  2185. );
  2186. const { deltasPerEvent, projection, snapshots } = runAll(log.events);
  2187. expect(projection.getSnapshot().rows.window.filter((row) => row.kind === "toolCall")).toEqual(
  2188. [],
  2189. );
  2190. expect(
  2191. projection.getSnapshot().rows.window.find((row) => row.kind === "assistantText"),
  2192. ).toMatchObject({ text: "continued", state: "complete" });
  2193. expect(
  2194. deltasPerEvent
  2195. .flat()
  2196. .some(
  2197. (delta) =>
  2198. (delta.op === "row.appended" || delta.op === "row.upserted") &&
  2199. delta.row.kind === "toolCall",
  2200. ),
  2201. ).toBe(false);
  2202. const direct = applyConversationDeltas(snapshots[0]!, deltasPerEvent.flat());
  2203. for (const profile of [DELIVERY_PROFILES.continuous, DELIVERY_PROFILES.replayable]) {
  2204. const delivered = coalesceConversationDeltas(
  2205. filterConversationDeltasForProfile(deltasPerEvent.flat(), profile),
  2206. );
  2207. expect(applyConversationDeltas(snapshots[0]!, delivered)).toEqual(direct);
  2208. }
  2209. });
  2210. it("O/ETN:合法 empty_tool_name 工具保留 live 与 replayable 可见生命周期", () => {
  2211. const turnId = "turn-legitimate-empty-tool-name";
  2212. const toolCallId = "call-legitimate-empty-tool-name";
  2213. const log = new EventLog();
  2214. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2215. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run tool" }, { turnId });
  2216. log.push(
  2217. SessionEventType.ModelStreaming,
  2218. {
  2219. kind: "tool_input_start",
  2220. delta: "",
  2221. done: false,
  2222. toolCallId,
  2223. toolName: "empty_tool_name",
  2224. },
  2225. { turnId },
  2226. );
  2227. log.push(
  2228. SessionEventType.ModelStreaming,
  2229. {
  2230. kind: "tool_input_delta",
  2231. delta: '{"value":1}',
  2232. done: false,
  2233. toolCallId,
  2234. },
  2235. { turnId },
  2236. );
  2237. log.push(
  2238. SessionEventType.ModelStreaming,
  2239. {
  2240. kind: "tool_call",
  2241. delta: "",
  2242. done: true,
  2243. input: { value: 1 },
  2244. toolCallId,
  2245. toolName: "empty_tool_name",
  2246. },
  2247. { turnId },
  2248. );
  2249. log.push(
  2250. SessionEventType.ToolCallScheduled,
  2251. {
  2252. toolCallId,
  2253. toolName: "empty_tool_name",
  2254. input: { value: 1 },
  2255. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  2256. },
  2257. { turnId },
  2258. );
  2259. log.push(
  2260. SessionEventType.ToolCallResult,
  2261. {
  2262. toolCallId,
  2263. result: { success: true, content: "ok" },
  2264. duration: 1,
  2265. },
  2266. { turnId },
  2267. );
  2268. const { deltasPerEvent, projection, snapshots } = runAll(log.events);
  2269. expect(
  2270. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  2271. ).toMatchObject({
  2272. input: { value: 1 },
  2273. status: "success",
  2274. toolCallId,
  2275. toolName: "empty_tool_name",
  2276. });
  2277. const direct = applyConversationDeltas(snapshots[0]!, deltasPerEvent.flat());
  2278. for (const profile of [DELIVERY_PROFILES.continuous, DELIVERY_PROFILES.replayable]) {
  2279. const delivered = coalesceConversationDeltas(
  2280. filterConversationDeltasForProfile(deltasPerEvent.flat(), profile),
  2281. );
  2282. expect(applyConversationDeltas(snapshots[0]!, delivered)).toEqual(direct);
  2283. }
  2284. });
  2285. it("O/ETN:普通非空 unknown tool 仍保留 terminal error 工具行", () => {
  2286. const turnId = "turn-unknown-tool";
  2287. const toolCallId = "call-unknown-tool";
  2288. const log = new EventLog();
  2289. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2290. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "continue" }, { turnId });
  2291. log.push(
  2292. SessionEventType.ToolCallScheduled,
  2293. {
  2294. toolCallId,
  2295. toolName: "DefinitelyMissingTool",
  2296. input: {},
  2297. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  2298. },
  2299. { turnId },
  2300. );
  2301. log.push(
  2302. SessionEventType.ToolCallError,
  2303. {
  2304. toolCallId,
  2305. error: { type: "fault.runtime.toolNotFound", message: "Tool not found" },
  2306. },
  2307. { turnId },
  2308. );
  2309. expect(
  2310. runAll(log.events)
  2311. .projection.getSnapshot()
  2312. .rows.window.find((row) => row.kind === "toolCall"),
  2313. ).toMatchObject({
  2314. toolCallId,
  2315. toolName: "DefinitelyMissingTool",
  2316. status: "error",
  2317. });
  2318. });
  2319. it.each(["Write", "Edit"])(
  2320. "STIP06:%s 首包立即,后续 inputText 按事件时间戳每秒合并一次",
  2321. (toolName) => {
  2322. const turnId = "turn-file-tool";
  2323. const base = 1_700_000_010_000;
  2324. const log = new EventLog();
  2325. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2326. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "modify file" }, { turnId });
  2327. log.push(
  2328. SessionEventType.ModelStreaming,
  2329. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-file", toolName },
  2330. { timestampMs: base, turnId },
  2331. );
  2332. log.push(
  2333. SessionEventType.ModelStreaming,
  2334. {
  2335. kind: "tool_input_delta",
  2336. delta: '{"file_path":"src/app.ts",',
  2337. done: false,
  2338. toolCallId: "tc-file",
  2339. },
  2340. { timestampMs: base + 100, turnId },
  2341. );
  2342. log.push(
  2343. SessionEventType.ModelStreaming,
  2344. { kind: "tool_input_delta", delta: '"content":"a', done: false, toolCallId: "tc-file" },
  2345. { timestampMs: base + 400, turnId },
  2346. );
  2347. log.push(
  2348. SessionEventType.ModelStreaming,
  2349. { kind: "tool_input_delta", delta: 'b"}', done: false, toolCallId: "tc-file" },
  2350. { timestampMs: base + 1_100, turnId },
  2351. );
  2352. const { deltasPerEvent, projection } = runAll(log.events);
  2353. expect(inputTextAppends(deltasPerEvent[3] ?? [])).toEqual(['{"file_path":"src/app.ts",']);
  2354. expect(inputTextAppends(deltasPerEvent[4] ?? [])).toEqual([]);
  2355. expect(inputTextAppends(deltasPerEvent[5] ?? [])).toEqual(['"content":"ab"}']);
  2356. expect(
  2357. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  2358. ).toMatchObject({ inputText: '{"file_path":"src/app.ts","content":"ab"}' });
  2359. const estimateProjection = new ProductProjection("session-1", "epoch-1");
  2360. const appendEstimates = log.events.map((event) => {
  2361. const estimate = estimateProjection.establishedStreamingAppend(event);
  2362. estimateProjection.applyEvent(event);
  2363. return estimate;
  2364. });
  2365. expect(appendEstimates.slice(3)).toEqual([
  2366. '{"file_path":"src/app.ts",',
  2367. "",
  2368. '"content":"ab"}',
  2369. ]);
  2370. },
  2371. );
  2372. it("STIP07:Write input end 立即冲刷窗口内尚未发布的 suffix", () => {
  2373. const turnId = "turn-write-end";
  2374. const base = 1_700_000_020_000;
  2375. const log = new EventLog();
  2376. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2377. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "write" }, { turnId });
  2378. log.push(
  2379. SessionEventType.ModelStreaming,
  2380. {
  2381. kind: "tool_input_start",
  2382. delta: "",
  2383. done: false,
  2384. toolCallId: "tc-write",
  2385. toolName: "Write",
  2386. },
  2387. { timestampMs: base, turnId },
  2388. );
  2389. log.push(
  2390. SessionEventType.ModelStreaming,
  2391. { kind: "tool_input_delta", delta: '{"content":"a', done: false, toolCallId: "tc-write" },
  2392. { timestampMs: base + 100, turnId },
  2393. );
  2394. log.push(
  2395. SessionEventType.ModelStreaming,
  2396. { kind: "tool_input_delta", delta: 'b"}', done: false, toolCallId: "tc-write" },
  2397. { timestampMs: base + 200, turnId },
  2398. );
  2399. log.push(
  2400. SessionEventType.ModelStreaming,
  2401. { kind: "tool_input_end", delta: "", done: true, toolCallId: "tc-write" },
  2402. { timestampMs: base + 300, turnId },
  2403. );
  2404. const { deltasPerEvent, projection } = runAll(log.events);
  2405. expect(inputTextAppends(deltasPerEvent[4] ?? [])).toEqual([]);
  2406. expect(inputTextAppends(deltasPerEvent[5] ?? [])).toEqual(['b"}']);
  2407. expect(
  2408. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  2409. ).toMatchObject({ inputText: '{"content":"ab"}' });
  2410. });
  2411. it("STIP07:Write 被取消时把窗口内 suffix 收进 cancelled row", () => {
  2412. const turnId = "turn-write-cancel";
  2413. const base = 1_700_000_030_000;
  2414. const log = new EventLog();
  2415. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2416. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "write" }, { turnId });
  2417. log.push(
  2418. SessionEventType.ModelStreaming,
  2419. {
  2420. kind: "tool_input_start",
  2421. delta: "",
  2422. done: false,
  2423. toolCallId: "tc-write",
  2424. toolName: "Write",
  2425. },
  2426. { timestampMs: base, turnId },
  2427. );
  2428. log.push(
  2429. SessionEventType.ModelStreaming,
  2430. { kind: "tool_input_delta", delta: '{"content":"a', done: false, toolCallId: "tc-write" },
  2431. { timestampMs: base + 100, turnId },
  2432. );
  2433. log.push(
  2434. SessionEventType.ModelStreaming,
  2435. { kind: "tool_input_delta", delta: 'b"}', done: false, toolCallId: "tc-write" },
  2436. { timestampMs: base + 200, turnId },
  2437. );
  2438. log.push(
  2439. SessionEventType.TurnComplete,
  2440. { response: "", tokenCount: 0, toolCallCount: 0, duration: 300, resultType: "cancelled" },
  2441. { timestampMs: base + 300, turnId },
  2442. );
  2443. const { deltasPerEvent, projection } = runAll(log.events);
  2444. expect(inputTextAppends(deltasPerEvent[4] ?? [])).toEqual([]);
  2445. expect(
  2446. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  2447. ).toMatchObject({ status: "cancelled", inputText: '{"content":"ab"}' });
  2448. });
  2449. it("STIP08:非 Write/Edit 工具保留逐投影增量", () => {
  2450. const turnId = "turn-bash";
  2451. const base = 1_700_000_040_000;
  2452. const log = new EventLog();
  2453. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2454. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId });
  2455. log.push(
  2456. SessionEventType.ModelStreaming,
  2457. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-bash", toolName: "Bash" },
  2458. { timestampMs: base, turnId },
  2459. );
  2460. log.push(
  2461. SessionEventType.ModelStreaming,
  2462. { kind: "tool_input_delta", delta: '{"command":"p', done: false, toolCallId: "tc-bash" },
  2463. { timestampMs: base + 100, turnId },
  2464. );
  2465. log.push(
  2466. SessionEventType.ModelStreaming,
  2467. { kind: "tool_input_delta", delta: 'wd"}', done: false, toolCallId: "tc-bash" },
  2468. { timestampMs: base + 200, turnId },
  2469. );
  2470. const { deltasPerEvent } = runAll(log.events);
  2471. expect(inputTextAppends(deltasPerEvent[3] ?? [])).toEqual(['{"command":"p']);
  2472. expect(inputTextAppends(deltasPerEvent[4] ?? [])).toEqual(['wd"}']);
  2473. });
  2474. it("Q:AskUserQuestion 权限等待态 → structured userInput pendingInteraction", () => {
  2475. const turnId = "turn-ask";
  2476. const log = new EventLog();
  2477. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2478. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "帮我做个番茄钟" }, { turnId });
  2479. log.push(
  2480. SessionEventType.ToolCallScheduled,
  2481. {
  2482. toolCallId: "ask-1",
  2483. toolName: "AskUserQuestion",
  2484. input: {
  2485. questions: [
  2486. {
  2487. question: "你想把这个番茄时钟作为什么形式存在?",
  2488. header: "形式",
  2489. options: [
  2490. { label: "独立新页面", description: "新增页面", preview: "新增页面预览" },
  2491. { label: "独立小工具视图", description: "嵌入现有界面" },
  2492. ],
  2493. },
  2494. ],
  2495. },
  2496. schedule: { parallelGroups: [["ask-1"]], executionOrder: ["ask-1"] },
  2497. },
  2498. { turnId },
  2499. );
  2500. log.push(
  2501. SessionEventType.PermissionRequested,
  2502. {
  2503. requestId: "ask-request-1",
  2504. toolCallId: "ask-1",
  2505. toolName: "AskUserQuestion",
  2506. riskLevel: "low",
  2507. reason: "AskUserQuestion pauses execution to collect answers from the user",
  2508. origin: {
  2509. kind: "subagent",
  2510. agentId: "agent-ask",
  2511. agentType: "general-purpose",
  2512. childSessionId: "sess-child-ask",
  2513. description: "Ask from child",
  2514. parentSessionId: "session-1",
  2515. parentToolCallId: "call-parent-agent",
  2516. parentTurnId: turnId,
  2517. },
  2518. input: {
  2519. questions: [
  2520. {
  2521. question: "你想把这个番茄时钟作为什么形式存在?",
  2522. header: "形式",
  2523. options: [
  2524. { label: "独立新页面", description: "新增页面", preview: "新增页面预览" },
  2525. { label: "独立小工具视图", description: "嵌入现有界面" },
  2526. ],
  2527. },
  2528. ],
  2529. },
  2530. },
  2531. { turnId },
  2532. );
  2533. const { projection } = runAll(log.events);
  2534. const snapshot = projection.getSnapshot();
  2535. const toolRow = snapshot.rows.window.find((row) => row.kind === "toolCall");
  2536. expect(toolRow).toMatchObject({
  2537. status: "pendingApproval",
  2538. approvalInteractionId: "ask-request-1",
  2539. });
  2540. expect(snapshot.pendingInteractions).toHaveLength(1);
  2541. expect(snapshot.pendingInteractions[0]).toMatchObject({
  2542. interactionId: "ask-request-1",
  2543. kind: "userInput",
  2544. anchorRowId: toolRow?.rowId,
  2545. payload: {
  2546. kind: "userInput",
  2547. toolName: "AskUserQuestion",
  2548. toolCallId: "ask-1",
  2549. origin: {
  2550. kind: "subagent",
  2551. agentId: "agent-ask",
  2552. childSessionId: "sess-child-ask",
  2553. parentSessionId: "session-1",
  2554. parentToolCallId: "call-parent-agent",
  2555. },
  2556. prompt: "AskUserQuestion pauses execution to collect answers from the user",
  2557. freeText: true,
  2558. schema: { toolName: "AskUserQuestion" },
  2559. questions: [
  2560. {
  2561. question: "你想把这个番茄时钟作为什么形式存在?",
  2562. header: "形式",
  2563. options: [
  2564. {
  2565. value: "独立新页面",
  2566. label: "独立新页面",
  2567. description: "新增页面",
  2568. preview: "新增页面预览",
  2569. },
  2570. { value: "独立小工具视图", label: "独立小工具视图", description: "嵌入现有界面" },
  2571. ],
  2572. },
  2573. ],
  2574. },
  2575. });
  2576. const autoResolutionLog = new EventLog();
  2577. const hiddenGrace = {
  2578. state: "hiddenGrace" as const,
  2579. startedAt: 1_700_000_000_000,
  2580. visibleAt: 1_700_000_060_000,
  2581. deadlineAt: 1_700_000_300_000,
  2582. };
  2583. projection.applyEvent(
  2584. autoResolutionLog.push(
  2585. SessionEventType.UserInputAutoResolutionUpdated,
  2586. {
  2587. interactionId: "ask-request-1",
  2588. toolCallId: "ask-1",
  2589. autoResolution: hiddenGrace,
  2590. },
  2591. { turnId },
  2592. ),
  2593. );
  2594. expect(projection.getSnapshot().pendingInteractions[0]?.autoResolution).toEqual(hiddenGrace);
  2595. const visibleCountdown = { ...hiddenGrace, state: "visibleCountdown" as const };
  2596. projection.applyEvent(
  2597. autoResolutionLog.push(
  2598. SessionEventType.UserInputAutoResolutionUpdated,
  2599. {
  2600. interactionId: "ask-request-1",
  2601. toolCallId: "ask-1",
  2602. autoResolution: visibleCountdown,
  2603. },
  2604. { turnId },
  2605. ),
  2606. );
  2607. expect(projection.getSnapshot().pendingInteractions[0]?.autoResolution).toEqual(
  2608. visibleCountdown,
  2609. );
  2610. const snoozed = {
  2611. state: "snoozed" as const,
  2612. startedAt: hiddenGrace.startedAt,
  2613. snoozedAt: 1_700_000_299_000,
  2614. };
  2615. projection.applyEvent(
  2616. autoResolutionLog.push(
  2617. SessionEventType.UserInputAutoResolutionUpdated,
  2618. {
  2619. interactionId: "ask-request-1",
  2620. toolCallId: "ask-1",
  2621. autoResolution: snoozed,
  2622. },
  2623. { turnId },
  2624. ),
  2625. );
  2626. expect(projection.getSnapshot().pendingInteractions[0]?.autoResolution).toEqual(snoozed);
  2627. const resume = new EventLog();
  2628. projection.applyEvent(
  2629. resume.push(
  2630. SessionEventType.PermissionResolved,
  2631. { requestId: "ask-request-1", toolCallId: "ask-1", decision: "allow" },
  2632. { turnId },
  2633. ),
  2634. );
  2635. expect(projection.getSnapshot().pendingInteractions).toHaveLength(0);
  2636. });
  2637. it("Q:ExitPlanMode 权限等待态 → plan approval elicitation pendingInteraction", () => {
  2638. const turnId = "turn-plan";
  2639. const log = new EventLog();
  2640. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2641. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "进入计划模式" }, { turnId });
  2642. log.push(
  2643. SessionEventType.ToolCallScheduled,
  2644. {
  2645. toolCallId: "exit-plan-1",
  2646. toolName: "ExitPlanMode",
  2647. input: { plan: "1. 增加协议\n2. 补 UI" },
  2648. schedule: { parallelGroups: [["exit-plan-1"]], executionOrder: ["exit-plan-1"] },
  2649. },
  2650. { turnId },
  2651. );
  2652. log.push(
  2653. SessionEventType.PermissionRequested,
  2654. {
  2655. requestId: "plan-request-1",
  2656. toolCallId: "exit-plan-1",
  2657. toolName: "ExitPlanMode",
  2658. riskLevel: "low",
  2659. reason: "ExitPlanMode requires user approval before implementation",
  2660. input: { plan: "1. 增加协议\n2. 补 UI" },
  2661. },
  2662. { turnId },
  2663. );
  2664. const { projection } = runAll(log.events);
  2665. expect(projection.getSnapshot().pendingInteractions[0]).toMatchObject({
  2666. kind: "userInput",
  2667. payload: {
  2668. kind: "userInput",
  2669. toolName: "ExitPlanMode",
  2670. toolCallId: "exit-plan-1",
  2671. schema: { interaction: "plan_approval", toolName: "ExitPlanMode" },
  2672. questions: [
  2673. {
  2674. header: "Plan",
  2675. question: "ExitPlanMode requires user approval before implementation",
  2676. options: [
  2677. {
  2678. value: "approve",
  2679. label: "Approve",
  2680. description: "Exit plan mode and start implementation.",
  2681. },
  2682. ],
  2683. },
  2684. ],
  2685. },
  2686. });
  2687. });
  2688. it("Q:权限拒绝 → toolCall cancelled,交互清除", () => {
  2689. const turnId = "turn-1";
  2690. const log = new EventLog();
  2691. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2692. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "rm -rf" }, { turnId });
  2693. log.push(
  2694. SessionEventType.ToolCallScheduled,
  2695. {
  2696. toolCallId: "tc-1",
  2697. toolName: "bash",
  2698. input: { command: "rm -rf /" },
  2699. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  2700. },
  2701. { turnId },
  2702. );
  2703. log.push(
  2704. SessionEventType.PermissionRequested,
  2705. {
  2706. requestId: "req-1",
  2707. toolCallId: "tc-1",
  2708. toolName: "bash",
  2709. riskLevel: "high",
  2710. reason: "Destructive",
  2711. input: {},
  2712. },
  2713. { turnId },
  2714. );
  2715. log.push(
  2716. SessionEventType.PermissionResolved,
  2717. { requestId: "req-1", toolCallId: "tc-1", decision: "deny" },
  2718. { turnId },
  2719. );
  2720. const { projection } = runAll(log.events);
  2721. const snapshot = projection.getSnapshot();
  2722. expect(snapshot.pendingInteractions).toHaveLength(0);
  2723. expect(snapshot.rows.window.find((row) => row.kind === "toolCall")).toMatchObject({
  2724. status: "cancelled",
  2725. });
  2726. });
  2727. it("O:SubagentSpawned/Stopped → subagent row success 并保留 child session 下钻信息", () => {
  2728. const turnId = "turn-1";
  2729. const log = new EventLog();
  2730. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2731. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "派子代理" }, { turnId });
  2732. log.push(
  2733. SessionEventType.SubagentSpawned,
  2734. {
  2735. agentId: "agent-1",
  2736. agentType: "Explore",
  2737. childSessionId: "sess_child_1",
  2738. description: "探索项目结构",
  2739. parentToolCallId: "call-agent-1",
  2740. prompt: "请探索项目",
  2741. status: "running",
  2742. },
  2743. { turnId },
  2744. );
  2745. log.push(
  2746. SessionEventType.SubagentStopped,
  2747. {
  2748. agentId: "agent-1",
  2749. agentType: "Explore",
  2750. childSessionId: "sess_child_1",
  2751. status: "completed",
  2752. summaryText: "项目结构已经梳理完成",
  2753. },
  2754. { turnId },
  2755. );
  2756. const { projection } = runAll(log.events);
  2757. expect(
  2758. projection.getSnapshot().rows.window.find((row) => row.kind === "subagent"),
  2759. ).toMatchObject({
  2760. childSessionId: "sess_child_1",
  2761. parentToolCallId: "call-agent-1",
  2762. status: "success",
  2763. subagentType: "Explore",
  2764. summaryText: "项目结构已经梳理完成",
  2765. });
  2766. expect(projection.getSnapshot().subagents).toMatchObject({
  2767. childSessionIds: ["sess_child_1"],
  2768. running: [],
  2769. endedTotal: 1,
  2770. });
  2771. });
  2772. it("SAT12:SendMessage resumed spawn 在同一次投影中恢复原 row 和 cancellable work", () => {
  2773. const turnId = "turn-send-message-resume";
  2774. const log = new EventLog();
  2775. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  2776. log.push(
  2777. SessionEventType.TurnStarted,
  2778. { turnNumber: 1, input: "先运行前台 Agent" },
  2779. { turnId },
  2780. );
  2781. log.push(
  2782. SessionEventType.SubagentSpawned,
  2783. {
  2784. agentId: "agent-resume",
  2785. agentType: "general-purpose",
  2786. childSessionId: "sess-child-resume",
  2787. description: "前台任务",
  2788. parentToolCallId: "call-agent",
  2789. status: "running",
  2790. },
  2791. { turnId },
  2792. );
  2793. log.push(
  2794. SessionEventType.SubagentStopped,
  2795. {
  2796. agentId: "agent-resume",
  2797. agentType: "general-purpose",
  2798. childSessionId: "sess-child-resume",
  2799. parentToolCallId: "call-agent",
  2800. status: "completed",
  2801. },
  2802. { turnId },
  2803. );
  2804. const projection = new ProductProjection("session-1", "epoch-1");
  2805. for (const item of log.events) projection.applyEvent(item);
  2806. const resumedEvent = log.push(
  2807. SessionEventType.SubagentSpawned,
  2808. {
  2809. agentId: "agent-resume",
  2810. agentType: "general-purpose",
  2811. background: true,
  2812. childSessionId: "sess-child-resume",
  2813. description: "恢复到后台",
  2814. parentToolCallId: "call-send-message",
  2815. resumed: true,
  2816. status: "running",
  2817. },
  2818. { turnId },
  2819. );
  2820. const deltas = projection.applyEvent(resumedEvent);
  2821. const snapshot = projection.getSnapshot();
  2822. expect(
  2823. snapshot.rows.window.filter(
  2824. (row) => row.kind === "subagent" && row.entityId === "agent-resume",
  2825. ),
  2826. ).toHaveLength(1);
  2827. expect(snapshot.rows.window.find((row) => row.kind === "subagent")).toMatchObject({
  2828. childSessionId: "sess-child-resume",
  2829. parentToolCallId: "call-agent",
  2830. status: "running",
  2831. });
  2832. expect(snapshot.backgroundWorks).toEqual([
  2833. expect.objectContaining({
  2834. workId: "agent-resume",
  2835. kind: "subagent",
  2836. childSessionId: "sess-child-resume",
  2837. cancellable: true,
  2838. status: "running",
  2839. title: "恢复到后台",
  2840. }),
  2841. ]);
  2842. expect(snapshot.subagents).toMatchObject({
  2843. childSessionIds: ["sess-child-resume"],
  2844. running: [expect.objectContaining({ childSessionId: "sess-child-resume" })],
  2845. endedTotal: 0,
  2846. });
  2847. expect(
  2848. deltas.some(
  2849. (delta) => delta.op === "state.updated" && delta.patch.backgroundWorks?.length === 1,
  2850. ),
  2851. ).toBe(true);
  2852. expect(
  2853. deltas.some(
  2854. (delta) => delta.op === "state.updated" && delta.patch.subagents?.running.length === 1,
  2855. ),
  2856. ).toBe(true);
  2857. projection.applyEvent(
  2858. log.push(
  2859. SessionEventType.BackgroundTaskCompleted,
  2860. {
  2861. taskId: "agent-resume",
  2862. toolName: "Agent",
  2863. taskKind: "subagent",
  2864. childSessionId: "sess-child-resume",
  2865. status: "cancelled",
  2866. cancellable: false,
  2867. },
  2868. { turnId },
  2869. ),
  2870. );
  2871. projection.applyEvent(
  2872. log.push(
  2873. SessionEventType.SubagentStopped,
  2874. {
  2875. agentId: "agent-resume",
  2876. agentType: "general-purpose",
  2877. background: true,
  2878. childSessionId: "sess-child-resume",
  2879. parentToolCallId: "call-send-message",
  2880. status: "cancelled",
  2881. },
  2882. { turnId },
  2883. ),
  2884. );
  2885. const terminalSnapshot = projection.getSnapshot();
  2886. expect(terminalSnapshot.rows.window.find((row) => row.kind === "subagent")).toMatchObject({
  2887. parentToolCallId: "call-agent",
  2888. status: "cancelled",
  2889. });
  2890. expect(terminalSnapshot.backgroundWorks).toEqual([
  2891. expect.objectContaining({ workId: "agent-resume", status: "cancelled" }),
  2892. ]);
  2893. });
  2894. it("SAT24:7 个毫秒级并行 spawn 在每次 row 提交中原子发布完整 running 投影", () => {
  2895. const turnId = "turn-parallel-subagents";
  2896. const log = new EventLog();
  2897. log.push(SessionEventType.SessionCreated, {
  2898. mode: "default",
  2899. contextWindow: 1000,
  2900. });
  2901. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "并行派生" }, { turnId });
  2902. for (let index = 1; index <= 7; index += 1) {
  2903. log.push(
  2904. SessionEventType.SubagentSpawned,
  2905. {
  2906. agentId: `agent-${index}`,
  2907. agentType: "Explore",
  2908. childSessionId: `sess_child_${index}`,
  2909. description: `并行子智能体 ${index}`,
  2910. parentToolCallId: `call-agent-${index}`,
  2911. status: "running",
  2912. },
  2913. { turnId, timestampMs: 1_700_000_000_000 + index },
  2914. );
  2915. }
  2916. const projection = new ProductProjection("session-1", "epoch-1");
  2917. for (const event of log.events) {
  2918. const deltas = projection.applyEvent(event);
  2919. if (event.type !== SessionEventType.SubagentSpawned) continue;
  2920. const expectedCount = Number((event.payload as { agentId: string }).agentId.split("-")[1]);
  2921. const subagentPatch = deltas.find(
  2922. (delta) => delta.op === "state.updated" && delta.patch.subagents,
  2923. );
  2924. expect(deltas.some((delta) => delta.op === "row.appended")).toBe(true);
  2925. expect(subagentPatch).toMatchObject({
  2926. op: "state.updated",
  2927. patch: {
  2928. subagents: {
  2929. childSessionIds: expect.arrayContaining([`sess_child_${expectedCount}`]),
  2930. endedTotal: 0,
  2931. },
  2932. },
  2933. });
  2934. expect(projection.getSnapshot().subagents?.running).toHaveLength(expectedCount);
  2935. }
  2936. expect(projection.getSnapshot().subagents).toMatchObject({
  2937. childSessionIds: Array.from({ length: 7 }, (_, index) => `sess_child_${index + 1}`),
  2938. endedTotal: 0,
  2939. });
  2940. expect(projection.getSnapshot().subagents?.running).toHaveLength(7);
  2941. });
  2942. it("SAT22:cold seed 持续排除未持久化 ghost,直到新的合法 spawn", () => {
  2943. const turnId = "turn-cold-subagent-seed";
  2944. const log = new EventLog();
  2945. log.push(SessionEventType.SessionCreated, {
  2946. mode: "default",
  2947. contextWindow: 1000,
  2948. });
  2949. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "历史派生" }, { turnId });
  2950. log.push(
  2951. SessionEventType.SubagentSpawned,
  2952. {
  2953. agentId: "agent-reliable",
  2954. agentType: "Explore",
  2955. childSessionId: "sess-reliable",
  2956. description: "可靠 child",
  2957. status: "running",
  2958. },
  2959. { turnId },
  2960. );
  2961. log.push(
  2962. SessionEventType.SubagentSpawned,
  2963. {
  2964. agentId: "agent-ghost",
  2965. agentType: "Explore",
  2966. childSessionId: "sess-ghost",
  2967. description: "旧版本 ghost",
  2968. status: "running",
  2969. },
  2970. { turnId },
  2971. );
  2972. const projection = new ProductProjection("session-1", "epoch-1");
  2973. for (const event of log.events) projection.applyEvent(event);
  2974. projection.seedSubagents({
  2975. revision: 10,
  2976. childSessionIds: ["sess-reliable"],
  2977. running: [
  2978. {
  2979. agentId: "agent-reliable",
  2980. childSessionId: "sess-reliable",
  2981. status: "running",
  2982. subagentType: "Explore",
  2983. title: "可靠 child",
  2984. },
  2985. ],
  2986. });
  2987. expect(projection.getSnapshot().subagents).toMatchObject({
  2988. revision: 10,
  2989. childSessionIds: ["sess-reliable"],
  2990. running: [{ childSessionId: "sess-reliable" }],
  2991. endedTotal: 0,
  2992. });
  2993. projection.applyEvent(
  2994. log.push(SessionEventType.ModelSelected, {
  2995. modelSelection: {
  2996. providerId: "test-provider",
  2997. modelId: "test-model",
  2998. },
  2999. }),
  3000. );
  3001. expect(projection.getSnapshot().subagents?.childSessionIds).toEqual(["sess-reliable"]);
  3002. projection.applyEvent(
  3003. log.push(
  3004. SessionEventType.SubagentSpawned,
  3005. {
  3006. agentId: "agent-ghost",
  3007. agentType: "Explore",
  3008. childSessionId: "sess-ghost",
  3009. description: "已持久化后恢复",
  3010. resumed: true,
  3011. status: "running",
  3012. },
  3013. { turnId },
  3014. ),
  3015. );
  3016. expect(projection.getSnapshot().subagents?.childSessionIds).toEqual([
  3017. "sess-reliable",
  3018. "sess-ghost",
  3019. ]);
  3020. expect(projection.getSnapshot().subagents?.running).toHaveLength(2);
  3021. });
  3022. it("SAT22:非空 cold manifest 即使旧查询 revision 为 0 也会建立有效版本", () => {
  3023. const projection = new ProductProjection("session-1", "epoch-1");
  3024. projection.seedSubagents({
  3025. revision: 0,
  3026. childSessionIds: ["sess-reliable"],
  3027. running: [],
  3028. });
  3029. expect(projection.getSnapshot().subagents).toMatchObject({
  3030. revision: 1,
  3031. childSessionIds: ["sess-reliable"],
  3032. endedTotal: 1,
  3033. });
  3034. });
  3035. // ── M 组:turn steer 队列 ──
  3036. it("M:steer 入队/注入 —— queue.items 生命周期", () => {
  3037. const turnId = "turn-1";
  3038. const log = new EventLog();
  3039. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3040. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  3041. log.push(
  3042. SessionEventType.TurnSteerQueued,
  3043. {
  3044. pendingInputId: "pi-1",
  3045. inputId: "command-original",
  3046. input: "顺便加个测试",
  3047. inputPreview: "顺便加个测试",
  3048. inputSize: 6,
  3049. targetTurnId: turnId,
  3050. queueLength: 1,
  3051. delivery: "guide",
  3052. intent: {
  3053. sourceCommandId: "command-original",
  3054. queueItemId: "pi-1",
  3055. clientId: "mobile-client",
  3056. kind: "sendText",
  3057. admissionSeq: 12,
  3058. admittedAt: 1234,
  3059. requestedDelivery: "guide",
  3060. admittedDelivery: "guide",
  3061. highspeed: {
  3062. schemaVersion: 1,
  3063. cardId: "hsc-queue",
  3064. taskId: "session-1",
  3065. provider: "builtin:bigmodel-coding-plan",
  3066. model: "GLM-5.3",
  3067. issuedAt: 1_700_000_000_000,
  3068. expiresAt: 1_700_000_900_000,
  3069. },
  3070. attachmentRefs: [
  3071. { ref: "artifact://one", fileName: "one.txt", mime: "text/plain", bytes: 3 },
  3072. ],
  3073. },
  3074. },
  3075. { turnId },
  3076. );
  3077. const { projection } = runAll(log.events);
  3078. expect(projection.getSnapshot().queue.items).toHaveLength(1);
  3079. expect(projection.getSnapshot().queue.items[0]).toMatchObject({
  3080. queueItemId: "pi-1",
  3081. kind: "sendText",
  3082. text: "顺便加个测试",
  3083. sourceCommandId: "command-original",
  3084. clientId: "mobile-client",
  3085. attachments: [{ ref: "artifact://one", fileName: "one.txt", mime: "text/plain", bytes: 3 }],
  3086. delivery: { requested: "guide", admitted: "guide" },
  3087. order: { admissionSeq: 12, queuePosition: 0 },
  3088. steer: { state: "steering" },
  3089. dispatch: { state: "queued" },
  3090. highspeed: { cardId: "hsc-queue", expiresAt: 1_700_000_900_000 },
  3091. admittedAt: 1234,
  3092. });
  3093. const drain = new EventLog();
  3094. drain.push(
  3095. SessionEventType.TurnSteerDrained,
  3096. {
  3097. pendingInputIds: ["pi-1"],
  3098. targetTurnId: turnId,
  3099. injectedMessageIds: ["message-drained"],
  3100. drainedInputs: [
  3101. {
  3102. pendingInputId: "pi-1",
  3103. messageId: "message-drained",
  3104. text: "顺便加个测试",
  3105. delivery: "guide",
  3106. intent: {
  3107. sourceCommandId: "command-original",
  3108. queueItemId: "pi-1",
  3109. clientId: "mobile-client",
  3110. kind: "sendText",
  3111. admissionSeq: 12,
  3112. admittedAt: 1234,
  3113. requestedDelivery: "guide",
  3114. admittedDelivery: "guide",
  3115. attachmentRefs: [
  3116. {
  3117. ref: "artifact://one",
  3118. fileName: "one.txt",
  3119. mime: "text/plain",
  3120. bytes: 3,
  3121. },
  3122. ],
  3123. },
  3124. },
  3125. ],
  3126. },
  3127. { turnId },
  3128. );
  3129. for (const event of drain.events) projection.applyEvent(event);
  3130. expect(projection.getSnapshot().queue.items).toHaveLength(0);
  3131. expect(projection.getSnapshot().rows.window.at(-1)).toMatchObject({
  3132. kind: "userInput",
  3133. text: "顺便加个测试",
  3134. guided: true,
  3135. sourceCommandId: "command-original",
  3136. clientId: "mobile-client",
  3137. attachments: [{ ref: "artifact://one", fileName: "one.txt", mime: "text/plain", bytes: 3 }],
  3138. });
  3139. });
  3140. it("M:goal command 入队 —— queue item 保留 sendGoalCommand kind", () => {
  3141. const turnId = "turn-1";
  3142. const log = new EventLog();
  3143. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3144. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  3145. log.push(
  3146. SessionEventType.TurnSteerQueued,
  3147. {
  3148. pendingInputId: "pi-goal",
  3149. commandKind: "sendGoalCommand",
  3150. input: "/goal 新目标",
  3151. inputPreview: "/goal 新目标",
  3152. inputSize: 12,
  3153. targetTurnId: turnId,
  3154. queueLength: 1,
  3155. },
  3156. { turnId },
  3157. );
  3158. const { projection } = runAll(log.events);
  3159. expect(projection.getSnapshot().queue.items[0]).toMatchObject({
  3160. queueItemId: "pi-goal",
  3161. kind: "sendGoalCommand",
  3162. text: "/goal 新目标",
  3163. });
  3164. });
  3165. it("M:guide/附件 fallback 保留 requested/admitted 与 reasonCode", () => {
  3166. const log = new EventLog();
  3167. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3168. log.push(
  3169. SessionEventType.TurnSteerQueued,
  3170. {
  3171. pendingInputId: "queue-fallback",
  3172. inputId: "command-fallback",
  3173. input: "带附件",
  3174. inputPreview: "带附件",
  3175. inputSize: 9,
  3176. delivery: "queue",
  3177. targetTurnId: "turn-1",
  3178. queueLength: 1,
  3179. intent: {
  3180. sourceCommandId: "command-fallback",
  3181. queueItemId: "queue-fallback",
  3182. clientId: "desktop-client",
  3183. kind: "sendText",
  3184. admissionSeq: 2,
  3185. admittedAt: 50,
  3186. requestedDelivery: "guide",
  3187. admittedDelivery: "queue",
  3188. fallbackReasonCode: "guide.attachmentsUnsupported",
  3189. attachmentRefs: [
  3190. { ref: "artifact://a", fileName: "a.txt", mime: "text/plain", bytes: 1 },
  3191. ],
  3192. },
  3193. },
  3194. { turnId: "turn-1" },
  3195. );
  3196. const { projection } = runAll(log.events);
  3197. expect(projection.getSnapshot().queue.items[0]).toMatchObject({
  3198. sourceCommandId: "command-fallback",
  3199. attachments: [{ ref: "artifact://a" }],
  3200. delivery: {
  3201. requested: "guide",
  3202. admitted: "queue",
  3203. fallbackReasonCode: "guide.attachmentsUnsupported",
  3204. },
  3205. steer: { state: "fellBack", reasonCode: "guide.attachmentsUnsupported" },
  3206. });
  3207. });
  3208. it("M:text-only terminal 以 delivery changed 原地把 guide 改投 queue", () => {
  3209. const log = new EventLog();
  3210. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3211. log.push(
  3212. SessionEventType.TurnSteerQueued,
  3213. {
  3214. pendingInputId: "queue-guide-terminal",
  3215. input: "等下一个工具边界",
  3216. inputPreview: "等下一个工具边界",
  3217. inputSize: 9,
  3218. delivery: "guide",
  3219. targetTurnId: "turn-1",
  3220. queueLength: 1,
  3221. intent: {
  3222. sourceCommandId: "command-guide-terminal",
  3223. queueItemId: "queue-guide-terminal",
  3224. clientId: "desktop-client",
  3225. kind: "sendText",
  3226. admissionSeq: 3,
  3227. admittedAt: 60,
  3228. requestedDelivery: "guide",
  3229. admittedDelivery: "guide",
  3230. },
  3231. },
  3232. { turnId: "turn-1" },
  3233. );
  3234. log.push(
  3235. SessionEventType.TurnSteerDeliveryChanged,
  3236. {
  3237. pendingInputId: "queue-guide-terminal",
  3238. targetTurnId: "turn-1",
  3239. requestedDelivery: "guide",
  3240. admittedDelivery: "queue",
  3241. fallbackReasonCode: "guide.noToolBoundary",
  3242. },
  3243. { turnId: "turn-1" },
  3244. );
  3245. const { projection } = runAll(log.events);
  3246. expect(projection.getSnapshot().queue.items).toEqual([
  3247. expect.objectContaining({
  3248. queueItemId: "queue-guide-terminal",
  3249. text: "等下一个工具边界",
  3250. delivery: {
  3251. requested: "guide",
  3252. admitted: "queue",
  3253. fallbackReasonCode: "guide.noToolBoundary",
  3254. },
  3255. steer: { state: "fellBack", reasonCode: "guide.noToolBoundary" },
  3256. }),
  3257. ]);
  3258. });
  3259. // ── 错误态 ──
  3260. it("错误:turn_error → phase=error + lastError + turnHeader failed", () => {
  3261. const turnId = "turn-1";
  3262. const log = new EventLog();
  3263. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3264. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  3265. log.push(
  3266. SessionEventType.TurnError,
  3267. { error: { type: "ProviderError", message: "rate limited" }, turnPhase: "model" },
  3268. { turnId },
  3269. );
  3270. const { projection } = runAll(log.events);
  3271. const snapshot = projection.getSnapshot();
  3272. expect(snapshot.control.phase).toBe("error");
  3273. expect(snapshot.control.lastError).toMatchObject({
  3274. code: "ProviderError",
  3275. message: "rate limited",
  3276. recoverable: true,
  3277. source: "runtime",
  3278. });
  3279. expect(snapshot.rows.window.find((row) => row.kind === "turnHeader")).toMatchObject({
  3280. state: "failed",
  3281. });
  3282. });
  3283. it("错误:TurnError 保留底层错误详情到 V4 lastError", () => {
  3284. const log = new EventLog();
  3285. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3286. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  3287. log.push(
  3288. SessionEventType.TurnError,
  3289. {
  3290. error: {
  3291. type: "ModelError",
  3292. message: "Model request failed",
  3293. underlyingErrorMessage: "Runtime headers request failed",
  3294. underlyingErrorDetail: "Runtime headers helper timed out after 10000ms.",
  3295. },
  3296. turnPhase: "model",
  3297. },
  3298. { turnId: "turn-1" },
  3299. );
  3300. expect(runAll(log.events).projection.getSnapshot().control.lastError).toMatchObject({
  3301. underlyingErrorMessage: "Runtime headers request failed",
  3302. underlyingErrorDetail: "Runtime headers helper timed out after 10000ms.",
  3303. });
  3304. });
  3305. it("错误:TurnError 保留 future queue 并暂停自动消费", () => {
  3306. const turnId = "turn-error-queue";
  3307. const log = new EventLog();
  3308. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3309. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "首轮失败" }, { turnId });
  3310. log.push(
  3311. SessionEventType.TurnSteerQueued,
  3312. {
  3313. pendingInputId: "queue-after-error",
  3314. inputId: "input-after-error",
  3315. input: "错误后仍要发送",
  3316. inputPreview: "错误后仍要发送",
  3317. inputSize: 24,
  3318. targetTurnId: turnId,
  3319. queueLength: 1,
  3320. delivery: "queue",
  3321. },
  3322. { turnId },
  3323. );
  3324. log.push(
  3325. SessionEventType.TurnError,
  3326. { error: { type: "ProviderError", message: "provider 失败" }, turnPhase: "model" },
  3327. { turnId },
  3328. );
  3329. const { projection } = runAll(log.events);
  3330. const snapshot = projection.getSnapshot();
  3331. expect(snapshot.control.phase).toBe("error");
  3332. expect(snapshot.queue).toMatchObject({
  3333. autoDrain: false,
  3334. pauseReason: "error",
  3335. items: [expect.objectContaining({ queueItemId: "queue-after-error" })],
  3336. });
  3337. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  3338. });
  3339. it.each([true, false])("错误:TurnError retryable=%s 原样映射 recoverable", (retryable) => {
  3340. const turnId = "turn-retryable";
  3341. const log = new EventLog();
  3342. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3343. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  3344. log.push(
  3345. SessionEventType.TurnError,
  3346. {
  3347. error: { type: "ProviderError", message: "failed", retryable },
  3348. turnPhase: "model",
  3349. },
  3350. { turnId },
  3351. );
  3352. const { projection } = runAll(log.events);
  3353. expect(projection.getSnapshot().control.lastError?.recoverable).toBe(retryable);
  3354. });
  3355. it("错误:TurnError 结构化归因进入 lastError,但不改写既有 recoverable", () => {
  3356. const turnId = "turn-attribution";
  3357. const log = new EventLog();
  3358. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3359. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  3360. log.push(
  3361. SessionEventType.TurnError,
  3362. {
  3363. error: {
  3364. type: "model_request_failed",
  3365. message: "Provider stream failed",
  3366. attribution: {
  3367. source: "network",
  3368. reason: "network_error",
  3369. providerId: "default-deepseek",
  3370. modelId: "deepseek-v4-flash",
  3371. providerKind: "anthropic",
  3372. transport: "sse",
  3373. statusCode: 503,
  3374. retryable: false,
  3375. },
  3376. },
  3377. turnPhase: "model",
  3378. },
  3379. { turnId },
  3380. );
  3381. const { projection } = runAll(log.events);
  3382. const snapshot = projection.getSnapshot();
  3383. expect(snapshot.control.lastError).toMatchObject({
  3384. source: "network",
  3385. recoverable: true,
  3386. attribution: {
  3387. source: "network",
  3388. reason: "network_error",
  3389. providerId: "default-deepseek",
  3390. modelId: "deepseek-v4-flash",
  3391. providerKind: "anthropic",
  3392. transport: "sse",
  3393. statusCode: 503,
  3394. retryable: false,
  3395. },
  3396. });
  3397. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  3398. });
  3399. it("错误后新 turn 清除 lastError(与旧 reducer 同一裁决)", () => {
  3400. const log = new EventLog();
  3401. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3402. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  3403. log.push(
  3404. SessionEventType.TurnError,
  3405. { error: { type: "X", message: "boom" }, turnPhase: "model" },
  3406. { turnId: "turn-1" },
  3407. );
  3408. log.push(SessionEventType.TurnStarted, { turnNumber: 2, input: "retry" }, { turnId: "turn-2" });
  3409. const { projection } = runAll(log.events);
  3410. expect(projection.getSnapshot().control.lastError).toBeNull();
  3411. expect(projection.getSnapshot().control.phase).toBe("running");
  3412. });
  3413. it("K10:retry 目标只允许全时间线最后一条 assistantText row", () => {
  3414. const log = new EventLog();
  3415. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3416. for (const turnNumber of [1, 2]) {
  3417. const turnId = `turn-${turnNumber}`;
  3418. log.push(
  3419. SessionEventType.TurnStarted,
  3420. { turnNumber, input: `Q${turnNumber}`, messageId: `user-${turnNumber}` },
  3421. { turnId },
  3422. );
  3423. log.push(
  3424. SessionEventType.ModelStreaming,
  3425. {
  3426. kind: "text_start",
  3427. delta: "",
  3428. done: false,
  3429. assistantMessageId: `assistant-${turnNumber}`,
  3430. },
  3431. { turnId },
  3432. );
  3433. log.push(
  3434. SessionEventType.ModelStreaming,
  3435. { kind: "text_delta", delta: `A${turnNumber}`, done: false },
  3436. { turnId },
  3437. );
  3438. log.push(
  3439. SessionEventType.ModelStreaming,
  3440. { kind: "text_end", delta: "", done: false },
  3441. { turnId },
  3442. );
  3443. log.push(
  3444. SessionEventType.TurnComplete,
  3445. {
  3446. response: `A${turnNumber}`,
  3447. tokenCount: 1,
  3448. toolCallCount: 0,
  3449. duration: 100,
  3450. resultType: "success",
  3451. },
  3452. { turnId },
  3453. );
  3454. }
  3455. const { projection } = runAll(log.events);
  3456. const assistantRows = projection
  3457. .getSnapshot()
  3458. .rows.window.filter((row) => row.kind === "assistantText");
  3459. expect(assistantRows).toHaveLength(2);
  3460. expect(projection.isLatestRetryAssistantRow(assistantRows[0]!.rowId)).toBe(false);
  3461. expect(projection.isLatestRetryAssistantRow(assistantRows[1]!.rowId)).toBe(true);
  3462. expect(assistantRows[0]!.actions?.canRetry).not.toBe(true);
  3463. expect(assistantRows[1]!.actions?.canRetry).toBe(true);
  3464. expect(projection.getMessageIdForRow(assistantRows[1]!.rowId)).toBe("assistant-2");
  3465. });
  3466. it("BG33/K11:background 结果轮无普通 retry,且不会恢复更早真实用户轮", () => {
  3467. const log = new EventLog();
  3468. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  3469. const { projection } = runAll(log.events);
  3470. const apply = (type: SessionEventTypeUnion, payload: unknown, turnId: string): void => {
  3471. projection.applyEvent(log.push(type, payload, { turnId }));
  3472. };
  3473. const appendCompletedTurn = (input: {
  3474. assistantMessageId: string;
  3475. input: string;
  3476. inputSource?: "background_task";
  3477. messageId: string;
  3478. turnId: string;
  3479. turnNumber: number;
  3480. }): void => {
  3481. apply(
  3482. SessionEventType.TurnStarted,
  3483. {
  3484. turnNumber: input.turnNumber,
  3485. input: input.input,
  3486. messageId: input.messageId,
  3487. ...(input.inputSource
  3488. ? { inputSource: input.inputSource, inputVisibility: "model-only" }
  3489. : {}),
  3490. },
  3491. input.turnId,
  3492. );
  3493. apply(
  3494. SessionEventType.ModelStreaming,
  3495. {
  3496. kind: "text_start",
  3497. delta: "",
  3498. done: false,
  3499. assistantMessageId: input.assistantMessageId,
  3500. },
  3501. input.turnId,
  3502. );
  3503. apply(
  3504. SessionEventType.ModelStreaming,
  3505. { kind: "text_delta", delta: `answer ${input.turnNumber}`, done: false },
  3506. input.turnId,
  3507. );
  3508. apply(
  3509. SessionEventType.ModelStreaming,
  3510. { kind: "text_end", delta: "", done: false },
  3511. input.turnId,
  3512. );
  3513. apply(
  3514. SessionEventType.TurnComplete,
  3515. {
  3516. response: `answer ${input.turnNumber}`,
  3517. tokenCount: 1,
  3518. toolCallCount: 0,
  3519. duration: 100,
  3520. resultType: "success",
  3521. },
  3522. input.turnId,
  3523. );
  3524. };
  3525. appendCompletedTurn({
  3526. assistantMessageId: "assistant-user-1",
  3527. input: "Q1",
  3528. messageId: "user-1",
  3529. turnId: "turn-user-1",
  3530. turnNumber: 1,
  3531. });
  3532. let assistantRows = projection
  3533. .getSnapshot()
  3534. .rows.window.filter((row) => row.kind === "assistantText");
  3535. expect(assistantRows.map((row) => row.actions?.canRetry === true)).toEqual([true]);
  3536. appendCompletedTurn({
  3537. assistantMessageId: "assistant-background-1",
  3538. input: "background result",
  3539. inputSource: "background_task",
  3540. messageId: "wake-1",
  3541. turnId: "turn-background-1",
  3542. turnNumber: 2,
  3543. });
  3544. assistantRows = projection
  3545. .getSnapshot()
  3546. .rows.window.filter((row) => row.kind === "assistantText");
  3547. expect(assistantRows.map((row) => row.actions?.canRetry === true)).toEqual([false, false]);
  3548. expect(assistantRows[1]!.actions?.canFork).toBe(true);
  3549. const backgroundEntityId = projection.getEntityIdForRow(assistantRows[1]!.rowId);
  3550. expect(backgroundEntityId).toBeTruthy();
  3551. expect(
  3552. projection.resolveRowActionTarget(
  3553. { rowId: assistantRows[1]!.rowId, entityId: backgroundEntityId! },
  3554. "retryTurn",
  3555. ),
  3556. ).toEqual({ ok: false, status: "rejected", reasonCode: "guard.actionUnavailable" });
  3557. appendCompletedTurn({
  3558. assistantMessageId: "assistant-user-2",
  3559. input: "Q2",
  3560. messageId: "user-2",
  3561. turnId: "turn-user-2",
  3562. turnNumber: 3,
  3563. });
  3564. assistantRows = projection
  3565. .getSnapshot()
  3566. .rows.window.filter((row) => row.kind === "assistantText");
  3567. expect(assistantRows.map((row) => row.actions?.canRetry === true)).toEqual([
  3568. false,
  3569. false,
  3570. true,
  3571. ]);
  3572. });
  3573. });
  3574. describe("V4 API 重试状态投影", () => {
  3575. function runningProjection(): { log: EventLog; projection: ProductProjection } {
  3576. const log = new EventLog();
  3577. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  3578. log.push(
  3579. SessionEventType.TurnStarted,
  3580. { turnNumber: 1, input: "触发模型请求", messageId: "user-retry-1" },
  3581. { turnId: "turn-retry-1" },
  3582. );
  3583. return { log, projection: runAll(log.events).projection };
  3584. }
  3585. function modelStatus(overrides: Record<string, unknown>): Record<string, unknown> {
  3586. return {
  3587. timestamp: "2026-07-14T07:25:25.985Z",
  3588. traceId: "trace-1",
  3589. requestId: "request-retry-1",
  3590. model: { providerId: "bigmodel", modelId: "glm-5.2" },
  3591. transport: "sse",
  3592. attempt: 1,
  3593. maxAttempts: 11,
  3594. ...overrides,
  3595. };
  3596. }
  3597. it("429 重试在两个 delivery profile 中可见,并保持到首次有效模型进展", () => {
  3598. const { log, projection } = runningProjection();
  3599. const scheduledAt = 1_721_000_000_000;
  3600. const scheduled = log.push(
  3601. SessionEventType.ModelNetworkStatus,
  3602. modelStatus({
  3603. type: "model_retry_scheduled",
  3604. delayMs: 44_000,
  3605. nextAttempt: 2,
  3606. reason: "rate_limited",
  3607. message: "rate limited",
  3608. statusCode: 429,
  3609. }),
  3610. { turnId: "turn-retry-1", timestampMs: scheduledAt },
  3611. );
  3612. const retryDeltas = projection.applyEvent(scheduled);
  3613. expect(projection.getSnapshot().control.apiRetry).toEqual({
  3614. attempt: 1,
  3615. maxAttempts: 11,
  3616. nextRetryAt: scheduledAt + 44_000,
  3617. reasonCode: "fault.provider.rateLimited",
  3618. });
  3619. expect(() => conversationSnapshotSchema.parse(projection.getSnapshot())).not.toThrow();
  3620. for (const profile of [DELIVERY_PROFILES.continuous, DELIVERY_PROFILES.replayable]) {
  3621. expect(filterConversationDeltasForProfile(retryDeltas, profile)).toEqual(retryDeltas);
  3622. }
  3623. const retryStarted = log.push(
  3624. SessionEventType.ModelNetworkStatus,
  3625. modelStatus({ type: "model_request_started", attempt: 2 }),
  3626. { turnId: "turn-retry-1" },
  3627. );
  3628. expect(projection.applyEvent(retryStarted)).toEqual([]);
  3629. expect(projection.getSnapshot().control.apiRetry?.attempt).toBe(1);
  3630. projection.applyEvent(
  3631. log.push(
  3632. SessionEventType.ModelStreaming,
  3633. {
  3634. kind: "text_start",
  3635. delta: "",
  3636. done: false,
  3637. assistantMessageId: "assistant-retry-1",
  3638. },
  3639. { turnId: "turn-retry-1" },
  3640. ),
  3641. );
  3642. expect(projection.getSnapshot().control.apiRetry?.attempt).toBe(1);
  3643. projection.applyEvent(
  3644. log.push(
  3645. SessionEventType.ModelStreaming,
  3646. { kind: "text_delta", delta: "连接已恢复", done: false },
  3647. { turnId: "turn-retry-1" },
  3648. ),
  3649. );
  3650. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  3651. });
  3652. it("准入等待的两端(queued / admitted)不是 UI 状态:无 delta,apiRetry 不动(v3 决策 44)", () => {
  3653. const { log, projection } = runningProjection();
  3654. const queued = log.push(
  3655. SessionEventType.ModelNetworkStatus,
  3656. modelStatus({ type: "model_request_queued" } as never),
  3657. { turnId: "turn-queued-1" },
  3658. );
  3659. expect(projection.applyEvent(queued)).toEqual([]);
  3660. const admitted = log.push(
  3661. SessionEventType.ModelNetworkStatus,
  3662. modelStatus({ type: "model_request_admitted", queuedMs: 1200 } as never),
  3663. { turnId: "turn-queued-1" },
  3664. );
  3665. expect(projection.applyEvent(admitted)).toEqual([]);
  3666. expect(projection.getSnapshot().control.apiRetry ?? null).toBeNull();
  3667. expect(() => conversationSnapshotSchema.parse(projection.getSnapshot())).not.toThrow();
  3668. });
  3669. it("签名修复复用 provider retry live-tail 状态", () => {
  3670. const { log, projection } = runningProjection();
  3671. const scheduledAt = 1_721_000_000_000;
  3672. projection.applyEvent(
  3673. log.push(
  3674. SessionEventType.ModelNetworkStatus,
  3675. modelStatus({
  3676. type: "model_retry_scheduled",
  3677. delayMs: 0,
  3678. maxAttempts: 2,
  3679. nextAttempt: 2,
  3680. reason: "reasoning_signature_repair",
  3681. message: "thinking signature rejected",
  3682. statusCode: 400,
  3683. }),
  3684. { turnId: "turn-retry-1", timestampMs: scheduledAt },
  3685. ),
  3686. );
  3687. expect(projection.getSnapshot().control.apiRetry).toEqual({
  3688. attempt: 1,
  3689. maxAttempts: 2,
  3690. nextRetryAt: scheduledAt,
  3691. reasonCode: "fault.provider.requestFailed",
  3692. });
  3693. });
  3694. it("忽略非当前 turn 的迟到重试与完成事件", () => {
  3695. const { log, projection } = runningProjection();
  3696. const retryPayload = modelStatus({
  3697. type: "model_retry_scheduled",
  3698. delayMs: 1_000,
  3699. nextAttempt: 2,
  3700. reason: "rate_limited",
  3701. message: "rate limited",
  3702. statusCode: 429,
  3703. });
  3704. projection.applyEvent(
  3705. log.push(SessionEventType.ModelNetworkStatus, retryPayload, { turnId: "turn-stale" }),
  3706. );
  3707. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  3708. projection.applyEvent(
  3709. log.push(SessionEventType.ModelNetworkStatus, retryPayload, { turnId: "turn-retry-1" }),
  3710. );
  3711. expect(projection.getSnapshot().control.apiRetry).not.toBeNull();
  3712. projection.applyEvent(
  3713. log.push(
  3714. SessionEventType.ModelNetworkStatus,
  3715. modelStatus({ type: "model_request_completed", durationMs: 50 }),
  3716. { turnId: "turn-stale" },
  3717. ),
  3718. );
  3719. expect(projection.getSnapshot().control.apiRetry).not.toBeNull();
  3720. });
  3721. it("请求完成、不可重试失败和 turn 终态都会清理重试状态", () => {
  3722. const { log, projection } = runningProjection();
  3723. const scheduleRetry = (attempt: number) =>
  3724. projection.applyEvent(
  3725. log.push(
  3726. SessionEventType.ModelNetworkStatus,
  3727. modelStatus({
  3728. type: "model_retry_scheduled",
  3729. attempt,
  3730. delayMs: 1_000,
  3731. nextAttempt: attempt + 1,
  3732. reason: "server_error",
  3733. message: "server error",
  3734. statusCode: 503,
  3735. }),
  3736. { turnId: "turn-retry-1" },
  3737. ),
  3738. );
  3739. scheduleRetry(1);
  3740. projection.applyEvent(
  3741. log.push(
  3742. SessionEventType.ModelNetworkStatus,
  3743. modelStatus({
  3744. type: "model_request_failed",
  3745. reason: "server_error",
  3746. retryable: true,
  3747. message: "retryable",
  3748. statusCode: 503,
  3749. }),
  3750. { turnId: "turn-retry-1" },
  3751. ),
  3752. );
  3753. expect(projection.getSnapshot().control.apiRetry).not.toBeNull();
  3754. projection.applyEvent(
  3755. log.push(
  3756. SessionEventType.ModelNetworkStatus,
  3757. modelStatus({ type: "model_request_completed", attempt: 2, durationMs: 50 }),
  3758. { turnId: "turn-retry-1" },
  3759. ),
  3760. );
  3761. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  3762. scheduleRetry(2);
  3763. projection.applyEvent(
  3764. log.push(
  3765. SessionEventType.ModelNetworkStatus,
  3766. modelStatus({
  3767. type: "model_request_failed",
  3768. attempt: 3,
  3769. reason: "server_error",
  3770. retryable: false,
  3771. message: "exhausted",
  3772. statusCode: 503,
  3773. }),
  3774. { turnId: "turn-retry-1" },
  3775. ),
  3776. );
  3777. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  3778. scheduleRetry(3);
  3779. projection.applyEvent(
  3780. log.push(
  3781. SessionEventType.TurnComplete,
  3782. {
  3783. response: "done",
  3784. tokenCount: 1,
  3785. toolCallCount: 0,
  3786. duration: 100,
  3787. resultType: "success",
  3788. },
  3789. { turnId: "turn-retry-1" },
  3790. ),
  3791. );
  3792. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  3793. });
  3794. it("core SSE 恢复次数进入同一 apiRetry,并在工具进展后清理", () => {
  3795. const { log, projection } = runningProjection();
  3796. const recoveryStartedAt = 1_721_000_100_000;
  3797. projection.applyEvent(
  3798. log.push(
  3799. SessionEventType.StreamRecoveryStarted,
  3800. {
  3801. attemptId: "stream-attempt-1",
  3802. assistantMessageId: "assistant-retry-1",
  3803. failedRequestId: "request-retry-1",
  3804. failureKind: "provider_stream_error",
  3805. message: "stream disconnected",
  3806. retryNumber: 3,
  3807. maxRetries: 10,
  3808. },
  3809. { turnId: "turn-retry-1", timestampMs: recoveryStartedAt },
  3810. ),
  3811. );
  3812. expect(projection.getSnapshot().control.apiRetry).toEqual({
  3813. attempt: 3,
  3814. maxAttempts: 11,
  3815. nextRetryAt: recoveryStartedAt,
  3816. reasonCode: "fault.network.sseDisconnected",
  3817. });
  3818. projection.applyEvent(
  3819. log.push(
  3820. SessionEventType.StreamRecoveryRetryStarted,
  3821. {
  3822. attemptId: "stream-attempt-1",
  3823. anchorId: "anchor-1",
  3824. failedRequestId: "request-retry-1",
  3825. retryNumber: 3,
  3826. maxRetries: 10,
  3827. streamMode: "sse",
  3828. },
  3829. { turnId: "turn-retry-1" },
  3830. ),
  3831. );
  3832. projection.applyEvent(
  3833. log.push(
  3834. SessionEventType.ModelNetworkStatus,
  3835. modelStatus({
  3836. type: "model_request_started",
  3837. streamRecovery: {
  3838. attemptId: "stream-attempt-1",
  3839. anchorId: "anchor-1",
  3840. recoveredFromRequestId: "request-retry-1",
  3841. retryNumber: 3,
  3842. maxRetries: 10,
  3843. },
  3844. }),
  3845. { turnId: "turn-retry-1" },
  3846. ),
  3847. );
  3848. expect(projection.getSnapshot().control.apiRetry).toMatchObject({
  3849. attempt: 3,
  3850. maxAttempts: 11,
  3851. reasonCode: "fault.network.sseDisconnected",
  3852. });
  3853. projection.applyEvent(
  3854. log.push(
  3855. SessionEventType.ModelStreaming,
  3856. {
  3857. kind: "tool_input_start",
  3858. delta: "",
  3859. done: false,
  3860. toolCallId: "tool-retry-1",
  3861. toolName: "Read",
  3862. },
  3863. { turnId: "turn-retry-1" },
  3864. ),
  3865. );
  3866. expect(projection.getSnapshot().control.apiRetry).toBeNull();
  3867. });
  3868. it("reasoning-only recovery 将旧思考行收口为 interrupted,再用新行承接恢复流", () => {
  3869. const { log, projection } = runningProjection();
  3870. projection.applyEvent(
  3871. log.push(
  3872. SessionEventType.ModelStreaming,
  3873. { kind: "reasoning_start", delta: "", done: false },
  3874. { turnId: "turn-retry-1" },
  3875. ),
  3876. );
  3877. projection.applyEvent(
  3878. log.push(
  3879. SessionEventType.ModelStreaming,
  3880. { kind: "reasoning_delta", delta: "unfinished", done: false },
  3881. { turnId: "turn-retry-1" },
  3882. ),
  3883. );
  3884. projection.applyEvent(
  3885. log.push(
  3886. SessionEventType.StreamRecoveryTailDiscarded,
  3887. {
  3888. attemptId: "stream-attempt-1",
  3889. anchorId: "anchor-1",
  3890. assistantMessageId: "assistant-retry-1",
  3891. discardedReasoningBytes: 10,
  3892. discardedTextBytes: 0,
  3893. discardedToolCallIds: [],
  3894. },
  3895. { turnId: "turn-retry-1" },
  3896. ),
  3897. );
  3898. expect(projection.getSnapshot().rows.window.filter((row) => row.kind === "reasoning")).toEqual([
  3899. expect.objectContaining({ state: "interrupted", text: "unfinished" }),
  3900. ]);
  3901. projection.applyEvent(
  3902. log.push(
  3903. SessionEventType.ModelStreaming,
  3904. { kind: "reasoning_delta", delta: "fresh", done: false },
  3905. { turnId: "turn-retry-1" },
  3906. ),
  3907. );
  3908. expect(
  3909. projection
  3910. .getSnapshot()
  3911. .rows.window.filter((row) => row.kind === "reasoning")
  3912. .map((row) => ({ state: row.state, text: row.text })),
  3913. ).toEqual([
  3914. { state: "interrupted", text: "unfinished" },
  3915. { state: "streaming", text: "fresh" },
  3916. ]);
  3917. });
  3918. it("tail_discarded 收口未定稿的流式 tool row,已提交的 running 行不动,恢复流用新 id 重开", () => {
  3919. const { log, projection } = runningProjection();
  3920. const turnId = "turn-retry-1";
  3921. // 已提交并在执行中的工具:它的终态由 executor 发布,recovery 不能替它收口。
  3922. projection.applyEvent(
  3923. log.push(
  3924. SessionEventType.ToolCallScheduled,
  3925. {
  3926. toolCallId: "tool-committed",
  3927. assistantMessageId: "assistant-retry-1",
  3928. toolName: "Read",
  3929. input: { file_path: "a.ts" },
  3930. schedule: { parallelGroups: [["tool-committed"]], executionOrder: ["tool-committed"] },
  3931. },
  3932. { turnId },
  3933. ),
  3934. );
  3935. projection.applyEvent(
  3936. log.push(
  3937. SessionEventType.ToolCallStarted,
  3938. { toolCallId: "tool-committed", toolName: "Read", startedAt: new Date() },
  3939. { turnId },
  3940. ),
  3941. );
  3942. // 断流时只写到一半的 CreateWorkflow:tool_input_start 已开行,tool_call 永远不会来。
  3943. projection.applyEvent(
  3944. log.push(
  3945. SessionEventType.ModelStreaming,
  3946. {
  3947. kind: "tool_input_start",
  3948. delta: "",
  3949. done: false,
  3950. toolCallId: "tool-orphan",
  3951. toolName: "CreateWorkflow",
  3952. },
  3953. { turnId },
  3954. ),
  3955. );
  3956. projection.applyEvent(
  3957. log.push(
  3958. SessionEventType.ModelStreaming,
  3959. {
  3960. kind: "tool_input_delta",
  3961. delta: '{"script":"const a = agent(',
  3962. done: false,
  3963. toolCallId: "tool-orphan",
  3964. },
  3965. { turnId },
  3966. ),
  3967. );
  3968. projection.applyEvent(
  3969. log.push(
  3970. SessionEventType.StreamRecoveryTailDiscarded,
  3971. {
  3972. attemptId: "stream-attempt-1",
  3973. anchorId: "anchor-1",
  3974. assistantMessageId: "assistant-retry-1",
  3975. discardedReasoningBytes: 0,
  3976. discardedTextBytes: 12,
  3977. discardedToolCallIds: [],
  3978. },
  3979. { turnId },
  3980. ),
  3981. );
  3982. const toolRows = () =>
  3983. projection
  3984. .getSnapshot()
  3985. .rows.window.filter((row) => row.kind === "toolCall")
  3986. .map((row) => ({
  3987. toolCallId: row.toolCallId,
  3988. status: row.status,
  3989. inputText: row.inputText,
  3990. }));
  3991. expect(toolRows()).toEqual([
  3992. { toolCallId: "tool-committed", status: "running", inputText: '{"file_path":"a.ts"}' },
  3993. { toolCallId: "tool-orphan", status: "cancelled", inputText: '{"script":"const a = agent(' },
  3994. ]);
  3995. // 恢复请求重新写脚本:新 id 开新行,旧行保持已收口,不会并排两张「正在编写工作流」。
  3996. projection.applyEvent(
  3997. log.push(
  3998. SessionEventType.ModelStreaming,
  3999. {
  4000. kind: "tool_input_start",
  4001. delta: "",
  4002. done: false,
  4003. toolCallId: "tool-retry",
  4004. toolName: "CreateWorkflow",
  4005. },
  4006. { turnId },
  4007. ),
  4008. );
  4009. expect(toolRows().map((row) => [row.toolCallId, row.status])).toEqual([
  4010. ["tool-committed", "running"],
  4011. ["tool-orphan", "cancelled"],
  4012. ["tool-retry", "inputStreaming"],
  4013. ]);
  4014. });
  4015. });
  4016. // ── 结构性黄金测试(13-golden-test-mapping §v4 新增)──
  4017. describe("结构性不变量", () => {
  4018. function fullDeltaStream(events: readonly SessionEvent[]): {
  4019. deltasPerEvent: ConversationDelta[][];
  4020. snapshots: ConversationSnapshot[];
  4021. } {
  4022. const { deltasPerEvent, snapshots } = runAll(events);
  4023. return { deltasPerEvent, snapshots };
  4024. }
  4025. it("结构性1:任意水位 W 取 snapshot + 续流 ≡ 全量重放(R-03)", () => {
  4026. const log = new EventLog();
  4027. basicTurnEvents(log);
  4028. const { deltasPerEvent, snapshots } = fullDeltaStream(log.events);
  4029. const final = snapshots[snapshots.length - 1]!;
  4030. for (let w = 0; w < log.events.length; w++) {
  4031. const snapshotAtW = snapshots[w + 1]!;
  4032. const tail = deltasPerEvent.slice(w + 1).flat();
  4033. const resumed = applyConversationDeltas(snapshotAtW, tail);
  4034. // seq 由帧区间记账推进(不在 delta 内),对比时对齐到终值。
  4035. expect({ ...resumed, seq: final.seq }).toEqual(final);
  4036. }
  4037. });
  4038. it("结构性4(半):coalesce 后的 delta 流与逐条投递终态逐字节一致", () => {
  4039. const log = new EventLog();
  4040. basicTurnEvents(log);
  4041. const { deltasPerEvent, snapshots } = fullDeltaStream(log.events);
  4042. const base = snapshots[0]!;
  4043. const all = deltasPerEvent.flat();
  4044. const direct = applyConversationDeltas(base, all);
  4045. const coalesced = applyConversationDeltas(base, coalesceConversationDeltas(all));
  4046. expect(coalesced).toEqual(direct);
  4047. });
  4048. it("结构性10:fault 注入 session A,session B 投影逐字节不变(X 组)", () => {
  4049. const logA = new EventLog("session-a");
  4050. logA.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4051. logA.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-a" });
  4052. const logB = new EventLog("session-b");
  4053. basicTurnEvents(logB, "turn-b");
  4054. const projectionA = new ProductProjection("session-a", "epoch-1");
  4055. const projectionB = new ProductProjection("session-b", "epoch-1");
  4056. for (const event of logB.events) projectionB.applyEvent(event);
  4057. const snapshotB = structuredClone(projectionB.getSnapshot());
  4058. for (const event of logA.events) projectionA.applyEvent(event);
  4059. const fault = new EventLog("session-a");
  4060. fault.push(
  4061. SessionEventType.TurnError,
  4062. { error: { type: "fault.network.unreachable", message: "ECONNREFUSED" }, turnPhase: "model" },
  4063. { turnId: "turn-a" },
  4064. );
  4065. for (const event of fault.events) projectionA.applyEvent(event);
  4066. expect(projectionA.getSnapshot().control.phase).toBe("error");
  4067. expect(projectionB.getSnapshot()).toEqual(snapshotB);
  4068. });
  4069. it("revision 递进:结构性事件 +1 且随帧携带;纯 row.delta 不递增(R-04)", () => {
  4070. const log = new EventLog();
  4071. basicTurnEvents(log);
  4072. const { deltasPerEvent, snapshots } = fullDeltaStream(log.events);
  4073. deltasPerEvent.forEach((deltas, index) => {
  4074. const structural = deltas.some(
  4075. (delta) =>
  4076. delta.op === "row.appended" ||
  4077. delta.op === "row.upserted" ||
  4078. delta.op === "row.removed" ||
  4079. (delta.op === "state.updated" &&
  4080. Object.keys(delta.patch).some((key) => key !== "revision" && key !== "usage")),
  4081. );
  4082. const prev = snapshots[index]!.revision;
  4083. const next = snapshots[index + 1]!.revision;
  4084. if (structural) {
  4085. expect(next).toBe(prev + 1);
  4086. // 携带规则:含 revision 递增事件的帧,deltas 必含 state.updated.revision。
  4087. const carried = deltas.some(
  4088. (delta) => delta.op === "state.updated" && delta.patch.revision === next,
  4089. );
  4090. expect(carried).toBe(true);
  4091. } else {
  4092. expect(next).toBe(prev);
  4093. }
  4094. });
  4095. // 纯文本流事件(text_delta)revision 不动。
  4096. const textDeltaIndex = log.events.findIndex(
  4097. (event) =>
  4098. event.type === SessionEventType.ModelStreaming &&
  4099. (event.payload as { kind?: string }).kind === "text_delta",
  4100. );
  4101. expect(snapshots[textDeltaIndex + 1]!.revision).toBe(snapshots[textDeltaIndex]!.revision);
  4102. });
  4103. it("确定性:同一事件日志重放两次,投影与 delta 流逐字节一致(rowId 纯函数,R-04)", () => {
  4104. const log = new EventLog();
  4105. basicTurnEvents(log);
  4106. const first = runAll(log.events);
  4107. const second = runAll(log.events);
  4108. expect(second.projection.getSnapshot()).toEqual(first.projection.getSnapshot());
  4109. expect(second.deltasPerEvent).toEqual(first.deltasPerEvent);
  4110. });
  4111. });
  4112. // ── 结构性4:两 profile 终态逐字节一致(05 §delivery-profile 收敛性黄金测试)──
  4113. // 同一事件序列跑 continuous / replayable 两档 flush 管线(filter → coalesce → apply),
  4114. // 断言终态与逐条直投逐字节一致。replayable 只是中间帧少,终态必须相同——
  4115. // 这同时机械验证收口不变量:被 profile 过滤的 row.delta(inputText/output.text/
  4116. // summaryText)必须被后续不可过滤的 row.upserted 蕴含。
  4117. describe("结构性4:两 profile 终态一致", () => {
  4118. function pipelineFinalState(
  4119. events: readonly SessionEvent[],
  4120. profile: DeliveryProfile,
  4121. ): ConversationSnapshot {
  4122. const { deltasPerEvent, snapshots } = runAll(events);
  4123. const base = snapshots[0]!;
  4124. const piped = coalesceConversationDeltas(
  4125. filterConversationDeltasForProfile(deltasPerEvent.flat(), profile),
  4126. );
  4127. return applyConversationDeltas(base, piped);
  4128. }
  4129. function assertProfileConvergence(events: readonly SessionEvent[]): void {
  4130. const { deltasPerEvent, snapshots } = runAll(events);
  4131. const direct = applyConversationDeltas(snapshots[0]!, deltasPerEvent.flat());
  4132. expect(pipelineFinalState(events, DELIVERY_PROFILES.continuous)).toEqual(direct);
  4133. expect(pipelineFinalState(events, DELIVERY_PROFILES.replayable)).toEqual(direct);
  4134. }
  4135. it("基础 turn(文本流式)", () => {
  4136. const log = new EventLog();
  4137. basicTurnEvents(log);
  4138. assertProfileConvergence(log.events);
  4139. });
  4140. it("tool 输入流式 → 权限 → 执行成功(inputText 被 upsert 收口)", () => {
  4141. const turnId = "turn-1";
  4142. const log = new EventLog();
  4143. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4144. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run ls" }, { turnId });
  4145. log.push(
  4146. SessionEventType.ModelStreaming,
  4147. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-1", toolName: "bash" },
  4148. { turnId },
  4149. );
  4150. log.push(
  4151. SessionEventType.ModelStreaming,
  4152. { kind: "tool_input_delta", delta: '{"command":', done: false, toolCallId: "tc-1" },
  4153. { turnId },
  4154. );
  4155. log.push(
  4156. SessionEventType.ModelStreaming,
  4157. { kind: "tool_input_delta", delta: '"ls"}', done: false, toolCallId: "tc-1" },
  4158. { turnId },
  4159. );
  4160. log.push(
  4161. SessionEventType.ToolCallScheduled,
  4162. {
  4163. toolCallId: "tc-1",
  4164. toolName: "bash",
  4165. input: { command: "ls" },
  4166. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  4167. },
  4168. { turnId },
  4169. );
  4170. log.push(
  4171. SessionEventType.PermissionRequested,
  4172. {
  4173. requestId: "req-1",
  4174. toolCallId: "tc-1",
  4175. toolName: "bash",
  4176. riskLevel: "medium",
  4177. reason: "Run",
  4178. input: { command: "ls" },
  4179. },
  4180. { turnId },
  4181. );
  4182. log.push(
  4183. SessionEventType.PermissionResolved,
  4184. { requestId: "req-1", toolCallId: "tc-1", decision: "allow" },
  4185. { turnId },
  4186. );
  4187. log.push(
  4188. SessionEventType.ToolCallStarted,
  4189. { toolCallId: "tc-1", toolName: "bash", startedAt: new Date() },
  4190. { turnId },
  4191. );
  4192. log.push(
  4193. SessionEventType.ToolCallResult,
  4194. { toolCallId: "tc-1", result: { success: true, content: "file-a" }, duration: 42 },
  4195. { turnId },
  4196. );
  4197. log.push(
  4198. SessionEventType.TurnComplete,
  4199. { response: "done", tokenCount: 1, toolCallCount: 1, duration: 100, resultType: "success" },
  4200. { turnId },
  4201. );
  4202. assertProfileConvergence(log.events);
  4203. });
  4204. it("BG13:foreground subagent child tool 只留在 child conversation,main 仍由父 Agent 保持 running", () => {
  4205. const turnId = "turn-foreground-agent";
  4206. const parentToolCallId = "call_parent_agent";
  4207. const childToolCallId = "tool_subagent_agent-1_call_child_todo";
  4208. const mirrored = {
  4209. agentId: "agent-1",
  4210. agentType: "general-purpose",
  4211. childSessionId: "session-child-1",
  4212. childToolCallId: "call_child_todo",
  4213. description: "Inspect the project",
  4214. parentToolCallId,
  4215. source: "subagent",
  4216. };
  4217. const log = new EventLog();
  4218. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4219. log.push(
  4220. SessionEventType.TurnStarted,
  4221. { turnNumber: 1, input: "inspect with a foreground agent" },
  4222. { turnId },
  4223. );
  4224. log.push(
  4225. SessionEventType.ToolCallScheduled,
  4226. {
  4227. toolCallId: parentToolCallId,
  4228. toolName: "Agent",
  4229. input: { description: "Inspect the project", prompt: "Inspect the project" },
  4230. schedule: {
  4231. parallelGroups: [[parentToolCallId]],
  4232. executionOrder: [parentToolCallId],
  4233. },
  4234. },
  4235. { turnId },
  4236. );
  4237. log.push(
  4238. SessionEventType.ToolCallStarted,
  4239. { toolCallId: parentToolCallId, toolName: "Agent", startedAt: new Date() },
  4240. { turnId },
  4241. );
  4242. log.push(
  4243. SessionEventType.SubagentSpawned,
  4244. {
  4245. agentId: "agent-1",
  4246. agentType: "general-purpose",
  4247. childSessionId: "session-child-1",
  4248. description: "Inspect the project",
  4249. parentToolCallId,
  4250. status: "running",
  4251. },
  4252. { turnId },
  4253. );
  4254. log.push(
  4255. SessionEventType.ToolCallScheduled,
  4256. {
  4257. ...mirrored,
  4258. toolCallId: childToolCallId,
  4259. toolName: "TodoWrite",
  4260. input: { todos: [{ id: "child-only", content: "Read files", status: "in_progress" }] },
  4261. schedule: {
  4262. parallelGroups: [[childToolCallId]],
  4263. executionOrder: [childToolCallId],
  4264. },
  4265. },
  4266. { turnId },
  4267. );
  4268. log.push(
  4269. SessionEventType.ToolCallStarted,
  4270. { ...mirrored, toolCallId: childToolCallId, toolName: "TodoWrite", startedAt: new Date() },
  4271. { turnId },
  4272. );
  4273. log.push(
  4274. SessionEventType.ToolCallResult,
  4275. {
  4276. ...mirrored,
  4277. toolCallId: childToolCallId,
  4278. result: { success: true, content: "child todo updated" },
  4279. duration: 10,
  4280. },
  4281. { turnId },
  4282. );
  4283. assertProfileConvergence(log.events);
  4284. const snapshot = runAll(log.events).projection.getSnapshot();
  4285. expect(snapshot.control.phase).toBe("running");
  4286. expect(snapshot.plan).toBeNull();
  4287. expect(
  4288. snapshot.rows.window.filter((row) => row.kind === "toolCall").map((row) => row.toolCallId),
  4289. ).toEqual([parentToolCallId]);
  4290. expect(snapshot.rows.window).toContainEqual(
  4291. expect.objectContaining({
  4292. kind: "subagent",
  4293. childSessionId: "session-child-1",
  4294. parentToolCallId,
  4295. status: "running",
  4296. }),
  4297. );
  4298. const childLog = new EventLog();
  4299. childLog.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4300. childLog.push(
  4301. SessionEventType.TurnStarted,
  4302. { turnNumber: 1, input: "Inspect the project" },
  4303. { turnId: "turn-child-1" },
  4304. );
  4305. childLog.push(
  4306. SessionEventType.ToolCallScheduled,
  4307. {
  4308. toolCallId: "call_child_todo",
  4309. toolName: "TodoWrite",
  4310. input: { todos: [{ id: "child-only", content: "Read files", status: "in_progress" }] },
  4311. schedule: {
  4312. parallelGroups: [["call_child_todo"]],
  4313. executionOrder: ["call_child_todo"],
  4314. },
  4315. },
  4316. { turnId: "turn-child-1" },
  4317. );
  4318. childLog.push(
  4319. SessionEventType.ToolCallStarted,
  4320. { toolCallId: "call_child_todo", toolName: "TodoWrite", startedAt: new Date() },
  4321. { turnId: "turn-child-1" },
  4322. );
  4323. childLog.push(
  4324. SessionEventType.ToolCallResult,
  4325. {
  4326. toolCallId: "call_child_todo",
  4327. result: { success: true, content: "child todo updated" },
  4328. duration: 10,
  4329. },
  4330. { turnId: "turn-child-1" },
  4331. );
  4332. expect(childLog.events).not.toContainEqual(
  4333. expect.objectContaining({ payload: expect.objectContaining({ source: "subagent" }) }),
  4334. );
  4335. assertProfileConvergence(childLog.events);
  4336. expect(runAll(childLog.events).projection.getSnapshot().rows.window).toContainEqual(
  4337. expect.objectContaining({
  4338. kind: "toolCall",
  4339. toolCallId: "call_child_todo",
  4340. status: "success",
  4341. }),
  4342. );
  4343. });
  4344. it("BG26:真实失败 lifecycle 归并 hydration 合成行并补齐 child session 身份", () => {
  4345. const turnId = "turn-background-agent-rate-limit";
  4346. const parentToolCallId = "call-background-agent-rate-limit";
  4347. const realAgentId = "agent-background-rate-limit";
  4348. const childSessionId = "session-child-rate-limit";
  4349. const log = new EventLog();
  4350. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4351. log.push(
  4352. SessionEventType.TurnStarted,
  4353. { turnNumber: 1, input: "launch background agent" },
  4354. { turnId },
  4355. );
  4356. log.push(
  4357. SessionEventType.ToolCallScheduled,
  4358. {
  4359. toolCallId: parentToolCallId,
  4360. toolName: "Agent",
  4361. input: {
  4362. description: "Trigger provider rate limit",
  4363. prompt: "Trigger provider rate limit",
  4364. run_in_background: true,
  4365. },
  4366. schedule: {
  4367. parallelGroups: [[parentToolCallId]],
  4368. executionOrder: [parentToolCallId],
  4369. },
  4370. },
  4371. { turnId },
  4372. );
  4373. log.push(
  4374. SessionEventType.ToolCallStarted,
  4375. { toolCallId: parentToolCallId, toolName: "Agent", startedAt: new Date() },
  4376. { turnId },
  4377. );
  4378. // transcript hydration 只能从文本 tool output 合成出 toolCallId 身份,拿不到 childSessionId。
  4379. log.push(
  4380. SessionEventType.SubagentSpawned,
  4381. {
  4382. agentId: parentToolCallId,
  4383. agentType: "general-purpose",
  4384. description: "Trigger provider rate limit",
  4385. parentToolCallId,
  4386. status: "running",
  4387. },
  4388. { turnId },
  4389. );
  4390. // hydration await 窗口内补回的真实 spawned 也必须复用合成行,并建立真实 agentId 映射。
  4391. log.push(
  4392. SessionEventType.SubagentSpawned,
  4393. {
  4394. agentId: realAgentId,
  4395. agentType: "general-purpose",
  4396. background: true,
  4397. childSessionId,
  4398. description: "Trigger provider rate limit",
  4399. parentToolCallId,
  4400. status: "running",
  4401. },
  4402. { turnId },
  4403. );
  4404. // live terminal 事件携带真实 runtime 身份,必须更新上一行而不是追加重复 SubagentRow。
  4405. log.push(
  4406. SessionEventType.SubagentStopped,
  4407. {
  4408. agentId: realAgentId,
  4409. agentType: "general-purpose",
  4410. background: true,
  4411. parentToolCallId,
  4412. status: "failed",
  4413. error: "PROVIDER_ERROR: 429 rate limited",
  4414. },
  4415. { turnId },
  4416. );
  4417. const snapshot = runAll(log.events).projection.getSnapshot();
  4418. const subagentRows = snapshot.rows.window.filter(
  4419. (row): row is Extract<(typeof snapshot.rows.window)[number], { kind: "subagent" }> =>
  4420. row.kind === "subagent",
  4421. );
  4422. expect(subagentRows).toHaveLength(1);
  4423. expect(subagentRows[0]).toMatchObject({
  4424. childSessionId,
  4425. parentToolCallId,
  4426. status: "failed",
  4427. summaryText: "PROVIDER_ERROR: 429 rate limited",
  4428. });
  4429. });
  4430. it("BG35:background subagent child tool 不生成父 row,迟到终态也不复活", () => {
  4431. const turnId = "turn-background-agent";
  4432. const parentToolCallId = "call_parent_agent";
  4433. const childToolCallId = "tool_subagent_agent-1_call_child_bash";
  4434. const mirrored = {
  4435. agentId: "agent-1",
  4436. agentType: "general-purpose",
  4437. background: true,
  4438. childSessionId: "session-child-1",
  4439. childToolCallId: "call_child_bash",
  4440. description: "Run delayed Bash",
  4441. parentToolCallId,
  4442. source: "subagent",
  4443. };
  4444. const log = new EventLog();
  4445. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4446. log.push(
  4447. SessionEventType.TurnStarted,
  4448. { turnNumber: 1, input: "launch background agent" },
  4449. { turnId },
  4450. );
  4451. log.push(
  4452. SessionEventType.ToolCallScheduled,
  4453. {
  4454. toolCallId: parentToolCallId,
  4455. toolName: "Agent",
  4456. input: {
  4457. description: "Run delayed Bash",
  4458. prompt: "Run delayed Bash",
  4459. run_in_background: true,
  4460. },
  4461. schedule: {
  4462. parallelGroups: [[parentToolCallId]],
  4463. executionOrder: [parentToolCallId],
  4464. },
  4465. },
  4466. { turnId },
  4467. );
  4468. log.push(
  4469. SessionEventType.ToolCallStarted,
  4470. { toolCallId: parentToolCallId, toolName: "Agent", startedAt: new Date() },
  4471. { turnId },
  4472. );
  4473. log.push(
  4474. SessionEventType.ToolCallResult,
  4475. {
  4476. toolCallId: parentToolCallId,
  4477. result: { success: true, content: "background agent launched" },
  4478. duration: 5,
  4479. },
  4480. { turnId },
  4481. );
  4482. log.push(
  4483. SessionEventType.ToolCallScheduled,
  4484. {
  4485. ...mirrored,
  4486. toolCallId: childToolCallId,
  4487. toolName: "Bash",
  4488. input: { command: "sleep 60 && date" },
  4489. schedule: {
  4490. parallelGroups: [[childToolCallId]],
  4491. executionOrder: [childToolCallId],
  4492. },
  4493. },
  4494. { turnId },
  4495. );
  4496. log.push(
  4497. SessionEventType.ToolCallStarted,
  4498. { ...mirrored, toolCallId: childToolCallId, toolName: "Bash", startedAt: new Date() },
  4499. { turnId },
  4500. );
  4501. log.push(
  4502. SessionEventType.TurnComplete,
  4503. {
  4504. response: "launched",
  4505. tokenCount: 1,
  4506. toolCallCount: 1,
  4507. duration: 10,
  4508. resultType: "success",
  4509. },
  4510. { turnId },
  4511. );
  4512. const beforeChildTerminal = runAll(log.events).projection.getSnapshot();
  4513. expect(beforeChildTerminal.control.phase).toBe("completedSuccess");
  4514. expect(
  4515. beforeChildTerminal.rows.window
  4516. .filter((row) => row.kind === "toolCall")
  4517. .map((row) => row.toolCallId),
  4518. ).toEqual([parentToolCallId]);
  4519. log.push(
  4520. SessionEventType.ToolCallResult,
  4521. {
  4522. ...mirrored,
  4523. toolCallId: childToolCallId,
  4524. result: { success: true, content: "Fri Jul 17 12:40:36 CST 2026" },
  4525. duration: 60_000,
  4526. },
  4527. { turnId },
  4528. );
  4529. log.push(
  4530. SessionEventType.ToolCallError,
  4531. {
  4532. ...mirrored,
  4533. toolCallId: "tool_subagent_agent-1_call_child_error",
  4534. error: { type: "fault.runtime.toolFailed", message: "late child failure" },
  4535. },
  4536. { turnId },
  4537. );
  4538. assertProfileConvergence(log.events);
  4539. const terminalSnapshot = runAll(log.events).projection.getSnapshot();
  4540. expect(terminalSnapshot.control.phase).toBe("completedSuccess");
  4541. expect(
  4542. terminalSnapshot.rows.window
  4543. .filter((row) => row.kind === "toolCall")
  4544. .map((row) => row.toolCallId),
  4545. ).toEqual([parentToolCallId]);
  4546. });
  4547. it("BG18:父轮结束后的 child tool 事件不应清掉原 background Agent 控制身份", () => {
  4548. const parentTurnId = "turn-background-parent-anchor";
  4549. const followUpTurnId = "turn-background-parent-anchor-follow-up";
  4550. const parentToolCallId = "toolu_e2e_background_parent_anchor_agent";
  4551. const agentId = "agent-parent-anchor";
  4552. const childSessionId = "session-child-parent-anchor";
  4553. const log = new EventLog();
  4554. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4555. log.push(
  4556. SessionEventType.TurnStarted,
  4557. { turnNumber: 1, input: "launch background agent" },
  4558. { turnId: parentTurnId },
  4559. );
  4560. log.push(
  4561. SessionEventType.SubagentSpawned,
  4562. {
  4563. agentId,
  4564. agentType: "general-purpose",
  4565. background: true,
  4566. childSessionId,
  4567. description: "E2E background child tool parent anchor",
  4568. parentToolCallId,
  4569. status: "running",
  4570. },
  4571. { turnId: parentTurnId },
  4572. );
  4573. log.push(SessionEventType.TurnComplete, {}, { turnId: parentTurnId });
  4574. log.push(
  4575. SessionEventType.TurnStarted,
  4576. { turnNumber: 2, input: "finish a main follow-up first" },
  4577. { turnId: followUpTurnId },
  4578. );
  4579. log.push(SessionEventType.TurnComplete, {}, { turnId: followUpTurnId });
  4580. log.push(
  4581. SessionEventType.ToolCallStarted,
  4582. {
  4583. agentId,
  4584. childSessionId,
  4585. parentToolCallId,
  4586. source: "subagent",
  4587. toolCallId: "toolu_e2e_background_parent_anchor_child_bash",
  4588. toolName: "Bash",
  4589. },
  4590. { turnId: parentTurnId },
  4591. );
  4592. const snapshot = runAll(log.events).projection.getSnapshot();
  4593. expect(snapshot.subagents.running).toEqual([
  4594. expect.objectContaining({
  4595. agentId,
  4596. childSessionId,
  4597. title: "E2E background child tool parent anchor",
  4598. }),
  4599. ]);
  4600. });
  4601. it("tool 输入流到一半被 stop(cancelled 收口,inputStreaming 不悬挂)", () => {
  4602. const turnId = "turn-1";
  4603. const log = new EventLog();
  4604. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4605. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId });
  4606. log.push(
  4607. SessionEventType.ModelStreaming,
  4608. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-1", toolName: "bash" },
  4609. { turnId },
  4610. );
  4611. log.push(
  4612. SessionEventType.ModelStreaming,
  4613. { kind: "tool_input_delta", delta: '{"command":"rm', done: false, toolCallId: "tc-1" },
  4614. { turnId },
  4615. );
  4616. log.push(
  4617. SessionEventType.TurnComplete,
  4618. { response: "", tokenCount: 0, toolCallCount: 0, duration: 50, resultType: "cancelled" },
  4619. { turnId },
  4620. );
  4621. assertProfileConvergence(log.events);
  4622. // 收口语义本体:中断后 tool row 必须离开 inputStreaming(cancelled + 完整 inputText)。
  4623. const { projection } = runAll(log.events);
  4624. expect(
  4625. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  4626. ).toMatchObject({ status: "cancelled", inputText: '{"command":"rm' });
  4627. });
  4628. it("success turn 兜底收口缺少 terminal event 的 foreground tool", () => {
  4629. const turnId = "turn-1";
  4630. const log = new EventLog();
  4631. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4632. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "search" }, { turnId });
  4633. log.push(
  4634. SessionEventType.ModelStreaming,
  4635. {
  4636. kind: "tool_input_start",
  4637. delta: "",
  4638. done: false,
  4639. toolCallId: "tc-missing",
  4640. toolName: "GrepMissingFromRegistry",
  4641. },
  4642. { turnId },
  4643. );
  4644. log.push(
  4645. SessionEventType.ModelStreaming,
  4646. {
  4647. kind: "tool_input_delta",
  4648. delta: '{"pattern":"needle"}',
  4649. done: false,
  4650. toolCallId: "tc-missing",
  4651. },
  4652. { turnId },
  4653. );
  4654. log.push(
  4655. SessionEventType.PermissionRequested,
  4656. {
  4657. requestId: "req-missing",
  4658. toolCallId: "tc-missing",
  4659. toolName: "GrepMissingFromRegistry",
  4660. riskLevel: "low",
  4661. reason: "Search",
  4662. input: { pattern: "needle" },
  4663. },
  4664. { turnId },
  4665. );
  4666. log.push(
  4667. SessionEventType.TurnComplete,
  4668. { response: "done", tokenCount: 1, toolCallCount: 1, duration: 50, resultType: "success" },
  4669. { turnId },
  4670. );
  4671. assertProfileConvergence(log.events);
  4672. const { projection } = runAll(log.events);
  4673. expect(
  4674. projection.getSnapshot().rows.window.find((row) => row.kind === "toolCall"),
  4675. ).toMatchObject({
  4676. status: "error",
  4677. inputText: '{"pattern":"needle"}',
  4678. error: { code: "fault.runtime.toolLifecycleIncomplete" },
  4679. });
  4680. expect(projection.getSnapshot().pendingInteractions).toEqual([]);
  4681. });
  4682. it("reasoning 流式 + 中断", () => {
  4683. const turnId = "turn-1";
  4684. const log = new EventLog();
  4685. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4686. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "think" }, { turnId });
  4687. log.push(
  4688. SessionEventType.ModelStreaming,
  4689. { kind: "reasoning_start", delta: "", done: false },
  4690. { turnId },
  4691. );
  4692. log.push(
  4693. SessionEventType.ModelStreaming,
  4694. { kind: "reasoning_delta", delta: "hmm...", done: false },
  4695. { turnId },
  4696. );
  4697. log.push(
  4698. SessionEventType.ModelStreaming,
  4699. { kind: "text_start", delta: "", done: false },
  4700. { turnId },
  4701. );
  4702. log.push(
  4703. SessionEventType.ModelStreaming,
  4704. { kind: "text_delta", delta: "part", done: false },
  4705. { turnId },
  4706. );
  4707. log.push(
  4708. SessionEventType.TurnComplete,
  4709. { response: "", tokenCount: 0, toolCallCount: 0, duration: 10, resultType: "cancelled" },
  4710. { turnId },
  4711. );
  4712. assertProfileConvergence(log.events);
  4713. });
  4714. it("compact 生命周期(marker + usage 回落)", () => {
  4715. const log = new EventLog();
  4716. basicTurnEvents(log);
  4717. log.push(SessionEventType.CompactStarted, {
  4718. operationId: "op-1",
  4719. messageId: "msg-1",
  4720. status: "started",
  4721. trigger: "manual",
  4722. display: "separator",
  4723. sourceCommandId: "command-compact",
  4724. });
  4725. log.push(SessionEventType.CompactCompleted, {
  4726. operationId: "op-1",
  4727. messageId: "msg-1",
  4728. status: "completed",
  4729. trigger: "manual",
  4730. display: "separator",
  4731. preCompactTokenCount: 150,
  4732. postCompactTokenCount: 50,
  4733. });
  4734. assertProfileConvergence(log.events);
  4735. });
  4736. it("goal set → verify pass → fork → modelChange 全链路", () => {
  4737. const log = new EventLog();
  4738. basicTurnEvents(log);
  4739. log.push(SessionEventType.TargetChanged, {
  4740. action: "set",
  4741. source: "command",
  4742. target: {
  4743. sessionID: "session-1",
  4744. targetID: "target-1",
  4745. objective: "修绿",
  4746. summaryTitle: null,
  4747. status: "active",
  4748. tokenBudget: null,
  4749. tokensUsed: 0,
  4750. timeUsedSeconds: 0,
  4751. time: { created: 0, updated: 0 },
  4752. },
  4753. previousTarget: null,
  4754. });
  4755. log.push(SessionEventType.TargetCompletionVerification, {
  4756. targetId: "target-1",
  4757. status: "started",
  4758. verificationId: "verify-1",
  4759. goalIteration: 1,
  4760. });
  4761. log.push(SessionEventType.TargetCompletionVerification, {
  4762. targetId: "target-1",
  4763. status: "completed",
  4764. verificationId: "verify-1",
  4765. goalIteration: 1,
  4766. verification: { passed: true, reason: "ok" },
  4767. });
  4768. log.push(SessionEventType.SessionForked, {
  4769. originalSessionId: "session-1",
  4770. forkedSessionId: "session-child",
  4771. });
  4772. log.push(SessionEventType.ModelSelected, {
  4773. modelSelection: { providerId: "anthropic", modelId: "claude-4" },
  4774. });
  4775. log.push(SessionEventType.ModelSelected, {
  4776. modelSelection: { providerId: "openai", modelId: "gpt-6" },
  4777. });
  4778. assertProfileConvergence(log.events);
  4779. });
  4780. });
  4781. // ── G 组:compact marker ──
  4782. describe("compact marker(10 §4.4.7 / §6.4)", () => {
  4783. it("G:manual compact running→success —— 同一 marker row 状态迁移 + usage 回落", () => {
  4784. const log = new EventLog();
  4785. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  4786. log.push(SessionEventType.CompactStarted, {
  4787. operationId: "op-1",
  4788. messageId: "msg-marker",
  4789. status: "started",
  4790. trigger: "manual",
  4791. display: "separator",
  4792. sourceCommandId: "command-compact",
  4793. });
  4794. const { projection, deltasPerEvent } = runAll(log.events);
  4795. const runningMarker = projection
  4796. .getSnapshot()
  4797. .rows.window.find((row) => row.kind === "timelineMarker");
  4798. expect(runningMarker).toMatchObject({
  4799. sourceCommandId: "command-compact",
  4800. marker: { type: "compact", origin: "manual", status: "running" },
  4801. });
  4802. expect(deltasPerEvent[1]![0]!.op).toBe("row.appended");
  4803. projection.applyEvent(
  4804. new EventLog().push(SessionEventType.CompactCompleted, {
  4805. operationId: "op-1",
  4806. messageId: "msg-marker",
  4807. status: "completed",
  4808. trigger: "manual",
  4809. display: "separator",
  4810. sourceCommandId: "command-compact",
  4811. preCompactTokenCount: 100_000,
  4812. postCompactTokenCount: 30_000,
  4813. truePostCompactTokenCount: 20_000,
  4814. summaryMessageId: "msg-summary",
  4815. }),
  4816. );
  4817. const snapshot = projection.getSnapshot();
  4818. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  4819. const markers = snapshot.rows.window.filter((row) => row.kind === "timelineMarker");
  4820. // 全生命周期占同一行:终态是 upsert 不是新行。
  4821. expect(markers).toHaveLength(1);
  4822. expect(markers[0]).toMatchObject({
  4823. rowId: runningMarker?.rowId,
  4824. sourceCommandId: "command-compact",
  4825. marker: {
  4826. type: "compact",
  4827. origin: "manual",
  4828. status: "success",
  4829. tokensBefore: 100_000,
  4830. tokensAfter: 20_000,
  4831. summaryRef: "msg-summary",
  4832. },
  4833. });
  4834. // compact 成功 → context 水位立即回落(§6.4)。
  4835. expect(snapshot.usage.contextWindow?.usedTokens).toBe(20_000);
  4836. });
  4837. it("G12:auto compact 被 stop —— marker=cancelled,usage 不动", () => {
  4838. const log = new EventLog();
  4839. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4840. log.push(SessionEventType.CompactStarted, {
  4841. operationId: "op-1",
  4842. messageId: "msg-1",
  4843. status: "started",
  4844. trigger: "auto",
  4845. display: "separator",
  4846. });
  4847. log.push(SessionEventType.CompactFailed, {
  4848. operationId: "op-1",
  4849. messageId: "msg-1",
  4850. status: "interrupted",
  4851. trigger: "auto",
  4852. display: "separator",
  4853. });
  4854. const { projection } = runAll(log.events);
  4855. const snapshot = projection.getSnapshot();
  4856. expect(snapshot.rows.window.find((row) => row.kind === "timelineMarker")).toMatchObject({
  4857. marker: { type: "compact", origin: "auto", status: "cancelled" },
  4858. });
  4859. expect(snapshot.usage.contextWindow).toBeNull();
  4860. });
  4861. it("F09:compact 失败 —— marker=failed(retry 入口),会话状态不受污染", () => {
  4862. const log = new EventLog();
  4863. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4864. log.push(SessionEventType.CompactStarted, {
  4865. operationId: "op-1",
  4866. messageId: "msg-1",
  4867. status: "started",
  4868. trigger: "manual",
  4869. display: "separator",
  4870. });
  4871. log.push(SessionEventType.CompactFailed, {
  4872. operationId: "op-1",
  4873. messageId: "msg-1",
  4874. status: "failed",
  4875. trigger: "manual",
  4876. display: "separator",
  4877. reason: "api_error",
  4878. });
  4879. const { projection } = runAll(log.events);
  4880. const snapshot = projection.getSnapshot();
  4881. expect(snapshot.rows.window.find((row) => row.kind === "timelineMarker")).toMatchObject({
  4882. marker: { type: "compact", status: "failed" },
  4883. });
  4884. expect(snapshot.control.lastError).toBeNull();
  4885. });
  4886. });
  4887. // ── goal 状态机(10 §4.2.8)──
  4888. describe("goal 状态机", () => {
  4889. const goalTarget = (status: string, objective = "把测试全修绿") => ({
  4890. sessionID: "session-1",
  4891. targetID: "target-1",
  4892. objective,
  4893. summaryTitle: null,
  4894. status,
  4895. tokenBudget: null,
  4896. tokensUsed: 0,
  4897. timeUsedSeconds: 0,
  4898. time: { created: 0, updated: 0 },
  4899. });
  4900. it("goal set → stateOnly(不产 row)+ GoalState.active;verify pass → verified + 摘要锚点", () => {
  4901. const log = new EventLog();
  4902. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  4903. log.push(SessionEventType.TargetChanged, {
  4904. action: "set",
  4905. source: "command",
  4906. target: goalTarget("active"),
  4907. previousTarget: null,
  4908. });
  4909. log.push(SessionEventType.TargetCompletionVerification, {
  4910. targetId: "target-1",
  4911. status: "started",
  4912. verificationId: "verify-1",
  4913. foregroundExecutionId: "foreground-1",
  4914. goalIteration: 1,
  4915. });
  4916. const { projection } = runAll(log.events);
  4917. const verifying = projection.getSnapshot();
  4918. expect(verifying.goal).toMatchObject({
  4919. objective: "把测试全修绿",
  4920. status: "verifying",
  4921. iteration: 1,
  4922. });
  4923. expect(verifying.control).toMatchObject({
  4924. phase: "running",
  4925. canStop: true,
  4926. stopState: "stoppable",
  4927. stopTargetKind: "goalVerifier",
  4928. sessionEnded: false,
  4929. });
  4930. expect(verifying.control.activeWorks).toEqual([
  4931. expect.objectContaining({
  4932. kind: "goalVerifier",
  4933. foregroundExecutionId: "foreground-1",
  4934. }),
  4935. ]);
  4936. expect(verifying.inputRouting).toEqual({
  4937. mode: "enqueue",
  4938. reasonCode: "goalVerifierAcceptsFutureInput",
  4939. });
  4940. const verifyMarker = verifying.rows.window.find(
  4941. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  4942. );
  4943. expect(verifyMarker).toMatchObject({
  4944. marker: { type: "goalVerify", iteration: 1, outcome: "running" },
  4945. });
  4946. // S10(16-plan,2026-07-08 裁决):goalSet 是 stateOnly——不进 rows.window
  4947. //(旧实现产「渲染 null」的隐形行,污染 turn 分组),目标由 goal 面板承载。
  4948. expect(
  4949. verifying.rows.window.find(
  4950. (row) => row.kind === "timelineMarker" && row.marker.type === "goalSet",
  4951. ),
  4952. ).toBeUndefined();
  4953. projection.applyEvent(
  4954. new EventLog().push(SessionEventType.TargetCompletionVerification, {
  4955. targetId: "target-1",
  4956. status: "completed",
  4957. verificationId: "verify-1",
  4958. goalIteration: 1,
  4959. verification: { passed: true, reason: "全部通过" },
  4960. }),
  4961. );
  4962. const done = projection.getSnapshot();
  4963. expect(() => conversationSnapshotSchema.parse(done)).not.toThrow();
  4964. expect(done.goal).toMatchObject({ status: "verified", iteration: 1 });
  4965. expect(done.control).toMatchObject({
  4966. phase: "completedSuccess",
  4967. canStop: false,
  4968. stopState: "idle",
  4969. stopTargetKind: "unknown",
  4970. sessionEnded: true,
  4971. });
  4972. expect(done.control.activeWorks).toEqual([]);
  4973. expect(done.goal?.verifications).toEqual([
  4974. expect.objectContaining({
  4975. iteration: 1,
  4976. outcome: "pass",
  4977. anchorRowId: verifyMarker?.rowId,
  4978. }),
  4979. ]);
  4980. // marker 就地终态化(同 rowId)。
  4981. expect(
  4982. done.rows.window.find(
  4983. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  4984. ),
  4985. ).toMatchObject({
  4986. rowId: verifyMarker?.rowId,
  4987. marker: { outcome: "pass", detail: "全部通过" },
  4988. });
  4989. });
  4990. it("goal verifier 被 Stop 时暂停已有 future queue", () => {
  4991. const log = new EventLog();
  4992. log.push(SessionEventType.SessionCreated, {
  4993. mode: "default",
  4994. contextWindow: 1000,
  4995. });
  4996. log.push(SessionEventType.TargetChanged, {
  4997. action: "set",
  4998. source: "command",
  4999. target: goalTarget("active"),
  5000. previousTarget: null,
  5001. });
  5002. log.push(SessionEventType.TargetCompletionVerification, {
  5003. targetId: "target-1",
  5004. status: "started",
  5005. verificationId: "verify-stop",
  5006. foregroundExecutionId: "foreground-stop",
  5007. goalIteration: 1,
  5008. });
  5009. log.push(SessionEventType.TurnSteerQueued, {
  5010. pendingInputId: "queue-after-verifier",
  5011. inputId: "command-after-verifier",
  5012. input: "verifier 后继续的问题",
  5013. inputPreview: "verifier 后继续的问题",
  5014. inputSize: 13,
  5015. targetTurnId: "turn-goal",
  5016. queueLength: 1,
  5017. delivery: "queue",
  5018. });
  5019. log.push(SessionEventType.TargetCompletionVerification, {
  5020. targetId: "target-1",
  5021. status: "cancelled",
  5022. verificationId: "verify-stop",
  5023. foregroundExecutionId: "foreground-stop",
  5024. goalIteration: 1,
  5025. });
  5026. const { projection } = runAll(log.events);
  5027. const snapshot = projection.getSnapshot();
  5028. expect(snapshot.goal?.status).toBe("paused");
  5029. expect(snapshot.queue).toMatchObject({
  5030. autoDrain: false,
  5031. pauseReason: "stopped",
  5032. items: [expect.objectContaining({ queueItemId: "queue-after-verifier" })],
  5033. });
  5034. expect(snapshot.inputRouting).toEqual({
  5035. mode: "choice",
  5036. reasonCode: "heldQueueInputRequiresChoice",
  5037. });
  5038. });
  5039. it("M07j:sendQueuedNow 抢占 goal verifier 时不暂停 future queue", () => {
  5040. const log = new EventLog();
  5041. log.push(SessionEventType.SessionCreated, {
  5042. mode: "default",
  5043. contextWindow: 1000,
  5044. });
  5045. log.push(SessionEventType.TargetChanged, {
  5046. action: "set",
  5047. source: "command",
  5048. target: goalTarget("active"),
  5049. previousTarget: null,
  5050. });
  5051. log.push(SessionEventType.TargetCompletionVerification, {
  5052. targetId: "target-1",
  5053. status: "started",
  5054. verificationId: "verify-send-now",
  5055. foregroundExecutionId: "foreground-send-now",
  5056. goalIteration: 1,
  5057. });
  5058. log.push(SessionEventType.TurnSteerQueued, {
  5059. pendingInputId: "queue-send-now",
  5060. inputId: "command-send-now",
  5061. input: "立即发送的问题",
  5062. inputPreview: "立即发送的问题",
  5063. inputSize: 21,
  5064. targetTurnId: "turn-goal",
  5065. queueLength: 1,
  5066. delivery: "queue",
  5067. });
  5068. log.push(SessionEventType.TargetCompletionVerification, {
  5069. targetId: "target-1",
  5070. status: "cancelled",
  5071. verificationId: "verify-send-now",
  5072. foregroundExecutionId: "foreground-send-now",
  5073. preserveQueueAutoDrainOnCancel: true,
  5074. goalIteration: 1,
  5075. });
  5076. const { projection } = runAll(log.events);
  5077. const snapshot = projection.getSnapshot();
  5078. expect(snapshot.goal?.status).toBe("paused");
  5079. expect(snapshot.queue).toMatchObject({
  5080. autoDrain: true,
  5081. items: [expect.objectContaining({ queueItemId: "queue-send-now" })],
  5082. });
  5083. expect(snapshot.queue.pauseReason).toBeUndefined();
  5084. expect(snapshot.inputRouting.mode).toBe("startNow");
  5085. });
  5086. it("verify notSatisfied —— 有效结论与过程失败分离(goalVerificationOutcomeSeparation)", () => {
  5087. const log = new EventLog();
  5088. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5089. log.push(SessionEventType.TargetChanged, {
  5090. action: "set",
  5091. source: "command",
  5092. target: goalTarget("active"),
  5093. });
  5094. log.push(SessionEventType.TargetCompletionVerification, {
  5095. targetId: "target-1",
  5096. status: "started",
  5097. verificationId: "verify-1",
  5098. goalIteration: 1,
  5099. });
  5100. log.push(SessionEventType.TargetCompletionVerification, {
  5101. targetId: "target-1",
  5102. status: "completed",
  5103. verificationId: "verify-1",
  5104. goalIteration: 1,
  5105. verification: { passed: false, reason: "还有 2 个用例红" },
  5106. });
  5107. const { projection } = runAll(log.events);
  5108. expect(projection.getSnapshot().goal).toMatchObject({ status: "notSatisfied" });
  5109. expect(projection.getSnapshot().goal?.verifications[0]).toMatchObject({
  5110. outcome: "notSatisfied",
  5111. });
  5112. });
  5113. it("H13-H16:投影 target 计时/标题、verifier action 与逐轮 Todo 状态", () => {
  5114. const log = new EventLog();
  5115. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5116. log.push(SessionEventType.TargetChanged, {
  5117. action: "set",
  5118. source: "command",
  5119. target: {
  5120. ...goalTarget("active"),
  5121. summaryTitle: "第一轮:恢复摘要",
  5122. timeUsedSeconds: 7,
  5123. activeRunStartedAtMs: 1_700_000_001_000,
  5124. },
  5125. });
  5126. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "first" }, { turnId: "turn-1" });
  5127. log.push(
  5128. SessionEventType.ToolCallScheduled,
  5129. {
  5130. toolCallId: "todo-1",
  5131. toolName: "TodoWrite",
  5132. input: {
  5133. todos: [{ content: "恢复计时", status: "completed", priority: "high" }],
  5134. },
  5135. schedule: { parallelGroups: [["todo-1"]], executionOrder: ["todo-1"] },
  5136. },
  5137. { turnId: "turn-1" },
  5138. );
  5139. log.push(
  5140. SessionEventType.TurnComplete,
  5141. { response: "done", tokenCount: 1, toolCallCount: 1, duration: 1, resultType: "success" },
  5142. { turnId: "turn-1" },
  5143. );
  5144. log.push(SessionEventType.TargetCompletionVerification, {
  5145. targetId: "target-1",
  5146. status: "started",
  5147. verificationId: "verify-1",
  5148. goalIteration: 1,
  5149. });
  5150. log.push(SessionEventType.TargetCompletionVerification, {
  5151. targetId: "target-1",
  5152. status: "completed",
  5153. verificationId: "verify-1",
  5154. goalIteration: 1,
  5155. verification: {
  5156. passed: false,
  5157. reason: "还缺暂停状态",
  5158. nextAction: "第二轮:补暂停和完成态",
  5159. },
  5160. });
  5161. log.push(SessionEventType.TargetChanged, {
  5162. action: "run_started",
  5163. source: "runtime",
  5164. target: {
  5165. ...goalTarget("active"),
  5166. summaryTitle: "第一轮:恢复摘要",
  5167. timeUsedSeconds: 11,
  5168. activeRunStartedAtMs: 1_700_000_009_000,
  5169. },
  5170. });
  5171. log.push(
  5172. SessionEventType.TurnStarted,
  5173. { turnNumber: 2, input: "second" },
  5174. { turnId: "turn-2" },
  5175. );
  5176. log.push(
  5177. SessionEventType.ToolCallScheduled,
  5178. {
  5179. toolCallId: "todo-2",
  5180. toolName: "todo_write",
  5181. input: {
  5182. todos: [
  5183. { content: "恢复暂停按钮", status: "in_progress", priority: "high" },
  5184. { content: "恢复完成图标", status: "pending", priority: "medium" },
  5185. ],
  5186. },
  5187. schedule: { parallelGroups: [["todo-2"]], executionOrder: ["todo-2"] },
  5188. },
  5189. { turnId: "turn-2" },
  5190. );
  5191. const { projection } = runAll(log.events);
  5192. const snapshot = projection.getSnapshot();
  5193. expect(snapshot.goal).toMatchObject({
  5194. targetId: "target-1",
  5195. summaryTitle: "第一轮:恢复摘要",
  5196. timeUsedSeconds: 11,
  5197. activeRunStartedAtMs: 1_700_000_009_000,
  5198. status: "active",
  5199. iteration: 1,
  5200. verifications: [
  5201. expect.objectContaining({
  5202. iteration: 1,
  5203. outcome: "notSatisfied",
  5204. reason: "还缺暂停状态",
  5205. nextAction: "第二轮:补暂停和完成态",
  5206. }),
  5207. ],
  5208. iterations: [
  5209. expect.objectContaining({
  5210. iteration: 1,
  5211. items: [expect.objectContaining({ content: "恢复计时", status: "completed" })],
  5212. }),
  5213. expect.objectContaining({
  5214. iteration: 2,
  5215. items: [
  5216. expect.objectContaining({ content: "恢复暂停按钮", status: "inProgress" }),
  5217. expect.objectContaining({ content: "恢复完成图标", status: "pending" }),
  5218. ],
  5219. }),
  5220. ],
  5221. });
  5222. expect(snapshot.plan?.items).toHaveLength(2);
  5223. expect(snapshot.availability.pauseGoal).toEqual({ allowed: true });
  5224. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  5225. });
  5226. it("stopPausesActiveGoalTarget:stop(cancelled turn)把 active goal 压成 paused,resumeGoal 放行", () => {
  5227. const log = new EventLog();
  5228. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5229. log.push(SessionEventType.TargetChanged, {
  5230. action: "set",
  5231. source: "command",
  5232. target: goalTarget("active"),
  5233. });
  5234. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "go" }, { turnId: "turn-1" });
  5235. log.push(
  5236. SessionEventType.TurnComplete,
  5237. { response: "", tokenCount: 0, toolCallCount: 0, duration: 100, resultType: "cancelled" },
  5238. { turnId: "turn-1" },
  5239. );
  5240. const { projection } = runAll(log.events);
  5241. const snapshot = projection.getSnapshot();
  5242. expect(snapshot.goal).toMatchObject({ status: "paused" });
  5243. expect(snapshot.availability.resumeGoal).toEqual({ allowed: true });
  5244. // 非 paused 时 resumeGoal 被 guard 拒绝。
  5245. expect(snapshot.availability.resumeGoal.allowed).toBe(true);
  5246. });
  5247. it("verify 被 stop(cancelled)—— marker=failed(detail=cancelled),goal 回 paused,摘要不追加", () => {
  5248. const log = new EventLog();
  5249. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5250. log.push(SessionEventType.TargetChanged, {
  5251. action: "set",
  5252. source: "command",
  5253. target: goalTarget("active"),
  5254. });
  5255. log.push(SessionEventType.TargetCompletionVerification, {
  5256. targetId: "target-1",
  5257. status: "started",
  5258. verificationId: "verify-1",
  5259. goalIteration: 1,
  5260. });
  5261. log.push(SessionEventType.TargetCompletionVerification, {
  5262. targetId: "target-1",
  5263. status: "cancelled",
  5264. verificationId: "verify-1",
  5265. goalIteration: 1,
  5266. });
  5267. const { projection } = runAll(log.events);
  5268. const snapshot = projection.getSnapshot();
  5269. expect(snapshot.goal).toMatchObject({ status: "paused" });
  5270. expect(snapshot.goal?.verifications).toHaveLength(0);
  5271. expect(
  5272. snapshot.rows.window.find(
  5273. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  5274. ),
  5275. ).toMatchObject({ marker: { outcome: "failed", detail: "cancelled" } });
  5276. expect(snapshot.availability.resumeGoal).toEqual({ allowed: true });
  5277. });
  5278. it("goal cleared → GoalState=null;重复 status_updated 值未变不下发(conflation)", () => {
  5279. const log = new EventLog();
  5280. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5281. log.push(SessionEventType.TargetChanged, {
  5282. action: "set",
  5283. source: "command",
  5284. target: goalTarget("active"),
  5285. });
  5286. const { projection } = runAll(log.events);
  5287. const noop = new EventLog().push(SessionEventType.TargetChanged, {
  5288. action: "status_updated",
  5289. source: "runtime",
  5290. target: goalTarget("active"),
  5291. });
  5292. expect(projection.applyEvent(noop)).toEqual([]);
  5293. projection.applyEvent(
  5294. new EventLog().push(SessionEventType.TargetChanged, {
  5295. action: "cleared",
  5296. source: "command",
  5297. target: null,
  5298. }),
  5299. );
  5300. expect(projection.getSnapshot().goal).toBeNull();
  5301. expect(projection.getSnapshot().availability.resumeGoal).toEqual({
  5302. allowed: false,
  5303. reasonCode: "noGoalToResume",
  5304. });
  5305. });
  5306. });
  5307. // ── fork marker 与 modelChange marker ──
  5308. describe("fork / modelChange marker", () => {
  5309. it("fork:parent 时间线不显示 forkCreated(S7);child 首部 forkNotice", () => {
  5310. const parentLog = new EventLog("session-1");
  5311. basicTurnEvents(parentLog);
  5312. parentLog.push(SessionEventType.SessionForked, {
  5313. originalSessionId: "session-1",
  5314. forkedSessionId: "session-child",
  5315. targetMessageId: "msg-3",
  5316. });
  5317. const { projection: parent } = runAll(parentLog.events);
  5318. const parentSnapshot = parent.getSnapshot();
  5319. expect(() => conversationSnapshotSchema.parse(parentSnapshot)).not.toThrow();
  5320. // S7(16-plan,2026-07-08 裁决):fork 关系只在 sessions 树体现,父时间线零入侵
  5321. //(旧实现的 forkCreated 是「渲染 null」的隐形行 + nextRowId-1 近似锚点)。
  5322. expect(
  5323. parentSnapshot.rows.window.find(
  5324. (row) => row.kind === "timelineMarker" && row.marker.type === "forkCreated",
  5325. ),
  5326. ).toBeUndefined();
  5327. const childProjection = new ProductProjection("session-child", "epoch-1");
  5328. const childLog = new EventLog("session-child");
  5329. childLog.push(SessionEventType.SessionForked, {
  5330. originalSessionId: "session-1",
  5331. forkedSessionId: "session-child",
  5332. });
  5333. for (const event of childLog.events) childProjection.applyEvent(event);
  5334. expect(childProjection.getSnapshot().rows.window[0]).toMatchObject({
  5335. kind: "timelineMarker",
  5336. marker: { type: "forkNotice", parentSessionId: "session-1" },
  5337. });
  5338. });
  5339. it("modelChange(R-17 时机):marker 只在下一 turn 开始且与上一轮选型不同时产生", () => {
  5340. // 场景 1(草稿态 bug 复现,2026-07-07):turn 前任意切换选择器 → 不产 marker,
  5341. // 首轮以最终选型启动也不产(「第一次用什么模型」不构成「变化」)。
  5342. const log = new EventLog();
  5343. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5344. log.push(SessionEventType.ModelSelected, {
  5345. modelSelection: {
  5346. providerId: "anthropic",
  5347. modelId: "claude-4",
  5348. options: { reasoningLevel: "thinking" },
  5349. },
  5350. });
  5351. log.push(SessionEventType.ModelSelected, {
  5352. previousModelSelection: {
  5353. providerId: "anthropic",
  5354. modelId: "claude-4",
  5355. options: { reasoningLevel: "thinking" },
  5356. },
  5357. modelSelection: { providerId: "openai", modelId: "gpt-6" },
  5358. });
  5359. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  5360. const { projection } = runAll(log.events);
  5361. expect(projection.getSnapshot().config).toMatchObject({
  5362. provider: "openai",
  5363. model: "gpt-6",
  5364. });
  5365. expect(
  5366. projection
  5367. .getSnapshot()
  5368. .rows.window.filter(
  5369. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5370. ),
  5371. ).toHaveLength(0);
  5372. // 重复选同一配置:conflation,无 delta。
  5373. const repeat = new EventLog().push(SessionEventType.ModelSelected, {
  5374. modelSelection: { providerId: "openai", modelId: "gpt-6" },
  5375. });
  5376. expect(projection.applyEvent(repeat)).toEqual([]);
  5377. // 场景 2:turn-1 用 gpt-6,期间切换 A→B→A(净变化为零)→ turn-2 不产 marker。
  5378. projection.applyEvent(
  5379. new EventLog().push(SessionEventType.ModelSelected, {
  5380. modelSelection: { providerId: "anthropic", modelId: "claude-4" },
  5381. }),
  5382. );
  5383. projection.applyEvent(
  5384. new EventLog().push(SessionEventType.ModelSelected, {
  5385. modelSelection: { providerId: "openai", modelId: "gpt-6" },
  5386. }),
  5387. );
  5388. projection.applyEvent(
  5389. new EventLog().push(
  5390. SessionEventType.TurnStarted,
  5391. { turnNumber: 2, input: "again" },
  5392. { turnId: "turn-2" },
  5393. ),
  5394. );
  5395. expect(
  5396. projection
  5397. .getSnapshot()
  5398. .rows.window.filter(
  5399. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5400. ),
  5401. ).toHaveLength(0);
  5402. // 场景 3:切到不同选型后 turn-3 启动 → marker 落在 turnHeader 之前,
  5403. // from = 上一轮实际选型(gpt-6),to = 本轮选型(claude-4)。
  5404. projection.applyEvent(
  5405. new EventLog().push(SessionEventType.ModelSelected, {
  5406. modelSelection: { providerId: "anthropic", modelId: "claude-4" },
  5407. }),
  5408. );
  5409. projection.applyEvent(
  5410. new EventLog().push(
  5411. SessionEventType.TurnStarted,
  5412. { turnNumber: 3, input: "switch" },
  5413. { turnId: "turn-3" },
  5414. ),
  5415. );
  5416. const rows = projection.getSnapshot().rows.window;
  5417. const markerIndex = rows.findIndex(
  5418. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5419. );
  5420. expect(rows[markerIndex]).toMatchObject({
  5421. marker: {
  5422. type: "modelChange",
  5423. fromProvider: "openai",
  5424. fromModel: "gpt-6",
  5425. toProvider: "anthropic",
  5426. toModel: "claude-4",
  5427. toThought: "",
  5428. },
  5429. });
  5430. // marker 紧邻 turn-3 的 turnHeader 之前。
  5431. expect(rows[markerIndex + 1]).toMatchObject({
  5432. kind: "turnHeader",
  5433. turnId: "turn-3",
  5434. });
  5435. });
  5436. it("显式 source-less 模型边界经原子投影只在首个 turn 生成一次 marker", () => {
  5437. const log = new EventLog("child-session");
  5438. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  5439. log.push(SessionEventType.ModelSelected, {
  5440. previousModelSelection: null,
  5441. modelSelection: {
  5442. providerId: "child-provider",
  5443. modelId: "child-model",
  5444. options: { reasoningLevel: "high" },
  5445. },
  5446. });
  5447. log.push(SessionEventType.ModelSelected, {
  5448. previousModelSelection: {
  5449. providerId: "child-provider",
  5450. modelId: "child-model",
  5451. options: { reasoningLevel: "high" },
  5452. },
  5453. modelSelection: {
  5454. providerId: "child-provider",
  5455. modelId: "child-model-final",
  5456. options: { reasoningLevel: "max" },
  5457. },
  5458. });
  5459. log.push(
  5460. SessionEventType.TurnStarted,
  5461. { turnNumber: 1, input: "first child prompt" },
  5462. { turnId: "child-turn-1" },
  5463. );
  5464. log.push(
  5465. SessionEventType.TurnComplete,
  5466. {
  5467. response: "done",
  5468. tokenCount: 1,
  5469. toolCallCount: 0,
  5470. duration: 1,
  5471. resultType: "success",
  5472. },
  5473. { turnId: "child-turn-1" },
  5474. );
  5475. log.push(
  5476. SessionEventType.TurnStarted,
  5477. { turnNumber: 2, input: "second child prompt" },
  5478. { turnId: "child-turn-2" },
  5479. );
  5480. const projection = new ProductProjection("child-session", "epoch-1");
  5481. for (const event of log.events) {
  5482. expect(projection.applyEventAtomically(event, () => true)).not.toBeNull();
  5483. }
  5484. const rows = projection.getSnapshot().rows.window;
  5485. const markers = rows.filter(
  5486. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5487. );
  5488. expect(markers).toHaveLength(1);
  5489. expect(markers[0]).toMatchObject({
  5490. turnId: "child-turn-1",
  5491. marker: {
  5492. type: "modelChange",
  5493. toProvider: "child-provider",
  5494. toModel: "child-model-final",
  5495. toThought: "max",
  5496. },
  5497. });
  5498. expect(markers[0]?.kind === "timelineMarker" ? markers[0].marker : {}).not.toHaveProperty(
  5499. "fromProvider",
  5500. );
  5501. const markerIndex = rows.indexOf(markers[0]!);
  5502. expect(rows[markerIndex + 1]).toMatchObject({
  5503. kind: "turnHeader",
  5504. turnId: "child-turn-1",
  5505. });
  5506. expect(() => conversationSnapshotSchema.parse(projection.getSnapshot())).not.toThrow();
  5507. });
  5508. it("H17:切模型后 /goal 控制输入不创建工作生命周期,只有 continuation 为 running", () => {
  5509. const log = new EventLog();
  5510. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  5511. log.push(SessionEventType.ModelSelected, {
  5512. modelSelection: { providerId: "zhipu", modelId: "glm-5.2-highspeed" },
  5513. });
  5514. log.push(
  5515. SessionEventType.TurnStarted,
  5516. { turnNumber: 1, input: "上一轮", messageId: "user-previous" },
  5517. { turnId: "turn-previous" },
  5518. );
  5519. log.push(
  5520. SessionEventType.TurnComplete,
  5521. { response: "done", tokenCount: 1, toolCallCount: 0, duration: 1000, resultType: "success" },
  5522. { turnId: "turn-previous" },
  5523. );
  5524. log.push(SessionEventType.ModelSelected, {
  5525. modelSelection: {
  5526. providerId: "deepseek",
  5527. modelId: "deepseek-v4-flash",
  5528. options: { reasoningLevel: "max" },
  5529. },
  5530. });
  5531. log.push(
  5532. SessionEventType.TurnStarted,
  5533. {
  5534. turnNumber: 2,
  5535. input: "/Goal 开发一个招投标管理系统",
  5536. messageId: "user-goal",
  5537. executionKind: "controlOnly",
  5538. intent: {
  5539. sourceCommandId: "command-goal",
  5540. queueItemId: "queue-goal",
  5541. clientId: "desktop",
  5542. kind: "sendGoalCommand",
  5543. text: "开发一个招投标管理系统",
  5544. admissionSeq: 1,
  5545. admittedAt: 1,
  5546. requestedDelivery: "startNow",
  5547. admittedDelivery: "startNow",
  5548. },
  5549. },
  5550. { turnId: "turn-goal-query" },
  5551. );
  5552. const projection = new ProductProjection("session-1", "epoch-1");
  5553. for (const event of log.events) projection.applyEvent(event);
  5554. expect(projection.getSnapshot().control).toMatchObject({
  5555. phase: "completedSuccess",
  5556. canStop: false,
  5557. activeWorks: [],
  5558. });
  5559. log.push(
  5560. SessionEventType.TurnComplete,
  5561. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  5562. { turnId: "turn-goal-query" },
  5563. );
  5564. projection.applyEvent(log.events.at(-1)!);
  5565. const goalHeader = projection
  5566. .getSnapshot()
  5567. .rows.window.find((row) => row.kind === "turnHeader" && row.turnId === "user-goal");
  5568. expect(goalHeader).toMatchObject({
  5569. kind: "turnHeader",
  5570. executionKind: "controlOnly",
  5571. state: "completedSuccess",
  5572. });
  5573. expect(goalHeader).not.toHaveProperty("activeMs");
  5574. expect(projection.getSnapshot().control).toMatchObject({
  5575. phase: "completedSuccess",
  5576. canStop: false,
  5577. activeWorks: [],
  5578. });
  5579. log.push(
  5580. SessionEventType.TurnStarted,
  5581. {
  5582. turnNumber: 3,
  5583. input: "继续执行目标",
  5584. messageId: "goal-continuation-1",
  5585. inputSource: "goal-continuation",
  5586. inputVisibility: "model-only",
  5587. },
  5588. { turnId: "turn-goal-continuation" },
  5589. );
  5590. projection.applyEvent(log.events.at(-1)!);
  5591. const snapshot = projection.getSnapshot();
  5592. expect(snapshot.control).toMatchObject({
  5593. phase: "running",
  5594. canStop: true,
  5595. activeWorks: [{ kind: "goalContinuation" }],
  5596. });
  5597. expect(
  5598. snapshot.rows.window.find(
  5599. (row) => row.kind === "turnHeader" && row.turnId === "goal-continuation-1",
  5600. ),
  5601. ).toMatchObject({ executionKind: "agent", state: "running" });
  5602. expect(
  5603. snapshot.rows.window.filter(
  5604. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5605. ),
  5606. ).toHaveLength(1);
  5607. });
  5608. it("modelChange:仅思考深度变化不产 marker", () => {
  5609. const log = new EventLog();
  5610. log.push(SessionEventType.ModelSelected, {
  5611. modelSelection: { providerId: "default-deepseek", modelId: "deepseek-v4-flash" },
  5612. });
  5613. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "first" }, { turnId: "turn-1" });
  5614. const { projection } = runAll(log.events);
  5615. projection.applyEvent(
  5616. new EventLog().push(SessionEventType.ModelSelected, {
  5617. modelSelection: {
  5618. providerId: "default-deepseek",
  5619. modelId: "deepseek-v4-flash",
  5620. options: { reasoningLevel: "max" },
  5621. },
  5622. }),
  5623. );
  5624. projection.applyEvent(
  5625. new EventLog().push(
  5626. SessionEventType.TurnStarted,
  5627. { turnNumber: 2, input: "same model, deeper thought" },
  5628. { turnId: "turn-2" },
  5629. ),
  5630. );
  5631. expect(projection.getSnapshot().config).toMatchObject({
  5632. provider: "default-deepseek",
  5633. model: "deepseek-v4-flash",
  5634. thought: "max",
  5635. });
  5636. expect(
  5637. projection
  5638. .getSnapshot()
  5639. .rows.window.filter(
  5640. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  5641. ),
  5642. ).toHaveLength(0);
  5643. });
  5644. // ── M4:rowId → messageId 侧表(forkAssistant/editUserQuery 桥接翻译,13 §E 组前置)──
  5645. it("E:assistant 行记录 assistantMessageId,getMessageIdForRow 可翻译", () => {
  5646. const log = new EventLog();
  5647. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  5648. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  5649. log.push(
  5650. SessionEventType.ModelStreaming,
  5651. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-assist-1" },
  5652. { turnId: "turn-1" },
  5653. );
  5654. log.push(
  5655. SessionEventType.ModelStreaming,
  5656. { kind: "text_delta", delta: "hello", done: false, assistantMessageId: "msg-assist-1" },
  5657. { turnId: "turn-1" },
  5658. );
  5659. log.push(
  5660. SessionEventType.ModelStreaming,
  5661. { kind: "text_end", delta: "", done: false },
  5662. { turnId: "turn-1" },
  5663. );
  5664. const { projection } = runAll(log.events);
  5665. const assistantRow = projection
  5666. .getSnapshot()
  5667. .rows.window.find((row) => row.kind === "assistantText");
  5668. expect(assistantRow).toBeDefined();
  5669. expect(projection.getMessageIdForRow(assistantRow!.rowId)).toBe("msg-assist-1");
  5670. // 非 assistant 行 / 未知 rowId → null(桥接层据此 reject,不静默兜底 fork 错点)。
  5671. expect(projection.getMessageIdForRow(9999)).toBeNull();
  5672. const turnHeaderRow = projection
  5673. .getSnapshot()
  5674. .rows.window.find((row) => row.kind === "turnHeader");
  5675. expect(projection.getMessageIdForRow(turnHeaderRow!.rowId)).toBeNull();
  5676. });
  5677. it("E:无 assistantMessageId 的流(老 provider)→ 行存在但翻译为 null", () => {
  5678. const log = new EventLog();
  5679. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  5680. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  5681. log.push(
  5682. SessionEventType.ModelStreaming,
  5683. { kind: "text_start", delta: "", done: false },
  5684. { turnId: "turn-1" },
  5685. );
  5686. log.push(
  5687. SessionEventType.ModelStreaming,
  5688. { kind: "text_delta", delta: "hello", done: false },
  5689. { turnId: "turn-1" },
  5690. );
  5691. const { projection } = runAll(log.events);
  5692. const assistantRow = projection
  5693. .getSnapshot()
  5694. .rows.window.find((row) => row.kind === "assistantText");
  5695. expect(assistantRow).toBeDefined();
  5696. expect(projection.getMessageIdForRow(assistantRow!.rowId)).toBeNull();
  5697. });
  5698. it("P0:user messageId 缺失时不得用同 turn assistant anchor 冒充 canEdit target", () => {
  5699. const log = new EventLog();
  5700. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  5701. log.push(
  5702. SessionEventType.TurnStarted,
  5703. { turnNumber: 1, input: "缺少持久 user id" },
  5704. { turnId: "turn-1" },
  5705. );
  5706. log.push(
  5707. SessionEventType.ModelStreaming,
  5708. {
  5709. kind: "text_start",
  5710. delta: "",
  5711. done: false,
  5712. assistantMessageId: "assistant-only-anchor",
  5713. },
  5714. { turnId: "turn-1" },
  5715. );
  5716. log.push(
  5717. SessionEventType.ModelStreaming,
  5718. { kind: "text_delta", delta: "回答", done: false },
  5719. { turnId: "turn-1" },
  5720. );
  5721. log.push(
  5722. SessionEventType.TurnComplete,
  5723. { response: "回答", tokenCount: 1, toolCallCount: 0, duration: 1, resultType: "success" },
  5724. { turnId: "turn-1" },
  5725. );
  5726. const { projection } = runAll(log.events);
  5727. const userRow = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput");
  5728. expect(userRow).toBeDefined();
  5729. expect(projection.getMessageIdForRow(userRow!.rowId)).toBeNull();
  5730. // turn rewind 仍能找到 assistant anchor,但 exact user target 不存在。
  5731. expect(projection.getTurnRewindAnchor(userRow!.rowId)).toBe("assistant-only-anchor");
  5732. expect(userRow!.actions?.canEdit).not.toBe(true);
  5733. expect(projection.isLatestEditableUserRow(userRow!.rowId)).toBe(false);
  5734. });
  5735. it("P1:legacy 身份 fallback 必须由 normalizer 留下可观测诊断", () => {
  5736. const log = new EventLog();
  5737. log.push(
  5738. SessionEventType.TurnStarted,
  5739. { turnNumber: 1, input: "legacy query" },
  5740. { turnId: "turn-legacy" },
  5741. );
  5742. const { projection } = runAll(log.events);
  5743. expect(projection.getNormalizationDiagnostics()).toEqual([
  5744. {
  5745. code: "normalizer.user.missingTranscriptMessageId",
  5746. eventId: "event-1",
  5747. },
  5748. ]);
  5749. });
  5750. it("P1/P2:live 与 cold 合成事件的 command target/actions 逐实体等价", () => {
  5751. const project = (turnId: string) => {
  5752. const log = new EventLog();
  5753. log.push(
  5754. SessionEventType.TurnStarted,
  5755. { turnNumber: 1, input: "same query", messageId: "message-user-1" },
  5756. { turnId },
  5757. );
  5758. log.push(
  5759. SessionEventType.ModelStreaming,
  5760. {
  5761. kind: "text_start",
  5762. delta: "",
  5763. done: false,
  5764. assistantMessageId: "message-assistant-1",
  5765. partId: "part-1",
  5766. },
  5767. { turnId },
  5768. );
  5769. log.push(
  5770. SessionEventType.ModelStreaming,
  5771. { kind: "text_delta", delta: "same answer", done: false, partId: "part-1" },
  5772. { turnId },
  5773. );
  5774. log.push(
  5775. SessionEventType.ModelStreaming,
  5776. { kind: "text_end", delta: "", done: false, partId: "part-1" },
  5777. { turnId },
  5778. );
  5779. log.push(
  5780. SessionEventType.TurnComplete,
  5781. {
  5782. response: "same answer",
  5783. tokenCount: 1,
  5784. toolCallCount: 0,
  5785. duration: 1,
  5786. resultType: "success",
  5787. },
  5788. { turnId },
  5789. );
  5790. return runAll(log.events).projection;
  5791. };
  5792. const live = project("runtime-turn-1");
  5793. const cold = project("hydrate-turn-1");
  5794. const semanticRows = (projection: ProductProjection) =>
  5795. projection
  5796. .getSnapshot()
  5797. .rows.window.filter((row) => row.kind === "userInput" || row.kind === "assistantText")
  5798. .map((row) => ({
  5799. kind: row.kind,
  5800. text: row.text,
  5801. productTurnId: row.turnId,
  5802. actions: row.actions,
  5803. entityId: projection.getEntityIdForRow(row.rowId),
  5804. target: projection.getMessageIdForRow(row.rowId),
  5805. }));
  5806. expect(semanticRows(cold)).toEqual(semanticRows(live));
  5807. expect(semanticRows(live).map((row) => row.productTurnId)).toEqual([
  5808. "message-user-1",
  5809. "message-user-1",
  5810. ]);
  5811. expect(live.getNormalizationDiagnostics()).toEqual([]);
  5812. expect(cold.getNormalizationDiagnostics()).toEqual([]);
  5813. });
  5814. it("P2:entity resolver 只允许当前 canEdit 的真实用户实体", () => {
  5815. const log = new EventLog();
  5816. for (const turnNumber of [1, 2]) {
  5817. const turnId = `turn-${turnNumber}`;
  5818. log.push(
  5819. SessionEventType.TurnStarted,
  5820. {
  5821. turnNumber,
  5822. input: `query ${turnNumber}`,
  5823. messageId: `message-user-${turnNumber}`,
  5824. },
  5825. { turnId },
  5826. );
  5827. log.push(
  5828. SessionEventType.TurnComplete,
  5829. {
  5830. response: "",
  5831. tokenCount: 0,
  5832. toolCallCount: 0,
  5833. duration: 1,
  5834. resultType: "success",
  5835. },
  5836. { turnId },
  5837. );
  5838. }
  5839. const { projection } = runAll(log.events);
  5840. const userRows = projection.getSnapshot().rows.window.filter((row) => row.kind === "userInput");
  5841. expect(userRows.map((row) => row.actions?.canEdit === true)).toEqual([false, true]);
  5842. expect(projection.resolveEditTargetByEntityId("message-user-1")).toBeNull();
  5843. expect(projection.resolveEditTargetByEntityId("message-user-2")).toMatchObject({
  5844. entityId: "message-user-2",
  5845. productTurnId: "message-user-2",
  5846. transcriptMessageId: "message-user-2",
  5847. });
  5848. });
  5849. it("Task3:row.actions 与 target resolver 同源并声明 edit disposition", () => {
  5850. const log = new EventLog();
  5851. log.push(
  5852. SessionEventType.TurnStarted,
  5853. { turnNumber: 1, input: "query", messageId: "message-user-1" },
  5854. { turnId: "turn-1" },
  5855. );
  5856. log.push(
  5857. SessionEventType.ModelStreaming,
  5858. {
  5859. kind: "text_start",
  5860. delta: "",
  5861. done: false,
  5862. assistantMessageId: "message-assistant-1",
  5863. },
  5864. { turnId: "turn-1" },
  5865. );
  5866. log.push(
  5867. SessionEventType.ModelStreaming,
  5868. { kind: "text_end", delta: "", done: false },
  5869. { turnId: "turn-1" },
  5870. );
  5871. log.push(
  5872. SessionEventType.TurnComplete,
  5873. {
  5874. response: "",
  5875. tokenCount: 0,
  5876. toolCallCount: 0,
  5877. duration: 1,
  5878. resultType: "success",
  5879. },
  5880. { turnId: "turn-1" },
  5881. );
  5882. const { projection } = runAll(log.events);
  5883. const userRow = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput")!;
  5884. const assistantRow = projection
  5885. .getSnapshot()
  5886. .rows.window.find((row) => row.kind === "assistantText")!;
  5887. const target = { rowId: userRow.rowId, entityId: "message-user-1" };
  5888. expect(userRow.actions).toMatchObject({
  5889. canEdit: true,
  5890. editDisposition: "rewind",
  5891. });
  5892. expect(assistantRow.actions).toMatchObject({
  5893. canFork: true,
  5894. canRetry: true,
  5895. });
  5896. expect(projection.resolveRowActionTarget(target, "editUserQuery")).toMatchObject({
  5897. ok: true,
  5898. action: "editUserQuery",
  5899. editTarget: { transcriptMessageId: "message-user-1" },
  5900. });
  5901. expect(
  5902. projection.resolveRowActionTarget(
  5903. { rowId: userRow.rowId, entityId: "reused-for-another-entity" },
  5904. "editUserQuery",
  5905. ),
  5906. ).toEqual({ ok: false, status: "stale", reasonCode: "proto.staleTarget" });
  5907. expect(projection.resolveRowActionTarget(target, "retryTurn")).toEqual({
  5908. ok: false,
  5909. status: "rejected",
  5910. reasonCode: "guard.actionUnavailable",
  5911. });
  5912. projection.applyEvent(
  5913. new EventLog().push(SessionEventType.CompactStarted, {
  5914. operationId: "compact-1",
  5915. messageId: "compact-message",
  5916. status: "started",
  5917. trigger: "manual",
  5918. display: "separator",
  5919. }),
  5920. );
  5921. const lockedRow = projection
  5922. .getSnapshot()
  5923. .rows.window.find((row) => row.rowId === userRow.rowId)!;
  5924. const lockedAssistantRow = projection
  5925. .getSnapshot()
  5926. .rows.window.find((row) => row.rowId === assistantRow.rowId)!;
  5927. expect(lockedRow.actions?.canEdit).toBeUndefined();
  5928. expect(lockedAssistantRow.actions?.canFork).toBeUndefined();
  5929. expect(lockedAssistantRow.actions?.canRetry).toBeUndefined();
  5930. expect(projection.getSnapshot().availability.sendQueuedNow).toEqual({
  5931. allowed: false,
  5932. reasonCode: "compactOperationLock",
  5933. });
  5934. projection.applyEvent(
  5935. new EventLog().push(SessionEventType.CompactCompleted, {
  5936. operationId: "compact-1",
  5937. messageId: "compact-message",
  5938. status: "completed",
  5939. trigger: "manual",
  5940. display: "separator",
  5941. tailStartMessageId: "message-user-1",
  5942. }),
  5943. );
  5944. const compactedRow = projection
  5945. .getSnapshot()
  5946. .rows.window.find((row) => row.rowId === userRow.rowId)!;
  5947. expect(compactedRow.actions).toMatchObject({
  5948. canEdit: true,
  5949. editDisposition: "rewind",
  5950. });
  5951. expect(projection.resolveRowActionTarget(target, "editUserQuery")).toMatchObject({
  5952. ok: true,
  5953. action: "editUserQuery",
  5954. editTarget: { coveredByStableCompact: true },
  5955. });
  5956. });
  5957. it("root review:primary/goal continuation/verifier running 时 retry 与 file rewind 同源禁用", () => {
  5958. const completedProjection = () => {
  5959. const log = new EventLog();
  5960. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  5961. log.push(
  5962. SessionEventType.TurnStarted,
  5963. { turnNumber: 1, input: "改文件", messageId: "message-user-base" },
  5964. { turnId: "turn-base" },
  5965. );
  5966. log.push(
  5967. SessionEventType.ModelStreaming,
  5968. {
  5969. kind: "text_start",
  5970. delta: "",
  5971. done: false,
  5972. assistantMessageId: "message-assistant-base",
  5973. },
  5974. { turnId: "turn-base" },
  5975. );
  5976. log.push(
  5977. SessionEventType.ModelStreaming,
  5978. { kind: "text_delta", delta: "done", done: false },
  5979. { turnId: "turn-base" },
  5980. );
  5981. log.push(
  5982. SessionEventType.ModelComplete,
  5983. {
  5984. content: "done",
  5985. stopReason: "stop",
  5986. querySource: "main_turn",
  5987. contextWindow: 200_000,
  5988. usage: { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 },
  5989. fileChanges: {
  5990. files: 1,
  5991. additions: 2,
  5992. deletions: 1,
  5993. items: [{ path: "/work/a.ts", additions: 2, deletions: 1, writeCount: 1 }],
  5994. },
  5995. },
  5996. { turnId: "turn-base" },
  5997. );
  5998. log.push(
  5999. SessionEventType.TurnComplete,
  6000. { response: "done", tokenCount: 2, toolCallCount: 0, duration: 1, resultType: "success" },
  6001. { turnId: "turn-base" },
  6002. );
  6003. return runAll(log.events).projection;
  6004. };
  6005. const contexts = [
  6006. {
  6007. kind: "primaryTurn",
  6008. event: () =>
  6009. new EventLog().push(
  6010. SessionEventType.TurnStarted,
  6011. { turnNumber: 2, input: "next", messageId: "message-user-next" },
  6012. { turnId: "turn-next" },
  6013. ),
  6014. },
  6015. {
  6016. kind: "goalContinuation",
  6017. event: () =>
  6018. new EventLog().push(
  6019. SessionEventType.TurnStarted,
  6020. {
  6021. turnNumber: 2,
  6022. input: "continue",
  6023. inputSource: "goal-continuation",
  6024. inputVisibility: "model-only",
  6025. },
  6026. { turnId: "turn-goal-continuation" },
  6027. ),
  6028. },
  6029. {
  6030. kind: "goalVerifier",
  6031. event: () =>
  6032. new EventLog().push(SessionEventType.TargetCompletionVerification, {
  6033. targetId: "target-1",
  6034. status: "started",
  6035. verificationId: "verify-1",
  6036. goalIteration: 1,
  6037. }),
  6038. },
  6039. ] as const;
  6040. for (const context of contexts) {
  6041. const projection = completedProjection();
  6042. const base = projection.getSnapshot();
  6043. const header = base.rows.window.find((row) => row.kind === "turnHeader")!;
  6044. const assistant = base.rows.window.find((row) => row.kind === "assistantText")!;
  6045. const headerTarget = { rowId: header.rowId, entityId: header.entityId! };
  6046. const assistantTarget = { rowId: assistant.rowId, entityId: assistant.entityId! };
  6047. projection.applyEvent(context.event());
  6048. const running = projection.getSnapshot();
  6049. const lockedHeader = running.rows.window.find((row) => row.rowId === header.rowId)!;
  6050. const lockedAssistant = running.rows.window.find((row) => row.rowId === assistant.rowId)!;
  6051. expect(running.control.activeWorks.some((work) => work.kind === context.kind)).toBe(true);
  6052. expect(lockedHeader.actions?.canRewindFiles, context.kind).toBeUndefined();
  6053. expect(lockedAssistant.actions?.canRetry, context.kind).toBeUndefined();
  6054. expect(lockedAssistant.actions?.canFork, context.kind).toBe(true);
  6055. expect(projection.resolveRowActionTarget(headerTarget, "applyFileRewind")).toMatchObject({
  6056. ok: false,
  6057. reasonCode: "guard.actionUnavailable",
  6058. });
  6059. expect(projection.resolveRowActionTarget(assistantTarget, "retryTurn")).toMatchObject({
  6060. ok: false,
  6061. reasonCode: "guard.actionUnavailable",
  6062. });
  6063. expect(projection.resolveRowActionTarget(assistantTarget, "forkAssistant")).toMatchObject({
  6064. ok: true,
  6065. });
  6066. }
  6067. });
  6068. // ── M4:queue 单项编辑(同 id 重入 TurnSteerQueued → 原地更新保位)──
  6069. it("A/B:editQueueItem —— 同 queueItemId 重入更新文本且保位", () => {
  6070. const log = new EventLog();
  6071. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6072. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6073. // 入队两条
  6074. log.push(
  6075. SessionEventType.TurnSteerQueued,
  6076. {
  6077. pendingInputId: "q1",
  6078. input: "第一条",
  6079. inputPreview: "第一条",
  6080. inputSize: 9,
  6081. queueLength: 1,
  6082. targetTurnId: "t1",
  6083. intent: {
  6084. botGroupSource: {
  6085. provider: "feishu",
  6086. botId: "bot",
  6087. chatId: "group",
  6088. senderId: "member",
  6089. senderName: "Member",
  6090. messageId: "message",
  6091. },
  6092. sourceCommandId: "command-q1",
  6093. queueItemId: "q1",
  6094. clientId: "mobile-client",
  6095. kind: "sendText",
  6096. admissionSeq: 1,
  6097. admittedAt: 10,
  6098. requestedDelivery: "guide",
  6099. admittedDelivery: "queue",
  6100. fallbackReasonCode: "guide.attachmentsUnsupported",
  6101. attachmentRefs: [
  6102. { ref: "artifact://q1", fileName: "q1.txt", mime: "text/plain", bytes: 2 },
  6103. ],
  6104. },
  6105. },
  6106. { turnId: "t1" },
  6107. );
  6108. log.push(
  6109. SessionEventType.TurnSteerQueued,
  6110. {
  6111. pendingInputId: "q2",
  6112. input: "第二条",
  6113. inputPreview: "第二条",
  6114. inputSize: 9,
  6115. queueLength: 2,
  6116. targetTurnId: "t1",
  6117. },
  6118. { turnId: "t1" },
  6119. );
  6120. // 编辑第一条(同 id 重入)
  6121. log.push(
  6122. SessionEventType.TurnSteerQueued,
  6123. {
  6124. pendingInputId: "q1",
  6125. input: "第一条改",
  6126. inputPreview: "第一条改",
  6127. inputSize: 12,
  6128. queueLength: 2,
  6129. targetTurnId: "t1",
  6130. },
  6131. { turnId: "t1" },
  6132. );
  6133. const { projection } = runAll(log.events);
  6134. const items = projection.getSnapshot().queue.items;
  6135. // 仍 2 条,q1 在原位(index 0)且文本已更新。
  6136. expect(items.map((i) => i.queueItemId)).toEqual(["q1", "q2"]);
  6137. expect(items[0]).toMatchObject({
  6138. text: "第一条改",
  6139. botGroupSource: { senderId: "member", chatId: "group" },
  6140. sourceCommandId: "command-q1",
  6141. clientId: "mobile-client",
  6142. attachments: [{ ref: "artifact://q1" }],
  6143. delivery: {
  6144. requested: "guide",
  6145. admitted: "queue",
  6146. fallbackReasonCode: "guide.attachmentsUnsupported",
  6147. },
  6148. order: { admissionSeq: 1, queuePosition: 0 },
  6149. steer: { state: "fellBack", reasonCode: "guide.attachmentsUnsupported" },
  6150. });
  6151. expect(items[1]!.text).toBe("第二条");
  6152. });
  6153. // ── M4:queue 重排(TurnSteerReordered → 按新序重排 queue rows)──
  6154. it("A/B:reorderQueueItem —— 按 orderedPendingInputIds 重排 queue", () => {
  6155. const log = new EventLog();
  6156. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6157. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6158. for (const [id, text, len] of [
  6159. ["q1", "一", 3],
  6160. ["q2", "二", 3],
  6161. ["q3", "三", 3],
  6162. ] as const) {
  6163. log.push(
  6164. SessionEventType.TurnSteerQueued,
  6165. {
  6166. pendingInputId: id,
  6167. input: text,
  6168. inputPreview: text,
  6169. inputSize: len,
  6170. queueLength: 3,
  6171. targetTurnId: "t1",
  6172. },
  6173. { turnId: "t1" },
  6174. );
  6175. }
  6176. // 把 q3 移到 q1 之前:新序 q3, q1, q2。
  6177. log.push(
  6178. SessionEventType.TurnSteerReordered,
  6179. { orderedPendingInputIds: ["q3", "q1", "q2"], targetTurnId: "t1" },
  6180. { turnId: "t1" },
  6181. );
  6182. const { projection } = runAll(log.events);
  6183. expect(projection.getSnapshot().queue.items.map((i) => i.queueItemId)).toEqual([
  6184. "q3",
  6185. "q1",
  6186. "q2",
  6187. ]);
  6188. expect(projection.getSnapshot().queue.items.map((i) => i.order.queuePosition)).toEqual([
  6189. 0, 1, 2,
  6190. ]);
  6191. });
  6192. it("sendQueuedNow dispatch:reserved/promoting 只更新目标项且保留完整 intent", () => {
  6193. const log = new EventLog();
  6194. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6195. log.push(
  6196. SessionEventType.TurnSteerQueued,
  6197. {
  6198. pendingInputId: "q1",
  6199. input: "带附件输入",
  6200. inputPreview: "带附件输入",
  6201. inputSize: 18,
  6202. queueLength: 1,
  6203. targetTurnId: "t1",
  6204. intent: {
  6205. sourceCommandId: "source-q1",
  6206. queueItemId: "q1",
  6207. clientId: "mobile-client",
  6208. kind: "sendText",
  6209. admissionSeq: 1,
  6210. admittedAt: 10,
  6211. requestedDelivery: "queue",
  6212. admittedDelivery: "queue",
  6213. attachmentRefs: [
  6214. { ref: "artifact://q1", fileName: "q1.txt", mime: "text/plain", bytes: 2 },
  6215. ],
  6216. },
  6217. },
  6218. { turnId: "t1" },
  6219. );
  6220. log.push(SessionEventType.TurnSteerDispatchChanged, {
  6221. pendingInputId: "q1",
  6222. reservationId: "send-now-1",
  6223. state: "reserved",
  6224. targetTurnId: "t1",
  6225. });
  6226. log.push(SessionEventType.TurnSteerDispatchChanged, {
  6227. pendingInputId: "q1",
  6228. reservationId: "send-now-1",
  6229. state: "promoting",
  6230. targetTurnId: "t1",
  6231. });
  6232. const { projection } = runAll(log.events);
  6233. expect(projection.getSnapshot().queue.items[0]).toMatchObject({
  6234. sourceCommandId: "source-q1",
  6235. clientId: "mobile-client",
  6236. attachments: [{ ref: "artifact://q1" }],
  6237. dispatch: { state: "promoting", reservationId: "send-now-1" },
  6238. });
  6239. });
  6240. it("sendQueuedNow commit:SessionInputPromoted 是 queue 移除的 durable 提交信号", () => {
  6241. const log = new EventLog();
  6242. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6243. log.push(
  6244. SessionEventType.TurnSteerQueued,
  6245. {
  6246. pendingInputId: "q1",
  6247. input: "已持久化输入",
  6248. inputPreview: "已持久化输入",
  6249. inputSize: 21,
  6250. queueLength: 1,
  6251. targetTurnId: "t1",
  6252. intent: {
  6253. sourceCommandId: "source-q1",
  6254. queueItemId: "q1",
  6255. clientId: "desktop-client",
  6256. kind: "sendText",
  6257. admissionSeq: 1,
  6258. admittedAt: 10,
  6259. requestedDelivery: "queue",
  6260. admittedDelivery: "queue",
  6261. attachmentRefs: [],
  6262. },
  6263. },
  6264. { turnId: "t1" },
  6265. );
  6266. log.push(SessionEventType.TurnSteerDispatchChanged, {
  6267. pendingInputId: "q1",
  6268. reservationId: "send-now-1",
  6269. state: "promoting",
  6270. targetTurnId: "t1",
  6271. });
  6272. // startPromptTurn 已把 user message + session_input promotion 同事务提交。
  6273. // 即使后续 TurnSteerDiscarded(promoted) 丢失,投影也不能留下幽灵 queue item。
  6274. log.push(SessionEventType.SessionInputPromoted, {
  6275. pendingInputId: "q1",
  6276. sourceCommandId: "source-q1",
  6277. messageId: "message-q1",
  6278. });
  6279. const { projection } = runAll(log.events);
  6280. expect(projection.getSnapshot().queue.items).toEqual([]);
  6281. });
  6282. // ── M4:setAutoDrain(QueueAutoDrainChanged → queue.autoDrain + held 派生)──
  6283. it("A/B:setAutoDrain(false) → queue.autoDrain=false,held 时 completed+queue>0 走 choice", () => {
  6284. const log = new EventLog();
  6285. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6286. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6287. log.push(
  6288. SessionEventType.TurnSteerQueued,
  6289. {
  6290. pendingInputId: "q1",
  6291. input: "排队项",
  6292. inputPreview: "排队项",
  6293. inputSize: 9,
  6294. queueLength: 1,
  6295. targetTurnId: "t1",
  6296. },
  6297. { turnId: "t1" },
  6298. );
  6299. // 关闭 autoDrain(保留队列)
  6300. log.push(SessionEventType.QueueAutoDrainChanged, { autoDrain: false });
  6301. // turn 结束 → completed + queue>0 + autoDrain=false → 输入路由为 choice
  6302. log.push(
  6303. SessionEventType.TurnComplete,
  6304. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  6305. { turnId: "t1" },
  6306. );
  6307. const { projection } = runAll(log.events);
  6308. const snapshot = projection.getSnapshot();
  6309. expect(snapshot.queue.autoDrain).toBe(false);
  6310. expect(snapshot.queue.pauseReason).toBe("manual");
  6311. expect(snapshot.inputRouting.mode).toBe("choice");
  6312. expect(snapshot.inputRouting.reasonCode).toBe("heldQueueInputRequiresChoice");
  6313. });
  6314. it("B:Stop 保留队列时记录 stopped 原因;恢复后清除暂停原因", () => {
  6315. const log = new EventLog();
  6316. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6317. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6318. log.push(
  6319. SessionEventType.TurnSteerQueued,
  6320. {
  6321. pendingInputId: "q1",
  6322. input: "排队项",
  6323. inputPreview: "排队项",
  6324. inputSize: 9,
  6325. queueLength: 1,
  6326. targetTurnId: "t1",
  6327. },
  6328. { turnId: "t1" },
  6329. );
  6330. log.push(
  6331. SessionEventType.TurnComplete,
  6332. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "cancelled" },
  6333. { turnId: "t1" },
  6334. );
  6335. log.push(SessionEventType.QueueAutoDrainChanged, { autoDrain: true });
  6336. const projection = new ProductProjection("s1", "epoch-1");
  6337. for (const event of log.events.slice(0, -1)) projection.applyEvent(event);
  6338. expect(projection.getSnapshot().queue).toMatchObject({
  6339. autoDrain: false,
  6340. pauseReason: "stopped",
  6341. });
  6342. projection.applyEvent(log.events.at(-1)!);
  6343. expect(projection.getSnapshot().queue.autoDrain).toBe(true);
  6344. expect(projection.getSnapshot().queue.pauseReason).toBeUndefined();
  6345. });
  6346. it("M07a:sendQueuedNow 内部抢占不把 future queue 投影为 stopped", () => {
  6347. const log = new EventLog();
  6348. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6349. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6350. log.push(
  6351. SessionEventType.TurnSteerQueued,
  6352. {
  6353. pendingInputId: "q1",
  6354. input: "立即发送",
  6355. inputPreview: "立即发送",
  6356. inputSize: 12,
  6357. queueLength: 1,
  6358. targetTurnId: "t1",
  6359. },
  6360. { turnId: "t1" },
  6361. );
  6362. log.push(
  6363. SessionEventType.TurnComplete,
  6364. {
  6365. response: "",
  6366. tokenCount: 0,
  6367. toolCallCount: 0,
  6368. duration: 0,
  6369. resultType: "cancelled",
  6370. preserveQueueAutoDrainOnCancel: true,
  6371. },
  6372. { turnId: "t1" },
  6373. );
  6374. const { projection } = runAll(log.events);
  6375. const snapshot = projection.getSnapshot();
  6376. expect(snapshot.control.phase).toBe("completedInterrupted");
  6377. expect(snapshot.queue).toMatchObject({
  6378. autoDrain: true,
  6379. items: [expect.objectContaining({ queueItemId: "q1" })],
  6380. });
  6381. expect(snapshot.queue.pauseReason).toBeUndefined();
  6382. expect(snapshot.inputRouting.mode).toBe("startNow");
  6383. });
  6384. it("A/B:setAutoDrain 幂等 —— 同值不产 delta", () => {
  6385. const log = new EventLog();
  6386. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6387. // 初始 autoDrain=true,再置 true 应无变化。
  6388. log.push(SessionEventType.QueueAutoDrainChanged, { autoDrain: true });
  6389. const { projection } = runAll(log.events);
  6390. expect(projection.getSnapshot().queue.autoDrain).toBe(true);
  6391. });
  6392. // ── M4:setFollowupMode(FollowupModeChanged → running 时 enqueue vs guide)──
  6393. it("A/B:setFollowupMode(guide) → running 时输入路由为 guide", () => {
  6394. const log = new EventLog();
  6395. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6396. log.push(SessionEventType.FollowupModeChanged, { mode: "guide" });
  6397. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6398. const { projection } = runAll(log.events);
  6399. const snapshot = projection.getSnapshot();
  6400. expect(snapshot.config.followupMode).toBe("guide");
  6401. expect(snapshot.inputRouting.mode).toBe("guide");
  6402. });
  6403. it("A/B:followupMode 默认 queue —— running 时输入入队", () => {
  6404. const log = new EventLog();
  6405. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6406. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "跑" }, { turnId: "t1" });
  6407. const { projection } = runAll(log.events);
  6408. const snapshot = projection.getSnapshot();
  6409. expect(snapshot.config.followupMode).toBe("queue");
  6410. expect(snapshot.inputRouting.mode).toBe("enqueue");
  6411. });
  6412. // ── M5:switchCollaborationMode(SessionModeChanged → config.mode)──
  6413. it("A/B:SessionModeChanged —— config.mode 更新且 revision 前进;同值不动", () => {
  6414. const log = new EventLog();
  6415. log.push(SessionEventType.SessionCreated, { mode: "build", contextWindow: 200_000 });
  6416. log.push(SessionEventType.SessionModeChanged, {
  6417. mode: "plan",
  6418. previousMode: "build",
  6419. source: "command",
  6420. });
  6421. const { projection } = runAll(log.events);
  6422. const snapshot = projection.getSnapshot();
  6423. expect(snapshot.config.mode).toBe("plan");
  6424. const revisionAfterSwitch = snapshot.revision;
  6425. // 同值再切:无 delta,revision 不前进。
  6426. log.push(SessionEventType.SessionModeChanged, {
  6427. mode: "plan",
  6428. previousMode: "plan",
  6429. source: "command",
  6430. });
  6431. const { projection: projection2 } = runAll(log.events);
  6432. expect(projection2.getSnapshot().config.mode).toBe("plan");
  6433. expect(projection2.getSnapshot().revision).toBe(revisionAfterSwitch);
  6434. });
  6435. it("A/B:config.mode 初值 = build(draft 期无 SessionModeChanged 时的回落)", () => {
  6436. const log = new EventLog();
  6437. log.push(SessionEventType.SessionCreated, { mode: "build", contextWindow: 200_000 });
  6438. const { projection } = runAll(log.events);
  6439. expect(projection.getSnapshot().config.mode).toBe("build");
  6440. });
  6441. // ── M4:renameSession / 自动标题(SessionTitleUpdated → meta.title)──
  6442. it("A/B:SessionTitleUpdated —— generated 更新,custom 覆盖且 custom 后不被 generated 回退", () => {
  6443. const log = new EventLog();
  6444. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6445. // 初始 default
  6446. expect(runAll(log.events).projection.getSnapshot().meta.titleSource).toBe("default");
  6447. // 自动生成标题
  6448. log.push(SessionEventType.SessionTitleUpdated, {
  6449. previousTitle: "",
  6450. source: "generated",
  6451. title: "自动标题",
  6452. });
  6453. // 用户重命名(custom)
  6454. log.push(SessionEventType.SessionTitleUpdated, {
  6455. previousTitle: "自动标题",
  6456. source: "custom",
  6457. title: "我的会话",
  6458. });
  6459. // custom 后再来一次 generated —— 应被忽略(custom 粘性)
  6460. log.push(SessionEventType.SessionTitleUpdated, {
  6461. previousTitle: "我的会话",
  6462. source: "generated",
  6463. title: "又一个自动标题",
  6464. });
  6465. const meta = runAll(log.events).projection.getSnapshot().meta;
  6466. expect(meta.title).toBe("我的会话");
  6467. expect(meta.titleSource).toBe("custom");
  6468. });
  6469. it("A/B:SessionTitleUpdated —— first_input 归一为 generated", () => {
  6470. const log = new EventLog();
  6471. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6472. log.push(SessionEventType.SessionTitleUpdated, {
  6473. previousTitle: "",
  6474. source: "first_input",
  6475. title: "首条输入标题",
  6476. });
  6477. const meta = runAll(log.events).projection.getSnapshot().meta;
  6478. expect(meta.title).toBe("首条输入标题");
  6479. expect(meta.titleSource).toBe("generated");
  6480. });
  6481. // ── M4:switchModelConfig(ModelSelected → config 更新 + 中途切换 modelChange marker)──
  6482. it("A/B:ModelSelected 首次 → config 更新,无 marker(首次选型不算切换)", () => {
  6483. const log = new EventLog();
  6484. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6485. log.push(SessionEventType.ModelSelected, {
  6486. modelSelection: { providerId: "e2e-deepseek", modelId: "deepseek-v4-flash" },
  6487. supportedThoughtLevels: ["max", "high", "nothink"],
  6488. });
  6489. const { projection } = runAll(log.events);
  6490. const snapshot = projection.getSnapshot();
  6491. expect(snapshot.config.provider).toBe("e2e-deepseek");
  6492. expect(snapshot.config.model).toBe("deepseek-v4-flash");
  6493. expect(snapshot.config.thoughtLevels).toEqual(["max", "high", "nothink"]);
  6494. // 首次选型不产 modelChange marker。
  6495. expect(
  6496. snapshot.rows.window.some(
  6497. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  6498. ),
  6499. ).toBe(false);
  6500. });
  6501. it("ModelSelected 分离稀疏 Session Selection 与 effective reasoning 展示事实", () => {
  6502. const log = new EventLog();
  6503. log.push(SessionEventType.ModelSelected, {
  6504. modelSelection: { providerId: "provider-a", modelId: "model-a" },
  6505. effectiveReasoningLevel: "high",
  6506. supportedThoughtLevels: ["low", "high"],
  6507. });
  6508. const snapshot = runAll(log.events).projection.getSnapshot();
  6509. expect(snapshot.config.modelSelection).toEqual({
  6510. providerId: "provider-a",
  6511. modelId: "model-a",
  6512. });
  6513. expect(snapshot.config.thought).toBe("high");
  6514. });
  6515. it("A/B:ModelSelected 中途切换 → config 更新;marker 归 turn 开始(R-17 时机)", () => {
  6516. const log = new EventLog();
  6517. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6518. log.push(SessionEventType.ModelSelected, {
  6519. modelSelection: { providerId: "e2e-deepseek", modelId: "deepseek-v4-flash" },
  6520. supportedThoughtLevels: ["max", "high", "nothink"],
  6521. });
  6522. log.push(SessionEventType.ModelSelected, {
  6523. modelSelection: {
  6524. providerId: "e2e-deepseek",
  6525. modelId: "deepseek-v4-pro",
  6526. options: { reasoningLevel: "max" },
  6527. },
  6528. supportedThoughtLevels: ["max", "nothink"],
  6529. });
  6530. const { projection } = runAll(log.events);
  6531. const snapshot = projection.getSnapshot();
  6532. expect(snapshot.config.model).toBe("deepseek-v4-pro");
  6533. expect(snapshot.config.thought).toBe("max");
  6534. expect(snapshot.config.thoughtLevels).toEqual(["max", "nothink"]);
  6535. // R-17 时机修复(2026-07-07):切换动作本身不落 marker——尚未有 turn 使用过
  6536. // 任何模型(草稿态截图 bug:首条消息上方挂 [modelChange])。
  6537. expect(
  6538. snapshot.rows.window.some(
  6539. (row) => row.kind === "timelineMarker" && row.marker.type === "modelChange",
  6540. ),
  6541. ).toBe(false);
  6542. });
  6543. it("I56:registry fallback 投影稳定事件与起止模型,显式切换不伪造来源", () => {
  6544. const log = new EventLog();
  6545. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6546. log.push(SessionEventType.ModelSelected, {
  6547. modelSelection: { providerId: "provider-a", modelId: "model-a" },
  6548. });
  6549. const fallbackEvent = log.push(SessionEventType.ModelSelected, {
  6550. modelSelection: {
  6551. providerId: "provider-b",
  6552. modelId: "model-b",
  6553. options: { reasoningLevel: "deep" },
  6554. },
  6555. previousModelSelection: { providerId: "provider-a", modelId: "model-a" },
  6556. origin: "registryFallback",
  6557. });
  6558. const { projection } = runAll(log.events);
  6559. expect(projection.getSnapshot().modelTransition).toEqual({
  6560. eventId: fallbackEvent.id,
  6561. origin: "registryFallback",
  6562. from: { provider: "provider-a", model: "model-a" },
  6563. to: { provider: "provider-b", model: "model-b" },
  6564. });
  6565. projection.applyEvent(
  6566. log.push(SessionEventType.ModelSelected, {
  6567. modelSelection: { providerId: "provider-c", modelId: "model-c" },
  6568. previousModelSelection: {
  6569. providerId: "provider-b",
  6570. modelId: "model-b",
  6571. options: { reasoningLevel: "deep" },
  6572. },
  6573. }),
  6574. );
  6575. expect(projection.getSnapshot().modelTransition?.eventId).toBe(fallbackEvent.id);
  6576. });
  6577. it("A/B:历史会话切换模型后立即刷新 context window 分母并保留已用量", () => {
  6578. const log = new EventLog();
  6579. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6580. log.push(
  6581. SessionEventType.TurnStarted,
  6582. { turnNumber: 1, input: "history" },
  6583. { turnId: "turn-1" },
  6584. );
  6585. log.push(
  6586. SessionEventType.ModelComplete,
  6587. {
  6588. content: "done",
  6589. stopReason: "end_turn",
  6590. querySource: "main_turn",
  6591. contextWindow: 200_000,
  6592. usage: { inputTokens: 120, outputTokens: 30 },
  6593. },
  6594. { turnId: "turn-1" },
  6595. );
  6596. const { projection } = runAll(log.events);
  6597. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6598. usedTokens: 150,
  6599. maxTokens: 200_000,
  6600. });
  6601. projection.applyEvent(
  6602. log.push(SessionEventType.ModelSelected, {
  6603. modelSelection: {
  6604. providerId: "deepseek",
  6605. modelId: "deepseek-v4-flash",
  6606. options: { reasoningLevel: "max" },
  6607. },
  6608. supportedThoughtLevels: ["max", "high", "nothink"],
  6609. }),
  6610. );
  6611. // 旧持久化事件没有 contextWindow,重放时保持既有分母,不能清零。
  6612. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6613. usedTokens: 150,
  6614. maxTokens: 200_000,
  6615. });
  6616. projection.applyEvent(
  6617. log.push(SessionEventType.ModelSelected, {
  6618. modelSelection: {
  6619. providerId: "deepseek",
  6620. modelId: "deepseek-v4-flash",
  6621. options: { reasoningLevel: "max" },
  6622. },
  6623. contextWindow: 1_000_000,
  6624. supportedThoughtLevels: ["max", "high", "nothink"],
  6625. }),
  6626. );
  6627. // 修复目标:模型切换事件本身就是 runtime 新能力的权威提交点;不等下一轮发送完成。
  6628. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6629. usedTokens: 150,
  6630. maxTokens: 1_000_000,
  6631. });
  6632. projection.applyEvent(
  6633. log.push(
  6634. SessionEventType.ModelComplete,
  6635. {
  6636. content: "next",
  6637. stopReason: "end_turn",
  6638. querySource: "main_turn",
  6639. usage: { inputTokens: 160, outputTokens: 40 },
  6640. },
  6641. { turnId: "turn-2" },
  6642. ),
  6643. );
  6644. // 后续旧 adapter 未携带 contextWindow 时,也必须回退到刚切换后的新窗口。
  6645. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6646. usedTokens: 200,
  6647. maxTokens: 1_000_000,
  6648. });
  6649. });
  6650. it("A/B:清除 context window 后持续隐藏分母并在容量恢复时保留最新已用量", () => {
  6651. const log = new EventLog();
  6652. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6653. log.push(
  6654. SessionEventType.ModelComplete,
  6655. {
  6656. content: "before clear",
  6657. stopReason: "end_turn",
  6658. querySource: "main_turn",
  6659. contextWindow: 200_000,
  6660. usage: { inputTokens: 120, outputTokens: 30 },
  6661. },
  6662. { turnId: "turn-1" },
  6663. );
  6664. const { projection } = runAll(log.events);
  6665. projection.applyEvent(
  6666. log.push(SessionEventType.ModelSelected, {
  6667. modelSelection: { providerId: "custom", modelId: "unknown-context-model" },
  6668. contextWindow: null,
  6669. }),
  6670. );
  6671. expect(projection.getSnapshot().usage.contextWindow).toBeNull();
  6672. projection.applyEvent(
  6673. log.push(
  6674. SessionEventType.ModelComplete,
  6675. {
  6676. content: "while unknown",
  6677. stopReason: "end_turn",
  6678. querySource: "main_turn",
  6679. usage: { inputTokens: 160, outputTokens: 40 },
  6680. },
  6681. { turnId: "turn-2" },
  6682. ),
  6683. );
  6684. expect(projection.getSnapshot().usage.contextWindow).toBeNull();
  6685. expect(projection.getSnapshot().usage.cumulative).toMatchObject({
  6686. inputTokens: 280,
  6687. outputTokens: 70,
  6688. });
  6689. projection.applyEvent(
  6690. log.push(SessionEventType.ModelSelected, {
  6691. modelSelection: { providerId: "custom", modelId: "unknown-context-model" },
  6692. contextWindow: 1_000_000,
  6693. }),
  6694. );
  6695. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6696. usedTokens: 200,
  6697. maxTokens: 1_000_000,
  6698. });
  6699. });
  6700. it("A/B:显式清除窗口后 hydration seed 只恢复用量而不覆盖容量", () => {
  6701. const log = new EventLog();
  6702. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6703. log.push(SessionEventType.ModelSelected, {
  6704. modelSelection: { providerId: "custom", modelId: "unknown-context-model" },
  6705. contextWindow: null,
  6706. });
  6707. const { projection } = runAll(log.events);
  6708. projection.seedUsage({
  6709. contextWindow: {
  6710. usedTokens: 999,
  6711. maxTokens: 200_000,
  6712. autoCompactThresholdTokens: null,
  6713. },
  6714. cumulative: {
  6715. inputTokens: 700,
  6716. outputTokens: 50,
  6717. cacheReadTokens: 20,
  6718. cacheWriteTokens: 10,
  6719. },
  6720. });
  6721. expect(projection.getSnapshot().usage.contextWindow).toBeNull();
  6722. expect(projection.getSnapshot().usage.cumulative).toEqual({
  6723. inputTokens: 700,
  6724. outputTokens: 50,
  6725. cacheReadTokens: 20,
  6726. cacheWriteTokens: 10,
  6727. });
  6728. projection.applyEvent(
  6729. log.push(SessionEventType.ModelSelected, {
  6730. modelSelection: { providerId: "custom", modelId: "unknown-context-model" },
  6731. contextWindow: 1_000_000,
  6732. }),
  6733. );
  6734. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6735. usedTokens: 999,
  6736. maxTokens: 1_000_000,
  6737. });
  6738. });
  6739. it("Todo123: 未知容量种子保留用量,后续容量恢复不归零", () => {
  6740. const log = new EventLog();
  6741. log.push(SessionEventType.SessionCreated, { mode: "default" });
  6742. const { projection } = runAll(log.events);
  6743. projection.seedUsage({
  6744. contextWindow: { usedTokens: 29908, maxTokens: null, autoCompactThresholdTokens: null },
  6745. });
  6746. expect(projection.getSnapshot().usage.contextWindow).toBeNull();
  6747. projection.applyEvent(
  6748. log.push(SessionEventType.ModelSelected, {
  6749. modelSelection: { providerId: "glm", modelId: "GLM-5.3-Flash" },
  6750. contextWindow: 1_000_000,
  6751. }),
  6752. );
  6753. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6754. usedTokens: 29908,
  6755. maxTokens: 1_000_000,
  6756. });
  6757. });
  6758. it("Todo123: 未知容量期间真实用量优先,迟到恢复种子不能覆盖", () => {
  6759. const log = new EventLog();
  6760. log.push(SessionEventType.SessionCreated, { mode: "default" });
  6761. log.push(SessionEventType.ModelSelected, {
  6762. modelSelection: { providerId: "glm", modelId: "GLM-5.3-Flash" },
  6763. contextWindow: null,
  6764. });
  6765. log.push(SessionEventType.ModelComplete, {
  6766. content: "",
  6767. stopReason: "end_turn",
  6768. querySource: "main_turn",
  6769. usage: { inputTokens: 700, outputTokens: 30 },
  6770. });
  6771. const { projection } = runAll(log.events);
  6772. projection.seedUsage({
  6773. contextWindow: { usedTokens: 29908, maxTokens: null, autoCompactThresholdTokens: null },
  6774. });
  6775. projection.applyEvent(
  6776. log.push(SessionEventType.ModelSelected, {
  6777. modelSelection: { providerId: "glm", modelId: "GLM-5.3-Flash" },
  6778. contextWindow: 1_000_000,
  6779. }),
  6780. );
  6781. expect(projection.getSnapshot().usage.contextWindow).toMatchObject({
  6782. usedTokens: 730,
  6783. maxTokens: 1_000_000,
  6784. });
  6785. });
  6786. // ── M4:cancelBackgroundWork(BackgroundTask* → backgroundWorks 投影)──
  6787. it("A/B:BackgroundTaskStarted → backgroundWorks 出现 running 项,Completed(cancelled) → cancelled", () => {
  6788. const log = new EventLog();
  6789. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6790. log.push(SessionEventType.BackgroundTaskStarted, {
  6791. taskId: "bg-1",
  6792. toolName: "Bash",
  6793. command: "sleep 100",
  6794. description: "长任务",
  6795. status: "running",
  6796. });
  6797. let snapshot = runAll(log.events).projection.getSnapshot();
  6798. expect(snapshot.backgroundWorks).toHaveLength(1);
  6799. expect(snapshot.backgroundWorks[0]!.workId).toBe("bg-1");
  6800. expect(snapshot.backgroundWorks[0]!.kind).toBe("bash");
  6801. expect(snapshot.backgroundWorks[0]!.title).toBe("长任务");
  6802. expect(snapshot.backgroundWorks[0]!.status).toBe("running");
  6803. // 取消 → cancelled
  6804. log.push(SessionEventType.BackgroundTaskCompleted, {
  6805. taskId: "bg-1",
  6806. toolName: "Bash",
  6807. status: "cancelled",
  6808. });
  6809. snapshot = runAll(log.events).projection.getSnapshot();
  6810. expect(snapshot.backgroundWorks).toHaveLength(1);
  6811. expect(snapshot.backgroundWorks[0]!.status).toBe("cancelled");
  6812. });
  6813. it("A/B:真实 Agent 后台事件使用 runtime taskKind,且旧 Agent 事件兼容为 subagent", () => {
  6814. const log = new EventLog();
  6815. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6816. log.push(SessionEventType.BackgroundTaskStarted, {
  6817. taskId: "bg-2",
  6818. toolName: "Agent",
  6819. taskKind: "subagent",
  6820. childSessionId: "sess_child_bg_2",
  6821. description: "子代理",
  6822. status: "running",
  6823. cancellable: true,
  6824. });
  6825. let snapshot = runAll(log.events).projection.getSnapshot();
  6826. expect(snapshot.backgroundWorks[0]).toMatchObject({
  6827. kind: "subagent",
  6828. childSessionId: "sess_child_bg_2",
  6829. cancellable: true,
  6830. status: "running",
  6831. title: "子代理",
  6832. });
  6833. log.push(SessionEventType.BackgroundTaskCompleted, {
  6834. taskId: "bg-2",
  6835. toolName: "Agent",
  6836. taskKind: "subagent",
  6837. status: "completed",
  6838. cancellable: false,
  6839. });
  6840. snapshot = runAll(log.events).projection.getSnapshot();
  6841. expect(snapshot.backgroundWorks[0]).toMatchObject({
  6842. kind: "subagent",
  6843. childSessionId: "sess_child_bg_2",
  6844. cancellable: false,
  6845. status: "resultPending",
  6846. });
  6847. const lateIdentity = new EventLog();
  6848. lateIdentity.push(SessionEventType.SessionCreated, {
  6849. mode: "default",
  6850. contextWindow: 200_000,
  6851. });
  6852. lateIdentity.push(SessionEventType.BackgroundTaskStarted, {
  6853. taskId: "late-child-id",
  6854. toolName: "Agent",
  6855. taskKind: "subagent",
  6856. description: "晚到身份",
  6857. status: "running",
  6858. cancellable: true,
  6859. });
  6860. lateIdentity.push(SessionEventType.BackgroundTaskUpdated, {
  6861. taskId: "late-child-id",
  6862. toolName: "Agent",
  6863. taskKind: "subagent",
  6864. childSessionId: "sess_child_late",
  6865. description: "晚到身份",
  6866. status: "running",
  6867. cancellable: true,
  6868. });
  6869. expect(runAll(lateIdentity.events).projection.getSnapshot().backgroundWorks[0]).toMatchObject({
  6870. childSessionId: "sess_child_late",
  6871. status: "running",
  6872. });
  6873. const legacy = new EventLog();
  6874. legacy.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6875. legacy.push(SessionEventType.BackgroundTaskStarted, {
  6876. taskId: "legacy-agent",
  6877. toolName: "Agent",
  6878. description: "旧子代理",
  6879. status: "running",
  6880. });
  6881. legacy.push(SessionEventType.BackgroundTaskUpdated, {
  6882. taskId: "legacy-agent",
  6883. status: "running",
  6884. });
  6885. legacy.push(SessionEventType.BackgroundTaskCompleted, {
  6886. taskId: "legacy-agent",
  6887. status: "completed",
  6888. });
  6889. expect(runAll(legacy.events).projection.getSnapshot().backgroundWorks[0]).toMatchObject({
  6890. kind: "subagent",
  6891. status: "resultPending",
  6892. title: "旧子代理",
  6893. });
  6894. const explicit = new EventLog();
  6895. explicit.push(SessionEventType.SessionCreated, {
  6896. mode: "default",
  6897. contextWindow: 200_000,
  6898. });
  6899. explicit.push(SessionEventType.BackgroundTaskStarted, {
  6900. taskId: "explicit-bash",
  6901. // taskKind 是新事实;即使旧 toolName 数据矛盾也不得反向覆盖。
  6902. taskKind: "bash",
  6903. toolName: "Agent",
  6904. description: "显式进程",
  6905. status: "running",
  6906. });
  6907. expect(runAll(explicit.events).projection.getSnapshot().backgroundWorks[0]!.kind).toBe("bash");
  6908. });
  6909. // ── M4:RewindTriggered → row.removed(editUserQuery/retryTurn 的 live 截断)──
  6910. it("D/G:RewindTriggered(targetMessageId) 从目标 turn 首行整段移除", () => {
  6911. const log = new EventLog();
  6912. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6913. // turn1
  6914. log.push(
  6915. SessionEventType.TurnStarted,
  6916. { turnNumber: 1, input: "第一问", messageId: "msg-u1" },
  6917. { turnId: "t1" },
  6918. );
  6919. log.push(
  6920. SessionEventType.ModelStreaming,
  6921. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  6922. { turnId: "t1" },
  6923. );
  6924. log.push(
  6925. SessionEventType.ModelStreaming,
  6926. { kind: "text_delta", delta: "第一答", done: false, assistantMessageId: "msg-a1" },
  6927. { turnId: "t1" },
  6928. );
  6929. log.push(
  6930. SessionEventType.ModelStreaming,
  6931. { kind: "text_end", delta: "", done: false },
  6932. { turnId: "t1" },
  6933. );
  6934. log.push(
  6935. SessionEventType.TurnComplete,
  6936. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  6937. { turnId: "t1" },
  6938. );
  6939. // turn2
  6940. log.push(
  6941. SessionEventType.TurnStarted,
  6942. { turnNumber: 2, input: "第二问", messageId: "msg-u2" },
  6943. { turnId: "t2" },
  6944. );
  6945. log.push(
  6946. SessionEventType.ModelStreaming,
  6947. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a2" },
  6948. { turnId: "t2" },
  6949. );
  6950. log.push(
  6951. SessionEventType.ModelStreaming,
  6952. { kind: "text_delta", delta: "第二答", done: false, assistantMessageId: "msg-a2" },
  6953. { turnId: "t2" },
  6954. );
  6955. log.push(
  6956. SessionEventType.ModelStreaming,
  6957. { kind: "text_end", delta: "", done: false },
  6958. { turnId: "t2" },
  6959. );
  6960. log.push(
  6961. SessionEventType.TurnComplete,
  6962. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  6963. { turnId: "t2" },
  6964. );
  6965. // rewind 到 turn2 的 assistant 消息 → 整个 turn2 被移除。
  6966. // createdMessageId = applied 语义(unavailable/workspace 回滚不带,投影必须忽略)。
  6967. log.push(SessionEventType.RewindTriggered, {
  6968. targetMessageId: "msg-a2",
  6969. scope: "conversation",
  6970. createdMessageId: "msg-rewind-notice",
  6971. });
  6972. const { projection } = runAll(log.events);
  6973. const texts = projection
  6974. .getSnapshot()
  6975. .rows.window.filter((r) => r.kind === "userInput" || r.kind === "assistantText")
  6976. .map((r) => (r.kind === "userInput" || r.kind === "assistantText" ? r.text : ""));
  6977. // turn1 保留,turn2 整段被移除。
  6978. expect(texts).toEqual(["第一问", "第一答"]);
  6979. // turn2 的 assistant messageId 映射也被清理。
  6980. expect(projection.getMessageIdForRow(999)).toBeNull();
  6981. expect(projection.resolveEditTargetByEntityId("msg-u2")).toBeNull();
  6982. expect(projection.resolveEditTargetByEntityId("msg-u1")).toMatchObject({
  6983. entityId: "msg-u1",
  6984. transcriptMessageId: "msg-u1",
  6985. });
  6986. });
  6987. it("PV4-10 回归:首轮 edit rewind 后分页首行切换到新 active branch", () => {
  6988. const log = new EventLog();
  6989. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  6990. log.push(
  6991. SessionEventType.TurnStarted,
  6992. { turnNumber: 1, input: "你好", messageId: "msg-u1" },
  6993. { turnId: "t1" },
  6994. );
  6995. log.push(
  6996. SessionEventType.ModelStreaming,
  6997. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  6998. { turnId: "t1" },
  6999. );
  7000. log.push(
  7001. SessionEventType.ModelStreaming,
  7002. { kind: "text_delta", delta: "旧回答", done: false, assistantMessageId: "msg-a1" },
  7003. { turnId: "t1" },
  7004. );
  7005. log.push(
  7006. SessionEventType.ModelStreaming,
  7007. { kind: "text_end", delta: "", done: false },
  7008. { turnId: "t1" },
  7009. );
  7010. log.push(
  7011. SessionEventType.TurnComplete,
  7012. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  7013. { turnId: "t1" },
  7014. );
  7015. const original = runAll(log.events).projection.getSnapshot();
  7016. const originalMaxRowId = Math.max(...original.rows.window.map((row) => row.rowId));
  7017. log.push(SessionEventType.RewindTriggered, {
  7018. targetMessageId: "msg-u1",
  7019. scope: "conversation",
  7020. branchCutAfterMessageId: "msg-a1",
  7021. branchGeneration: 1,
  7022. });
  7023. const rewound = runAll(log.events).projection.getSnapshot();
  7024. expect(rewound.rows).toEqual({ window: [], totalCount: 0, firstRowId: null });
  7025. log.push(
  7026. SessionEventType.TurnStarted,
  7027. { turnNumber: 2, input: "你是谁", messageId: "msg-u2" },
  7028. { turnId: "t2" },
  7029. );
  7030. const rerun = runAll(log.events).projection.getSnapshot();
  7031. const newFirstRow = rerun.rows.window[0]!;
  7032. expect(newFirstRow.rowId).toBeGreaterThan(originalMaxRowId);
  7033. expect(rerun.rows.firstRowId).toBe(newFirstRow.rowId);
  7034. expect(rerun.rows.totalCount).toBe(rerun.rows.window.length);
  7035. });
  7036. it("D:getTurnRewindAnchor(user 行 rowId) → 同 turn 的 assistant messageId", () => {
  7037. const log = new EventLog();
  7038. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7039. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "问" }, { turnId: "t1" });
  7040. log.push(
  7041. SessionEventType.ModelStreaming,
  7042. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  7043. { turnId: "t1" },
  7044. );
  7045. log.push(
  7046. SessionEventType.ModelStreaming,
  7047. { kind: "text_delta", delta: "答", done: false, assistantMessageId: "msg-a1" },
  7048. { turnId: "t1" },
  7049. );
  7050. log.push(
  7051. SessionEventType.ModelStreaming,
  7052. { kind: "text_end", delta: "", done: false },
  7053. { turnId: "t1" },
  7054. );
  7055. const { projection } = runAll(log.events);
  7056. const userRow = projection.getSnapshot().rows.window.find((r) => r.kind === "userInput");
  7057. expect(userRow).toBeDefined();
  7058. // user 行自身无 messageId,但同 turn 的 assistant messageId 作 rewind 锚点。
  7059. expect(projection.getMessageIdForRow(userRow!.rowId)).toBeNull();
  7060. expect(projection.getTurnRewindAnchor(userRow!.rowId)).toBe("msg-a1");
  7061. });
  7062. it("D/G:RewindTriggered 目标 messageId 无法反查(user 行无 messageId)→ 不误删", () => {
  7063. const log = new EventLog();
  7064. basicTurnEvents(log);
  7065. const before = runAll(log.events).projection.getSnapshot().rows.window.length;
  7066. log.push(SessionEventType.RewindTriggered, {
  7067. targetMessageId: "unknown-msg",
  7068. scope: "conversation",
  7069. createdMessageId: "msg-rewind-notice",
  7070. });
  7071. const after = runAll(log.events).projection.getSnapshot().rows.window.length;
  7072. expect(after).toBe(before);
  7073. });
  7074. it("D/E09 回归:unavailable rewind(无 createdMessageId)与 workspace 回滚不得截断 live 行", () => {
  7075. // Bugfix 回归(2026-07-06 case catalog 战役):finishUnavailable 也发 RewindTriggered,
  7076. // 投影曾不加区分地截断 live 行——store/模型上下文却保留旧分支(假截断),
  7077. // fork child / 刷新 hydration 随后把旧分支复活(E09 失败形态)。
  7078. const log = new EventLog();
  7079. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7080. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "问" }, { turnId: "t1" });
  7081. log.push(
  7082. SessionEventType.ModelStreaming,
  7083. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  7084. { turnId: "t1" },
  7085. );
  7086. log.push(
  7087. SessionEventType.ModelStreaming,
  7088. { kind: "text_delta", delta: "答", done: false, assistantMessageId: "msg-a1" },
  7089. { turnId: "t1" },
  7090. );
  7091. log.push(
  7092. SessionEventType.ModelStreaming,
  7093. { kind: "text_end", delta: "", done: false },
  7094. { turnId: "t1" },
  7095. );
  7096. log.push(
  7097. SessionEventType.TurnComplete,
  7098. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  7099. { turnId: "t1" },
  7100. );
  7101. const beforeRows = runAll(log.events).projection.getSnapshot().rows.window.length;
  7102. expect(beforeRows).toBeGreaterThan(0);
  7103. // unavailable conversation rewind(无 createdMessageId)
  7104. log.push(SessionEventType.RewindTriggered, {
  7105. targetMessageId: "msg-a1",
  7106. scope: "conversation",
  7107. strategy: "unavailable",
  7108. reason: "target_message_is_not_user_prompt",
  7109. });
  7110. // workspace 文件回滚(带 createdMessageId 但 scope=workspace)
  7111. log.push(SessionEventType.RewindTriggered, {
  7112. targetMessageId: "msg-a1",
  7113. scope: "workspace",
  7114. createdMessageId: "msg-ws-notice",
  7115. });
  7116. const after = runAll(log.events).projection.getSnapshot().rows.window.length;
  7117. expect(after).toBe(beforeRows);
  7118. });
  7119. it("O10:ModelComplete.fileChanges 更新 turn header 摘要", () => {
  7120. const log = new EventLog();
  7121. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7122. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "改文件" }, { turnId: "t1" });
  7123. log.push(
  7124. SessionEventType.ModelComplete,
  7125. {
  7126. content: "done",
  7127. stopReason: "stop",
  7128. querySource: "main_turn",
  7129. contextWindow: 200_000,
  7130. usage: { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 },
  7131. fileChanges: {
  7132. files: 1,
  7133. additions: 2,
  7134. deletions: 1,
  7135. items: [{ path: "/work/src/demo.ts", additions: 2, deletions: 1, writeCount: 2 }],
  7136. },
  7137. },
  7138. { turnId: "t1" },
  7139. );
  7140. log.push(
  7141. SessionEventType.TurnComplete,
  7142. { response: "done", tokenCount: 2, toolCallCount: 0, duration: 1, resultType: "success" },
  7143. { turnId: "t1" },
  7144. );
  7145. const { projection } = runAll(log.events);
  7146. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  7147. expect(header).toMatchObject({
  7148. kind: "turnHeader",
  7149. fileChanges: {
  7150. additions: 2,
  7151. deletions: 1,
  7152. files: 1,
  7153. state: "active",
  7154. },
  7155. actions: { canRewindFiles: true },
  7156. });
  7157. const target = { rowId: header!.rowId, entityId: header!.entityId! };
  7158. expect(projection.resolveRowActionTarget(target, "applyFileRewind")).toMatchObject({
  7159. ok: true,
  7160. });
  7161. projection.applyEvent(
  7162. new EventLog().push(SessionEventType.CompactStarted, {
  7163. operationId: "compact-files",
  7164. messageId: "compact-files-message",
  7165. status: "started",
  7166. trigger: "manual",
  7167. display: "separator",
  7168. }),
  7169. );
  7170. const lockedHeader = projection
  7171. .getSnapshot()
  7172. .rows.window.find((row) => row.rowId === header!.rowId)!;
  7173. expect(lockedHeader.actions?.canRewindFiles).toBeUndefined();
  7174. expect(projection.resolveRowActionTarget(target, "applyFileRewind")).toEqual({
  7175. ok: false,
  7176. status: "rejected",
  7177. reasonCode: "guard.actionUnavailable",
  7178. });
  7179. });
  7180. it("O10:subagent ModelComplete 只更新 child turn 文件摘要,不覆盖 usage", () => {
  7181. const log = new EventLog();
  7182. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7183. log.push(
  7184. SessionEventType.TurnStarted,
  7185. { turnNumber: 1, input: "子会话改文件" },
  7186. { turnId: "t1" },
  7187. );
  7188. log.push(
  7189. SessionEventType.ModelComplete,
  7190. {
  7191. content: "done",
  7192. stopReason: "stop",
  7193. querySource: "subagent",
  7194. contextWindow: 999_999,
  7195. usage: { inputTokens: 100, outputTokens: 50, cacheReadTokens: 10, cacheWriteTokens: 5 },
  7196. fileChanges: {
  7197. files: 1,
  7198. additions: 1,
  7199. deletions: 0,
  7200. items: [{ path: "/work/src/child.ts", additions: 1, deletions: 0, writeCount: 1 }],
  7201. },
  7202. },
  7203. { turnId: "t1" },
  7204. );
  7205. log.push(
  7206. SessionEventType.TurnComplete,
  7207. { response: "done", tokenCount: 150, toolCallCount: 1, duration: 1, resultType: "success" },
  7208. { turnId: "t1" },
  7209. );
  7210. const { projection } = runAll(log.events);
  7211. const snapshot = projection.getSnapshot();
  7212. const header = snapshot.rows.window.find((row) => row.kind === "turnHeader");
  7213. expect(header).toMatchObject({
  7214. kind: "turnHeader",
  7215. fileChanges: {
  7216. additions: 1,
  7217. deletions: 0,
  7218. files: 1,
  7219. state: "active",
  7220. },
  7221. actions: { canRewindFiles: true },
  7222. });
  7223. expect(snapshot.usage.cumulative).toEqual({
  7224. inputTokens: 0,
  7225. outputTokens: 0,
  7226. cacheReadTokens: 0,
  7227. cacheWriteTokens: 0,
  7228. });
  7229. });
  7230. it("O10:普通 TurnStarted 的 user messageId 进入同轮文件摘要锚点", () => {
  7231. const log = new EventLog();
  7232. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7233. log.push(
  7234. SessionEventType.TurnStarted,
  7235. { turnNumber: 1, input: "改文件", messageId: "msg-user-1" },
  7236. { turnId: "t1" },
  7237. );
  7238. const { projection } = runAll(log.events);
  7239. const header = projection.getSnapshot().rows.window.find((row) => row.kind === "turnHeader");
  7240. expect(header).toBeDefined();
  7241. expect(projection.getMessageIdsForTurnRow(header!.rowId)).toContain("msg-user-1");
  7242. });
  7243. it("O12:workspace 文件撤销只标记 fileChanges.reverted,不移除聊天行", () => {
  7244. const log = new EventLog();
  7245. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7246. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "改文件" }, { turnId: "t1" });
  7247. log.push(
  7248. SessionEventType.ModelStreaming,
  7249. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  7250. { turnId: "t1" },
  7251. );
  7252. log.push(
  7253. SessionEventType.ModelStreaming,
  7254. { kind: "text_delta", delta: "已改", done: false, assistantMessageId: "msg-a1" },
  7255. { turnId: "t1" },
  7256. );
  7257. log.push(
  7258. SessionEventType.ModelStreaming,
  7259. { kind: "text_end", delta: "", done: false },
  7260. { turnId: "t1" },
  7261. );
  7262. log.push(
  7263. SessionEventType.ModelComplete,
  7264. {
  7265. content: "已改",
  7266. stopReason: "stop",
  7267. querySource: "main_turn",
  7268. contextWindow: 200_000,
  7269. usage: { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 },
  7270. fileChanges: {
  7271. files: 1,
  7272. additions: 2,
  7273. deletions: 1,
  7274. items: [{ path: "/work/src/demo.ts", additions: 2, deletions: 1, writeCount: 1 }],
  7275. },
  7276. },
  7277. { turnId: "t1" },
  7278. );
  7279. log.push(
  7280. SessionEventType.TurnComplete,
  7281. { response: "已改", tokenCount: 1, toolCallCount: 1, duration: 10, resultType: "success" },
  7282. { turnId: "t1" },
  7283. );
  7284. const before = runAll(log.events).projection.getSnapshot().rows.window;
  7285. log.push(SessionEventType.RewindTriggered, {
  7286. targetMessageId: "msg-a1",
  7287. scope: "workspace",
  7288. reason: "file_summary_rewind",
  7289. });
  7290. const { projection } = runAll(log.events);
  7291. const rows = projection.getSnapshot().rows.window;
  7292. expect(rows).toHaveLength(before.length);
  7293. const header = rows.find((row) => row.kind === "turnHeader");
  7294. expect(header).toMatchObject({
  7295. kind: "turnHeader",
  7296. fileChanges: {
  7297. additions: 2,
  7298. deletions: 1,
  7299. files: 1,
  7300. state: "reverted",
  7301. },
  7302. });
  7303. expect(rows.some((row) => row.kind === "assistantText" && row.text === "已改")).toBe(true);
  7304. });
  7305. });
  7306. // ── M5④ 附件渲染:TurnStarted.attachments → userInput row.attachments ──
  7307. describe("userInput 附件投影(M5④)", () => {
  7308. it("TurnStarted 携带附件元信息 → row.attachments 保真映射且 schema 合法", () => {
  7309. const log = new EventLog();
  7310. log.push(SessionEventType.SessionCreated, {
  7311. mode: "default",
  7312. contextWindow: 200_000,
  7313. });
  7314. log.push(
  7315. SessionEventType.TurnStarted,
  7316. {
  7317. turnNumber: 1,
  7318. input: "看看这张图",
  7319. inputId: "command-start-now",
  7320. intent: {
  7321. sourceCommandId: "command-start-now",
  7322. queueItemId: "queue_command-start-now",
  7323. clientId: "desktop-client",
  7324. kind: "sendText",
  7325. admissionSeq: 3,
  7326. admittedAt: 100,
  7327. requestedDelivery: "startNow",
  7328. admittedDelivery: "startNow",
  7329. },
  7330. attachments: [
  7331. {
  7332. fileName: "screenshot.png",
  7333. mime: "image/png",
  7334. bytes: 12345,
  7335. ref: "/tmp/screenshot.png",
  7336. },
  7337. // 无稳定引用(data URL 内联):ref 缺省 → 投影生成行内占位。
  7338. { fileName: "notes.md", mime: "text/markdown", bytes: 42 },
  7339. ],
  7340. },
  7341. { turnId: "turn-1" },
  7342. );
  7343. const { projection } = runAll(log.events);
  7344. const snapshot = projection.getSnapshot();
  7345. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  7346. const userInput = snapshot.rows.window.find((row) => row.kind === "userInput");
  7347. expect(userInput).toBeDefined();
  7348. expect(userInput).toMatchObject({
  7349. sourceCommandId: "command-start-now",
  7350. clientId: "desktop-client",
  7351. });
  7352. const attachments = userInput?.kind === "userInput" ? userInput.attachments : undefined;
  7353. expect(attachments).toHaveLength(2);
  7354. expect(attachments?.[0]).toEqual({
  7355. ref: "/tmp/screenshot.png",
  7356. fileName: "screenshot.png",
  7357. mime: "image/png",
  7358. bytes: 12345,
  7359. });
  7360. expect(attachments?.[1]).toMatchObject({
  7361. fileName: "notes.md",
  7362. mime: "text/markdown",
  7363. bytes: 42,
  7364. });
  7365. expect(attachments?.[1]?.ref).toMatch(/^turn-attachment\//);
  7366. });
  7367. it("无附件的 TurnStarted:row 不带 attachments 键(缺省语义)", () => {
  7368. const log = new EventLog();
  7369. basicTurnEvents(log);
  7370. const { projection } = runAll(log.events);
  7371. const userInput = projection.getSnapshot().rows.window.find((row) => row.kind === "userInput");
  7372. expect(userInput?.kind === "userInput" ? "attachments" in userInput : null).toBe(false);
  7373. });
  7374. });
  7375. // R-19(10 §4.2.3):config 种子——投影初值 = runtime 真值,种子不产 delta / 不 bump
  7376. // revision,事件触碰过的字段不接受种子覆盖("最终值以日志为准")。
  7377. // Bug 背景(2026-07-07 v4 桌面首测):初始 config 写死空 provider/model + mode=build,
  7378. // 导致新会话模型选择器显示空、持久化 mode=yolo 时 UI 停在 build 且点 yolo 静默 no-op。
  7379. describe("config 种子(R-19)", () => {
  7380. const SEED = {
  7381. provider: "prov-a",
  7382. model: "model-1",
  7383. thought: "high",
  7384. thoughtLevels: ["high", "max", "nothink"],
  7385. mode: "yolo",
  7386. };
  7387. it("种子填充空初值:config 就位、revision/seq 不动、schema 合法", () => {
  7388. const projection = new ProductProjection("session-1", "epoch-1");
  7389. projection.seedConfig(SEED);
  7390. const snapshot = projection.getSnapshot();
  7391. expect(snapshot.config).toMatchObject({
  7392. provider: "prov-a",
  7393. model: "model-1",
  7394. thought: "high",
  7395. thoughtLevels: ["high", "max", "nothink"],
  7396. mode: "yolo",
  7397. });
  7398. expect(snapshot.revision).toBe(0);
  7399. expect(snapshot.seq).toBe(0);
  7400. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  7401. });
  7402. it("种子后事件覆盖:ModelSelected / SessionModeChanged 的日志值优先", () => {
  7403. const projection = new ProductProjection("session-1", "epoch-1");
  7404. projection.seedConfig(SEED);
  7405. const log = new EventLog();
  7406. log.push(SessionEventType.ModelSelected, {
  7407. modelSelection: {
  7408. providerId: "prov-b",
  7409. modelId: "model-2",
  7410. options: { reasoningLevel: "low" },
  7411. },
  7412. supportedThoughtLevels: ["low", "high"],
  7413. });
  7414. log.push(SessionEventType.SessionModeChanged, {
  7415. mode: "plan",
  7416. previousMode: "yolo",
  7417. source: "command",
  7418. });
  7419. for (const event of log.events) projection.applyEvent(event);
  7420. expect(projection.getSnapshot().config).toMatchObject({
  7421. provider: "prov-b",
  7422. model: "model-2",
  7423. thought: "low",
  7424. thoughtLevels: ["low", "high"],
  7425. mode: "plan",
  7426. });
  7427. projection.seedConfig({ ...SEED, thoughtLevels: ["disabled"] });
  7428. expect(projection.getSnapshot().config.thoughtLevels).toEqual(["low", "high"]);
  7429. });
  7430. it("事件后种子不覆盖:冷恢复重放序在前时日志值保持权威", () => {
  7431. const projection = new ProductProjection("session-1", "epoch-1");
  7432. const log = new EventLog();
  7433. log.push(SessionEventType.ModelSelected, {
  7434. modelSelection: { providerId: "prov-b", modelId: "model-2" },
  7435. });
  7436. log.push(SessionEventType.SessionModeChanged, {
  7437. mode: "plan",
  7438. previousMode: "build",
  7439. source: "tool",
  7440. });
  7441. for (const event of log.events) projection.applyEvent(event);
  7442. projection.seedConfig(SEED);
  7443. expect(projection.getSnapshot().config).toMatchObject({
  7444. provider: "prov-b",
  7445. model: "model-2",
  7446. thoughtLevels: ["high", "max", "nothink"],
  7447. mode: "plan",
  7448. });
  7449. });
  7450. it("分区独立:只有 mode 被事件触碰时,模型区仍接受种子(反之亦然)", () => {
  7451. const projection = new ProductProjection("session-1", "epoch-1");
  7452. const log = new EventLog();
  7453. log.push(SessionEventType.SessionModeChanged, {
  7454. mode: "plan",
  7455. previousMode: "build",
  7456. source: "command",
  7457. });
  7458. for (const event of log.events) projection.applyEvent(event);
  7459. projection.seedConfig(SEED);
  7460. const config = projection.getSnapshot().config;
  7461. // mode 由日志裁决,模型区来自种子(历史会话恢复:resume 已把上次选型写回 runtime)。
  7462. expect(config.mode).toBe("plan");
  7463. expect(config).toMatchObject({
  7464. provider: "prov-a",
  7465. model: "model-1",
  7466. thought: "high",
  7467. thoughtLevels: ["high", "max", "nothink"],
  7468. });
  7469. });
  7470. it("相同种子幂等,明确留空的恢复结果清除旧模型", () => {
  7471. const projection = new ProductProjection("session-1", "epoch-1");
  7472. projection.seedConfig(SEED);
  7473. const first = projection.getSnapshot();
  7474. projection.seedConfig(SEED);
  7475. expect(projection.getSnapshot()).toBe(first);
  7476. // 恢复结果明确留空,不能继续显示历史消息留下的模型。
  7477. projection.seedConfig({ provider: "", model: "", mode: "" });
  7478. expect(projection.getSnapshot().config).toMatchObject({
  7479. provider: "",
  7480. model: "",
  7481. });
  7482. });
  7483. it("分享上下文导入种子只写只读来源元数据,不生成可见对话行", () => {
  7484. const projection = new ProductProjection("session-1", "epoch-1");
  7485. const before = projection.getSnapshot();
  7486. projection.seedSharedContextImport({ title: "筛选近一年收益前10%的偏股混合基金" });
  7487. const snapshot = projection.getSnapshot();
  7488. expect(snapshot.sharedContextImport).toEqual({
  7489. title: "筛选近一年收益前10%的偏股混合基金",
  7490. });
  7491. expect(snapshot.rows.window).toEqual([]);
  7492. expect(snapshot.revision).toBe(before.revision);
  7493. expect(snapshot.seq).toBe(before.seq);
  7494. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  7495. });
  7496. });
  7497. // ── 16-timeline-authority-plan P2:productTurn 切分 / goalVerify 身份与落位 ──
  7498. describe("P2 productTurn 切分(S1/S3/S5)", () => {
  7499. const drainScenario = (delivery: "queue" | "guide") => {
  7500. const log = new EventLog();
  7501. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7502. log.push(
  7503. SessionEventType.TurnStarted,
  7504. { turnNumber: 1, input: "问题一" },
  7505. { turnId: "turn-1" },
  7506. );
  7507. log.push(
  7508. SessionEventType.ModelStreaming,
  7509. { kind: "text_start", delta: "", done: false },
  7510. { turnId: "turn-1" },
  7511. );
  7512. log.push(
  7513. SessionEventType.ModelStreaming,
  7514. { kind: "text_delta", delta: "回答一", done: false },
  7515. { turnId: "turn-1" },
  7516. );
  7517. log.push(
  7518. SessionEventType.ModelStreaming,
  7519. { kind: "text_end", delta: "", done: false },
  7520. { turnId: "turn-1" },
  7521. );
  7522. log.push(
  7523. SessionEventType.TurnSteerQueued,
  7524. {
  7525. pendingInputId: "p-q2",
  7526. input: "问题二",
  7527. inputPreview: "问题二",
  7528. inputSize: 9,
  7529. delivery,
  7530. targetTurnId: "turn-1",
  7531. queueLength: 1,
  7532. },
  7533. { turnId: "turn-1" },
  7534. );
  7535. log.push(
  7536. SessionEventType.TurnSteerDrained,
  7537. {
  7538. pendingInputIds: ["p-q2"],
  7539. injectedMessageIds: ["msg-q2"],
  7540. drainedInputs: [
  7541. {
  7542. pendingInputId: "p-q2",
  7543. messageId: "msg-q2",
  7544. text: "问题二",
  7545. delivery,
  7546. intent: {
  7547. sourceCommandId: "command-q2",
  7548. queueItemId: "p-q2",
  7549. clientId: "desktop-continuous",
  7550. kind: delivery === "guide" ? "sendGoalCommand" : "sendText",
  7551. text: "问题二",
  7552. admissionSeq: 2,
  7553. admittedAt: 1_700_000_006_000,
  7554. requestedDelivery: "auto",
  7555. admittedDelivery: delivery,
  7556. fallbackReasonCode: "runtime.turnBusy",
  7557. attachmentRefs: [
  7558. {
  7559. ref: "artifact://q2",
  7560. fileName: "q2.txt",
  7561. mime: "text/plain",
  7562. bytes: 3,
  7563. },
  7564. ],
  7565. provenance: {
  7566. sourceCommandId: "command-q2-original",
  7567. queueItemId: "p-q2-original",
  7568. clientId: "desktop-continuous",
  7569. },
  7570. },
  7571. },
  7572. ],
  7573. targetTurnId: "turn-1",
  7574. },
  7575. { turnId: "turn-1" },
  7576. );
  7577. log.push(
  7578. SessionEventType.ModelStreaming,
  7579. { kind: "text_start", delta: "", done: false },
  7580. { turnId: "turn-1" },
  7581. );
  7582. log.push(
  7583. SessionEventType.ModelStreaming,
  7584. { kind: "text_delta", delta: "回答二", done: false },
  7585. { turnId: "turn-1" },
  7586. );
  7587. log.push(
  7588. SessionEventType.ModelStreaming,
  7589. { kind: "text_end", delta: "", done: false },
  7590. { turnId: "turn-1" },
  7591. );
  7592. log.push(
  7593. SessionEventType.TurnComplete,
  7594. { response: "", tokenCount: 0, toolCallCount: 0, duration: 9000, resultType: "success" },
  7595. { turnId: "turn-1" },
  7596. );
  7597. return runAll(log.events);
  7598. };
  7599. it("QD-node:queue drain 切新 productTurn,两段回复都可见、工时按边界拆分(Case A 根修)", () => {
  7600. const { projection } = drainScenario("queue");
  7601. const snapshot = projection.getSnapshot();
  7602. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  7603. const rows = snapshot.rows.window;
  7604. // 两个 turnHeader:首轮 legacy runtime id 与 promoted user messageId(稳定 productTurn)。
  7605. const headers = rows.filter((row) => row.kind === "turnHeader");
  7606. expect(headers.map((row) => row.turnId)).toEqual(["turn-1", "msg-q2"]);
  7607. // 第一段 header 在 drain 边界收口:activeMs = drain(7s) - start(2s)。
  7608. expect(headers[0]).toMatchObject({ state: "completedSuccess", activeMs: 5000 });
  7609. // 第二段 header 在 TurnComplete 收口:activeMs = complete(11s) - drain(7s),
  7610. // 不再是整段 runtime duration(9000)。
  7611. expect(headers[1]).toMatchObject({ state: "completedSuccess", activeMs: 4000 });
  7612. // 两段 assistant 正文都在,各归自己的 productTurn——A1 不再被折进上一轮 history。
  7613. const assistantRows = rows.filter((row) => row.kind === "assistantText");
  7614. expect(
  7615. assistantRows.map((row) => [row.turnId, row.kind === "assistantText" ? row.text : ""]),
  7616. ).toEqual([
  7617. ["turn-1", "回答一"],
  7618. ["msg-q2", "回答二"],
  7619. ]);
  7620. // drained user 行归新 productTurn,并原子登记 message/entity/edit target。
  7621. const drainedUser = rows.find((row) => row.kind === "userInput" && row.text === "问题二");
  7622. expect(drainedUser?.turnId).toBe("msg-q2");
  7623. expect(projection.getMessageIdForRow(drainedUser!.rowId)).toBe("msg-q2");
  7624. expect(projection.getEntityIdForRow(drainedUser!.rowId)).toBe("msg-q2");
  7625. expect(drainedUser?.actions).toMatchObject({ canEdit: true, editDisposition: "rewind" });
  7626. expect(
  7627. projection.resolveRowActionTarget(
  7628. { rowId: drainedUser!.rowId, entityId: drainedUser!.entityId },
  7629. "editUserQuery",
  7630. ),
  7631. ).toMatchObject({
  7632. ok: true,
  7633. editTarget: {
  7634. entityId: "msg-q2",
  7635. productTurnId: "msg-q2",
  7636. transcriptMessageId: "msg-q2",
  7637. intent: {
  7638. kind: "sendText",
  7639. text: "问题二",
  7640. sourceCommandId: "command-q2",
  7641. queueItemId: "p-q2",
  7642. clientId: "desktop-continuous",
  7643. admissionSeq: 2,
  7644. admittedAt: 1_700_000_006_000,
  7645. requestedDelivery: "auto",
  7646. admittedDelivery: "queue",
  7647. fallbackReasonCode: "runtime.turnBusy",
  7648. attachments: [
  7649. {
  7650. ref: "artifact://q2",
  7651. fileName: "q2.txt",
  7652. mime: "text/plain",
  7653. bytes: 3,
  7654. },
  7655. ],
  7656. provenance: {
  7657. sourceCommandId: "command-q2-original",
  7658. queueItemId: "p-q2-original",
  7659. clientId: "desktop-continuous",
  7660. },
  7661. },
  7662. },
  7663. });
  7664. const coldLog = new EventLog();
  7665. coldLog.push(
  7666. SessionEventType.TurnStarted,
  7667. { turnNumber: 2, input: "问题二", messageId: "msg-q2" },
  7668. { turnId: "hydrate-turn-2" },
  7669. );
  7670. const coldUser = runAll(coldLog.events)
  7671. .projection.getSnapshot()
  7672. .rows.window.find((row) => row.kind === "userInput");
  7673. // 同一 promoted user transcript 在 live drain 与 cold TurnStarted 中使用同一 productTurnId。
  7674. expect(coldUser?.turnId).toBe(drainedUser?.turnId);
  7675. expect(snapshot.queue.items).toEqual([]);
  7676. });
  7677. it("P06:guide steer 内联不切轮,但 accepted guide 开启独立可恢复工时段", () => {
  7678. const { projection } = drainScenario("guide");
  7679. const snapshot = projection.getSnapshot();
  7680. const rows = snapshot.rows.window;
  7681. const headers = rows.filter((row) => row.kind === "turnHeader");
  7682. expect(headers.map((row) => row.turnId)).toEqual(["turn-1"]);
  7683. expect(headers[0]).toMatchObject({
  7684. state: "completedSuccess",
  7685. activeMs: 9000,
  7686. workSegments: [
  7687. {
  7688. segmentId: "turn-1:initial",
  7689. startedAt: 1_700_000_002_000,
  7690. endedAt: 1_700_000_007_000,
  7691. activeMs: 5000,
  7692. },
  7693. {
  7694. segmentId: "msg-q2",
  7695. triggerEntityId: "msg-q2",
  7696. startedAt: 1_700_000_007_000,
  7697. endedAt: 1_700_000_011_000,
  7698. activeMs: 4000,
  7699. },
  7700. ],
  7701. });
  7702. const steerUser = rows.find((row) => row.kind === "userInput" && row.text === "问题二");
  7703. expect(steerUser?.turnId).toBe("turn-1");
  7704. expect(steerUser?.actions).toMatchObject({ canEdit: true, editDisposition: "rewind" });
  7705. expect(
  7706. projection.resolveRowActionTarget(
  7707. { rowId: steerUser!.rowId, entityId: steerUser!.entityId },
  7708. "editUserQuery",
  7709. ),
  7710. ).toMatchObject({
  7711. ok: true,
  7712. editTarget: {
  7713. entityId: "msg-q2",
  7714. productTurnId: "turn-1",
  7715. transcriptMessageId: "msg-q2",
  7716. intent: {
  7717. kind: "sendGoalCommand",
  7718. text: "问题二",
  7719. sourceCommandId: "command-q2",
  7720. queueItemId: "p-q2",
  7721. admittedDelivery: "guide",
  7722. },
  7723. },
  7724. });
  7725. // 内联位置:在 A1 之后、A2 之前。
  7726. const order = rows
  7727. .filter((row) => row.kind === "assistantText" || row.kind === "userInput")
  7728. .map((row) => (row.kind === "assistantText" || row.kind === "userInput" ? row.text : ""));
  7729. expect(order).toEqual(["问题一", "回答一", "问题二", "回答二"]);
  7730. });
  7731. it("兼容:旧 runtime 事件(无 drainedInputs/delivery)回退 queue 查表,按 followupMode 兜底切轮", () => {
  7732. const log = new EventLog();
  7733. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7734. log.push(
  7735. SessionEventType.TurnStarted,
  7736. { turnNumber: 1, input: "问题一" },
  7737. { turnId: "turn-1" },
  7738. );
  7739. log.push(
  7740. SessionEventType.TurnSteerQueued,
  7741. {
  7742. pendingInputId: "p-legacy",
  7743. input: "老事件文本",
  7744. inputPreview: "老事件文本",
  7745. inputSize: 15,
  7746. targetTurnId: "turn-1",
  7747. queueLength: 1,
  7748. },
  7749. { turnId: "turn-1" },
  7750. );
  7751. log.push(
  7752. SessionEventType.TurnSteerDrained,
  7753. {
  7754. pendingInputIds: ["p-legacy"],
  7755. injectedMessageIds: ["msg-legacy"],
  7756. targetTurnId: "turn-1",
  7757. },
  7758. { turnId: "turn-1" },
  7759. );
  7760. const { projection } = runAll(log.events);
  7761. const rows = projection.getSnapshot().rows.window;
  7762. const drained = rows.find((row) => row.kind === "userInput" && row.text === "老事件文本");
  7763. // followupMode 默认 queue → 切轮;旧事件虽无 drainedInputs,injectedMessageIds
  7764. // 仍是 promotion 后的持久 user 身份,因此 product turn 也稳定使用该 messageId。
  7765. expect(drained?.turnId).toBe("msg-legacy");
  7766. expect(projection.getMessageIdForRow(drained!.rowId)).toBe("msg-legacy");
  7767. });
  7768. it("PV4-10 防御:drain 缺持久 messageId 时不暴露无法执行的 edit action", () => {
  7769. const log = new EventLog();
  7770. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  7771. log.push(
  7772. SessionEventType.TurnStarted,
  7773. { turnNumber: 1, input: "问题一" },
  7774. { turnId: "turn-1" },
  7775. );
  7776. log.push(
  7777. SessionEventType.TurnSteerQueued,
  7778. {
  7779. pendingInputId: "p-no-message",
  7780. input: "缺少持久身份",
  7781. inputPreview: "缺少持久身份",
  7782. inputSize: 18,
  7783. targetTurnId: "turn-1",
  7784. queueLength: 1,
  7785. },
  7786. { turnId: "turn-1" },
  7787. );
  7788. log.push(
  7789. SessionEventType.TurnSteerDrained,
  7790. { pendingInputIds: ["p-no-message"], targetTurnId: "turn-1" },
  7791. { turnId: "turn-1" },
  7792. );
  7793. const { projection } = runAll(log.events);
  7794. const drained = projection
  7795. .getSnapshot()
  7796. .rows.window.find((row) => row.kind === "userInput" && row.text === "缺少持久身份");
  7797. expect(drained?.actions?.canEdit).not.toBe(true);
  7798. expect(
  7799. projection.resolveRowActionTarget(
  7800. { rowId: drained!.rowId, entityId: drained!.entityId },
  7801. "editUserQuery",
  7802. ),
  7803. ).toEqual({
  7804. ok: false,
  7805. status: "rejected",
  7806. reasonCode: "guard.actionUnavailable",
  7807. });
  7808. });
  7809. });
  7810. describe("P2 goalVerify 身份与落位(GV-identity / GV-terminal-only / GV-late-anchor)", () => {
  7811. it("同 targetId+iteration 的重试(新 verificationId)复用同一 marker,不长第二个", () => {
  7812. const log = new EventLog();
  7813. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  7814. log.push(SessionEventType.TargetCompletionVerification, {
  7815. targetId: "target-1",
  7816. status: "started",
  7817. verificationId: "attempt-1",
  7818. goalIteration: 1,
  7819. });
  7820. log.push(SessionEventType.TargetCompletionVerification, {
  7821. targetId: "target-1",
  7822. status: "started",
  7823. verificationId: "attempt-2",
  7824. goalIteration: 1,
  7825. });
  7826. log.push(SessionEventType.TargetCompletionVerification, {
  7827. targetId: "target-1",
  7828. status: "completed",
  7829. verificationId: "attempt-2",
  7830. goalIteration: 1,
  7831. verification: { passed: true, reason: "ok" },
  7832. });
  7833. const { projection } = runAll(log.events);
  7834. const markers = projection
  7835. .getSnapshot()
  7836. .rows.window.filter(
  7837. (row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify",
  7838. );
  7839. expect(markers).toHaveLength(1);
  7840. expect(markers[0]).toMatchObject({ marker: { iteration: 1, outcome: "pass" } });
  7841. });
  7842. it("GV-terminal-only:终态先到(无 started、无 goal 状态)也能创建 boundary", () => {
  7843. const log = new EventLog();
  7844. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  7845. log.push(SessionEventType.TargetCompletionVerification, {
  7846. targetId: "target-1",
  7847. status: "completed",
  7848. verificationId: "only-terminal",
  7849. goalIteration: 3,
  7850. verification: { passed: false, reason: "还差测试" },
  7851. });
  7852. const { projection } = runAll(log.events);
  7853. const marker = projection
  7854. .getSnapshot()
  7855. .rows.window.find((row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify");
  7856. expect(marker).toMatchObject({
  7857. marker: { iteration: 3, outcome: "notSatisfied", detail: "还差测试" },
  7858. });
  7859. });
  7860. it("GV-late-anchor:verify 迟到到下一轮之后,按 anchorTurnId 锚回被验证的轮", () => {
  7861. const log = new EventLog();
  7862. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  7863. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "Q1" }, { turnId: "turn-1" });
  7864. log.push(
  7865. SessionEventType.TurnComplete,
  7866. { response: "", tokenCount: 0, toolCallCount: 0, duration: 100, resultType: "success" },
  7867. { turnId: "turn-1" },
  7868. );
  7869. log.push(SessionEventType.TurnStarted, { turnNumber: 2, input: "Q2" }, { turnId: "turn-2" });
  7870. // 迟到的 verify:事件本身归属 turn-2 期间,但 payload 锚定 turn-1。
  7871. log.push(SessionEventType.TargetCompletionVerification, {
  7872. targetId: "target-1",
  7873. status: "started",
  7874. verificationId: "late-1",
  7875. goalIteration: 1,
  7876. anchorTurnId: "turn-1",
  7877. });
  7878. const { projection } = runAll(log.events);
  7879. const marker = projection
  7880. .getSnapshot()
  7881. .rows.window.find((row) => row.kind === "timelineMarker" && row.marker.type === "goalVerify");
  7882. // UI 按 turnId 分组:锚回 turn-1 而不是落进 turn-2 或 "turn-unknown"。
  7883. expect(marker?.turnId).toBe("turn-1");
  7884. });
  7885. });
  7886. describe("Desktop Hook invocation projection", () => {
  7887. it("keeps the shared Hook event enum aligned with Coding contracts", () => {
  7888. expect(new Set(hookInvocationRowSchema.shape.hookEventName.options)).toEqual(
  7889. new Set(Object.values(HookEventName)),
  7890. );
  7891. });
  7892. const descriptor = {
  7893. clientVisible: true as const,
  7894. sourceKind: "user" as const,
  7895. sourcePath: "/Users/example/.zcode/cli/config.json",
  7896. executionType: "process" as const,
  7897. executionMode: "foreground" as const,
  7898. commandDisplay: "node hooks/check.mjs",
  7899. timeoutMs: 5_000,
  7900. };
  7901. it("HK08/HK10 projects safe Hook summaries into the authoritative real turn", () => {
  7902. const log = new EventLog();
  7903. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1_000 });
  7904. log.push(
  7905. SessionEventType.HookRunStarted,
  7906. {
  7907. descriptor,
  7908. hookEventName: "SessionStart",
  7909. hookIndex: 0,
  7910. hookCount: 1,
  7911. hookInvocationId: "startup-hook",
  7912. hookRunId: "startup-run",
  7913. startedAt: 1_700_000_002_000,
  7914. },
  7915. { turnId: "runtime-turn-before-product-mapping" },
  7916. );
  7917. log.push(
  7918. SessionEventType.HookRunCompleted,
  7919. {
  7920. descriptor,
  7921. durationMs: 10,
  7922. hookEventName: "SessionStart",
  7923. hookIndex: 0,
  7924. hookCount: 1,
  7925. hookInvocationId: "startup-hook",
  7926. hookRunId: "startup-run",
  7927. outcome: "success",
  7928. startedAt: 1_700_000_002_000,
  7929. },
  7930. { turnId: "runtime-turn-before-product-mapping" },
  7931. );
  7932. const beforeTurn = runAll(log.events).projection.getSnapshot();
  7933. expect(beforeTurn.rows.window.some((row) => row.kind === "hookInvocation")).toBe(false);
  7934. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  7935. log.push(
  7936. SessionEventType.HookRunStarted,
  7937. {
  7938. descriptor,
  7939. hookEventName: "PreToolUse",
  7940. hookIndex: 0,
  7941. hookCount: 1,
  7942. hookInvocationId: "tool-hook",
  7943. hookRunId: "tool-run",
  7944. startedAt: 1_700_000_003_000,
  7945. toolCallId: "tool-1",
  7946. toolName: "Write",
  7947. },
  7948. { turnId: "turn-1" },
  7949. );
  7950. log.push(
  7951. SessionEventType.HookRunCompleted,
  7952. {
  7953. descriptor,
  7954. durationMs: 20,
  7955. hookEventName: "PreToolUse",
  7956. hookIndex: 0,
  7957. hookCount: 1,
  7958. hookInvocationId: "tool-hook",
  7959. hookRunId: "tool-run",
  7960. outcome: "success",
  7961. startedAt: 1_700_000_003_000,
  7962. toolCallId: "tool-1",
  7963. toolName: "Write",
  7964. },
  7965. { turnId: "turn-1" },
  7966. );
  7967. const { projection } = runAll(log.events);
  7968. const hookRows = projection
  7969. .getSnapshot()
  7970. .rows.window.filter((row) => row.kind === "hookInvocation");
  7971. expect(hookRows).toHaveLength(2);
  7972. expect(hookRows.map((row) => row.turnId)).toEqual(["turn-1", "turn-1"]);
  7973. expect(hookRows[0]).toMatchObject({
  7974. hookEventName: "SessionStart",
  7975. executions: [
  7976. expect.objectContaining({
  7977. didExecute: true,
  7978. displayName: "node · check.mjs",
  7979. sourceKind: "user",
  7980. }),
  7981. ],
  7982. });
  7983. expect(hookRows[1]).toMatchObject({
  7984. hookEventName: "PreToolUse",
  7985. anchorToolCallId: "tool-1",
  7986. executions: [
  7987. expect.objectContaining({
  7988. didExecute: true,
  7989. displayName: "node · check.mjs",
  7990. sourceKind: "user",
  7991. toolName: "Write",
  7992. }),
  7993. ],
  7994. });
  7995. expect(JSON.stringify(hookRows)).not.toMatch(/commandDisplay|sourcePath/u);
  7996. expect(projection.getSnapshot().rows.window.map((row) => row.turnId)).not.toContain(
  7997. "session-hooks:session-1",
  7998. );
  7999. });
  8000. it("HK09 distinguishes admission-only blocked from a Hook that executed and blocked", () => {
  8001. const log = new EventLog();
  8002. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8003. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  8004. log.push(
  8005. SessionEventType.HookRunBlocked,
  8006. {
  8007. descriptor,
  8008. hookEventName: "PreToolUse",
  8009. hookIndex: 0,
  8010. hookCount: 2,
  8011. hookInvocationId: "mixed-hook",
  8012. hookRunId: "admission-blocked",
  8013. outcome: "blocked",
  8014. startedAt: 1_700_000_003_000,
  8015. },
  8016. { turnId: "turn-1" },
  8017. );
  8018. log.push(
  8019. SessionEventType.HookRunStarted,
  8020. {
  8021. descriptor,
  8022. hookEventName: "PreToolUse",
  8023. hookIndex: 1,
  8024. hookCount: 2,
  8025. hookInvocationId: "mixed-hook",
  8026. hookRunId: "executed-block",
  8027. startedAt: 1_700_000_003_010,
  8028. },
  8029. { turnId: "turn-1" },
  8030. );
  8031. log.push(
  8032. SessionEventType.HookRunBlocked,
  8033. {
  8034. descriptor,
  8035. durationMs: 8,
  8036. hookEventName: "PreToolUse",
  8037. hookIndex: 1,
  8038. hookCount: 2,
  8039. hookInvocationId: "mixed-hook",
  8040. hookRunId: "executed-block",
  8041. blockReason: "blocked by workspace policy",
  8042. outcome: "blocked",
  8043. startedAt: 1_700_000_003_010,
  8044. },
  8045. { turnId: "turn-1" },
  8046. );
  8047. const row = runAll(log.events)
  8048. .projection.getSnapshot()
  8049. .rows.window.find((candidate) => candidate.kind === "hookInvocation");
  8050. expect(row).toMatchObject({
  8051. state: "completed",
  8052. executions: [
  8053. expect.objectContaining({ hookRunId: "admission-blocked", didExecute: false }),
  8054. expect.objectContaining({
  8055. hookRunId: "executed-block",
  8056. didExecute: true,
  8057. outcome: "blocked",
  8058. blockReason: "blocked by workspace policy",
  8059. }),
  8060. ],
  8061. });
  8062. });
  8063. it("HK-UP-02 projects an executed UserPromptSubmit block into the chat error", () => {
  8064. const log = new EventLog();
  8065. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1_000 });
  8066. log.push(
  8067. SessionEventType.TurnStarted,
  8068. { turnNumber: 1, input: "blocked prompt" },
  8069. { turnId: "turn-1" },
  8070. );
  8071. log.push(
  8072. SessionEventType.HookRunStarted,
  8073. {
  8074. descriptor,
  8075. hookEventName: "UserPromptSubmit",
  8076. hookIndex: 0,
  8077. hookCount: 1,
  8078. hookInvocationId: "prompt-hook",
  8079. hookRunId: "prompt-run",
  8080. startedAt: 1_700_000_003_000,
  8081. },
  8082. { turnId: "turn-1" },
  8083. );
  8084. log.push(
  8085. SessionEventType.HookRunBlocked,
  8086. {
  8087. descriptor,
  8088. durationMs: 12,
  8089. hookEventName: "UserPromptSubmit",
  8090. hookIndex: 0,
  8091. hookCount: 1,
  8092. hookInvocationId: "prompt-hook",
  8093. hookRunId: "prompt-run",
  8094. blockReason: "hooks_prompt_block",
  8095. errorMessage:
  8096. "python3: can't open file '/workspace/a.py': [Errno 2] No such file or directory",
  8097. stderrPreview:
  8098. "python3: can't open file '/workspace/a.py': [Errno 2] No such file or directory",
  8099. outcome: "blocked",
  8100. startedAt: 1_700_000_003_000,
  8101. },
  8102. { turnId: "turn-1" },
  8103. );
  8104. log.push(
  8105. SessionEventType.TurnComplete,
  8106. {
  8107. response: "HOOK_PROMPT_BLOCK_REASON",
  8108. tokenCount: 0,
  8109. toolCallCount: 0,
  8110. duration: 12,
  8111. resultType: "success",
  8112. },
  8113. { turnId: "turn-1" },
  8114. );
  8115. const { projection } = runAll(log.events);
  8116. const snapshot = projection.getSnapshot();
  8117. expect(snapshot.control.phase).toBe("completedSuccess");
  8118. expect(snapshot.control.lastError).toMatchObject({
  8119. code: "fault.runtime.hookBlocked",
  8120. message:
  8121. "hooks_prompt_block: python3: can't open file '/workspace/a.py': [Errno 2] No such file or directory",
  8122. detail:
  8123. "Hook block reason: hooks_prompt_block\nHook error: python3: can't open file '/workspace/a.py': [Errno 2] No such file or directory",
  8124. recoverable: false,
  8125. source: "runtime",
  8126. traceId: "trace-1",
  8127. attribution: { source: "runtime", reason: "hook_blocked" },
  8128. });
  8129. });
  8130. it.each([
  8131. [SessionEventType.HookRunCompleted, "success"],
  8132. [SessionEventType.HookRunFailed, "failed"],
  8133. ] as const)("HK09 keeps terminal-only %s as not executed", (terminalType, outcome) => {
  8134. const log = new EventLog();
  8135. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8136. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  8137. log.push(
  8138. terminalType,
  8139. {
  8140. descriptor,
  8141. durationMs: 20,
  8142. hookEventName: "PreToolUse",
  8143. hookIndex: 0,
  8144. hookCount: 1,
  8145. hookInvocationId: `terminal-only-${outcome}`,
  8146. hookRunId: `terminal-only-run-${outcome}`,
  8147. outcome,
  8148. startedAt: 1_700_000_003_000,
  8149. },
  8150. { turnId: "turn-1", timestampMs: 1_700_000_003_020 },
  8151. );
  8152. const row = runAll(log.events)
  8153. .projection.getSnapshot()
  8154. .rows.window.find((candidate) => candidate.kind === "hookInvocation");
  8155. expect(row).toMatchObject({
  8156. executions: [expect.objectContaining({ didExecute: false, outcome })],
  8157. });
  8158. });
  8159. it("HK13 updates a late async terminal in place without reopening the completed turn", () => {
  8160. const log = new EventLog();
  8161. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8162. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  8163. log.push(
  8164. SessionEventType.HookRunStarted,
  8165. {
  8166. descriptor: { ...descriptor, executionMode: "background" },
  8167. hookEventName: "UserPromptSubmit",
  8168. hookIndex: 0,
  8169. hookCount: 1,
  8170. hookInvocationId: "async-hook",
  8171. hookRunId: "async-run",
  8172. startedAt: 1_700_000_003_000,
  8173. },
  8174. { turnId: "turn-1", timestampMs: 1_700_000_003_000 },
  8175. );
  8176. log.push(
  8177. SessionEventType.TurnComplete,
  8178. { response: "done", tokenCount: 1, toolCallCount: 0, duration: 10, resultType: "success" },
  8179. { turnId: "turn-1", timestampMs: 1_700_000_003_010 },
  8180. );
  8181. log.push(
  8182. SessionEventType.HookRunCompleted,
  8183. {
  8184. descriptor: { ...descriptor, executionMode: "background" },
  8185. durationMs: 50,
  8186. hookEventName: "UserPromptSubmit",
  8187. hookIndex: 0,
  8188. hookCount: 1,
  8189. hookInvocationId: "async-hook",
  8190. hookRunId: "async-run",
  8191. outcome: "success",
  8192. startedAt: 1_700_000_003_000,
  8193. },
  8194. { turnId: "turn-1", timestampMs: 1_700_000_003_050 },
  8195. );
  8196. const { deltasPerEvent, projection } = runAll(log.events);
  8197. expect(deltasPerEvent[4]).toContainEqual(
  8198. expect.objectContaining({
  8199. op: "row.upserted",
  8200. row: expect.objectContaining({ hookInvocationId: "async-hook", state: "completed" }),
  8201. }),
  8202. );
  8203. expect(projection.getSnapshot().control.phase).toBe("completedSuccess");
  8204. expect(
  8205. projection
  8206. .getSnapshot()
  8207. .rows.window.filter(
  8208. (row) => row.kind === "hookInvocation" && row.hookInvocationId === "async-hook",
  8209. ),
  8210. ).toHaveLength(1);
  8211. });
  8212. it("HK13 closes an attached started-only execution on a real runtime resume", () => {
  8213. const log = new EventLog();
  8214. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8215. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  8216. log.push(
  8217. SessionEventType.HookRunStarted,
  8218. {
  8219. descriptor,
  8220. hookEventName: "PreToolUse",
  8221. hookIndex: 0,
  8222. hookCount: 1,
  8223. hookInvocationId: "started-only-hook",
  8224. hookRunId: "started-only-run",
  8225. startedAt: 1_700_000_002_000,
  8226. },
  8227. { turnId: "turn-1", timestampMs: 1_700_000_002_000 },
  8228. );
  8229. log.push(SessionEventType.SessionResumed, {}, { timestampMs: 1_700_000_003_000 });
  8230. const row = runAll(log.events)
  8231. .projection.getSnapshot()
  8232. .rows.window.find((candidate) => candidate.kind === "hookInvocation");
  8233. expect(row).toMatchObject({
  8234. state: "failed",
  8235. executions: [
  8236. {
  8237. didExecute: true,
  8238. state: "failed",
  8239. outcome: "cancelled",
  8240. durationMs: 1_000,
  8241. },
  8242. ],
  8243. });
  8244. });
  8245. it("HK17 does not flush a pending SessionStart summary onto a model-only compact turn", () => {
  8246. // Bug 根因:Runtime 的 runSessionStartHooks 先于 /compact 输入解析执行,首条输入即
  8247. // /compact 时 SessionStart Hook 真实执行且携带 compact 的 runtime turnId;投影层
  8248. // flush 只看「下一条 TurnStarted」,把摘要挂到了 model-only 维护 turn 上。
  8249. const log = new EventLog();
  8250. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  8251. log.push(
  8252. SessionEventType.HookRunStarted,
  8253. {
  8254. descriptor,
  8255. hookEventName: "SessionStart",
  8256. hookIndex: 0,
  8257. hookCount: 1,
  8258. hookInvocationId: "startup-hook",
  8259. hookRunId: "startup-run",
  8260. startedAt: 1_700_000_002_000,
  8261. },
  8262. { turnId: "turn-1", timestampMs: 1_700_000_002_000 },
  8263. );
  8264. log.push(
  8265. SessionEventType.HookRunCompleted,
  8266. {
  8267. descriptor,
  8268. durationMs: 10,
  8269. hookEventName: "SessionStart",
  8270. hookIndex: 0,
  8271. hookCount: 1,
  8272. hookInvocationId: "startup-hook",
  8273. hookRunId: "startup-run",
  8274. outcome: "success",
  8275. startedAt: 1_700_000_002_000,
  8276. },
  8277. { turnId: "turn-1", timestampMs: 1_700_000_002_010 },
  8278. );
  8279. // compact 维护 turn:inputVisibility=model-only,无 user bubble。
  8280. log.push(
  8281. SessionEventType.TurnStarted,
  8282. { turnNumber: 1, input: "/compact", inputVisibility: "model-only" },
  8283. { turnId: "turn-1", timestampMs: 1_700_000_003_000 },
  8284. );
  8285. log.push(
  8286. SessionEventType.CompactStarted,
  8287. {
  8288. operationId: "op-1",
  8289. messageId: "msg-compact",
  8290. status: "started",
  8291. trigger: "manual",
  8292. display: "separator",
  8293. },
  8294. { turnId: "turn-1", timestampMs: 1_700_000_003_050 },
  8295. );
  8296. log.push(
  8297. SessionEventType.CompactCompleted,
  8298. {
  8299. operationId: "op-1",
  8300. messageId: "msg-compact",
  8301. status: "completed",
  8302. trigger: "manual",
  8303. display: "separator",
  8304. },
  8305. { turnId: "turn-1", timestampMs: 1_700_000_004_000 },
  8306. );
  8307. log.push(
  8308. SessionEventType.TurnComplete,
  8309. {
  8310. response: "compacted",
  8311. tokenCount: 1,
  8312. toolCallCount: 0,
  8313. duration: 1_000,
  8314. resultType: "success",
  8315. },
  8316. { turnId: "turn-1", timestampMs: 1_700_000_004_050 },
  8317. );
  8318. const afterCompact = runAll(log.events).projection.getSnapshot();
  8319. // compact 维护 turn 不承载 SessionStart 摘要:不得出现挂在 turn-1 的 hook row。
  8320. expect(afterCompact.rows.window.filter((row) => row.kind === "hookInvocation")).toHaveLength(0);
  8321. // 下一条真实 user-visible turn 才是合法收口目标。
  8322. log.push(
  8323. SessionEventType.TurnStarted,
  8324. { turnNumber: 2, input: "next real prompt" },
  8325. { turnId: "turn-2", timestampMs: 1_700_000_005_000 },
  8326. );
  8327. const afterRealTurn = runAll(log.events).projection.getSnapshot();
  8328. const hookRows = afterRealTurn.rows.window.filter((row) => row.kind === "hookInvocation");
  8329. expect(hookRows).toHaveLength(1);
  8330. expect(hookRows[0]).toMatchObject({
  8331. hookEventName: "SessionStart",
  8332. turnId: "turn-2",
  8333. executions: [expect.objectContaining({ didExecute: true })],
  8334. });
  8335. });
  8336. it("HK17 keeps a SessionStart summary pending when a compact turn is the last turn", () => {
  8337. // 只有 /compact 且无后续输入:摘要保持 pending,不挂 compact marker,也不制造
  8338. // 可见时间线内容(session-hooks:* synthetic turn 禁止)。
  8339. const log = new EventLog();
  8340. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  8341. log.push(
  8342. SessionEventType.HookRunStarted,
  8343. {
  8344. descriptor,
  8345. hookEventName: "SessionStart",
  8346. hookIndex: 0,
  8347. hookCount: 1,
  8348. hookInvocationId: "startup-hook",
  8349. hookRunId: "startup-run",
  8350. startedAt: 1_700_000_002_000,
  8351. },
  8352. { turnId: "turn-1", timestampMs: 1_700_000_002_000 },
  8353. );
  8354. log.push(
  8355. SessionEventType.HookRunCompleted,
  8356. {
  8357. descriptor,
  8358. durationMs: 10,
  8359. hookEventName: "SessionStart",
  8360. hookIndex: 0,
  8361. hookCount: 1,
  8362. hookInvocationId: "startup-hook",
  8363. hookRunId: "startup-run",
  8364. outcome: "success",
  8365. startedAt: 1_700_000_002_000,
  8366. },
  8367. { turnId: "turn-1", timestampMs: 1_700_000_002_010 },
  8368. );
  8369. log.push(
  8370. SessionEventType.TurnStarted,
  8371. { turnNumber: 1, input: "/compact", inputVisibility: "model-only" },
  8372. { turnId: "turn-1", timestampMs: 1_700_000_003_000 },
  8373. );
  8374. log.push(
  8375. SessionEventType.TurnComplete,
  8376. {
  8377. response: "compacted",
  8378. tokenCount: 1,
  8379. toolCallCount: 0,
  8380. duration: 1_000,
  8381. resultType: "success",
  8382. },
  8383. { turnId: "turn-1", timestampMs: 1_700_000_004_000 },
  8384. );
  8385. const snapshot = runAll(log.events).projection.getSnapshot();
  8386. expect(snapshot.rows.window.filter((row) => row.kind === "hookInvocation")).toHaveLength(0);
  8387. expect(snapshot.rows.window.map((row) => row.turnId)).not.toContain("session-hooks:session-1");
  8388. });
  8389. it("HK17 keeps tool Hooks of a model-only real agent turn attached to that turn", () => {
  8390. // 回归背景(2026-08-28 review):model-only ≠ 维护 turn。background_task 通知轮
  8391. // (runtime-command-queue)、subagent_message 轮、goal continuation 轮都是
  8392. // inputVisibility="model-only" 但会真实跑工具的 agent 轮。HK17 首版把直挂 gate
  8393. // 无差别地按 currentTurnStartedModelOnly 拦截,导致这些轮的 PreToolUse/PostToolUse
  8394. // 被 pending 吞掉、错误 flush 到下一个不相关用户轮。维护 turn 排除只属于
  8395. // SessionStart;工具 Hook 必须按 event.turnId 直挂原轮,与 cold merge 对齐。
  8396. const log = new EventLog();
  8397. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8398. log.push(
  8399. SessionEventType.TurnStarted,
  8400. {
  8401. turnNumber: 1,
  8402. input: "background task completed, continue",
  8403. inputVisibility: "model-only",
  8404. },
  8405. { turnId: "turn-bg", timestampMs: 1_700_000_001_000 },
  8406. );
  8407. log.push(
  8408. SessionEventType.HookRunStarted,
  8409. {
  8410. descriptor,
  8411. hookEventName: "PreToolUse",
  8412. hookIndex: 0,
  8413. hookCount: 1,
  8414. hookInvocationId: "bg-tool-hook",
  8415. hookRunId: "bg-tool-run",
  8416. startedAt: 1_700_000_002_000,
  8417. toolCallId: "tool-bg",
  8418. toolName: "Write",
  8419. },
  8420. { turnId: "turn-bg", timestampMs: 1_700_000_002_000 },
  8421. );
  8422. log.push(
  8423. SessionEventType.HookRunCompleted,
  8424. {
  8425. descriptor,
  8426. durationMs: 15,
  8427. hookEventName: "PreToolUse",
  8428. hookIndex: 0,
  8429. hookCount: 1,
  8430. hookInvocationId: "bg-tool-hook",
  8431. hookRunId: "bg-tool-run",
  8432. outcome: "success",
  8433. startedAt: 1_700_000_002_000,
  8434. toolCallId: "tool-bg",
  8435. toolName: "Write",
  8436. },
  8437. { turnId: "turn-bg", timestampMs: 1_700_000_002_015 },
  8438. );
  8439. log.push(
  8440. SessionEventType.TurnStarted,
  8441. { turnNumber: 2, input: "unrelated user question" },
  8442. { turnId: "turn-user", timestampMs: 1_700_000_003_000 },
  8443. );
  8444. const hookRows = runAll(log.events)
  8445. .projection.getSnapshot()
  8446. .rows.window.filter((row) => row.kind === "hookInvocation");
  8447. expect(hookRows).toHaveLength(1);
  8448. // 工具 Hook 留在 model-only 真实 agent 轮,不被 pending 迁移到用户轮。
  8449. expect(hookRows[0]).toMatchObject({
  8450. hookEventName: "PreToolUse",
  8451. turnId: "turn-bg",
  8452. anchorToolCallId: "tool-bg",
  8453. executions: [expect.objectContaining({ didExecute: true })],
  8454. });
  8455. });
  8456. it.each([
  8457. {
  8458. caseName: "TurnError",
  8459. terminal: (log: EventLog, turnId: string, at: number) =>
  8460. log.push(
  8461. SessionEventType.TurnError,
  8462. { error: { type: "ProviderError", message: "rate limited" }, turnPhase: "model" },
  8463. { turnId, timestampMs: at },
  8464. ),
  8465. },
  8466. {
  8467. caseName: "TurnComplete(cancelled)",
  8468. terminal: (log: EventLog, turnId: string, at: number) =>
  8469. log.push(
  8470. SessionEventType.TurnComplete,
  8471. {
  8472. response: "",
  8473. tokenCount: 0,
  8474. toolCallCount: 0,
  8475. duration: 100,
  8476. resultType: "cancelled",
  8477. },
  8478. { turnId, timestampMs: at },
  8479. ),
  8480. },
  8481. ])(
  8482. "HK17 keeps a pending SessionStart summary off an abnormally terminated model-only turn ($caseName)",
  8483. ({ terminal }) => {
  8484. // SG-01:currentTurnId / currentTurnStartedModelOnly 是 reducer 内部侧表,
  8485. // 异常终态是最容易遗漏的生命周期边界。TurnError 非 controlOnly 路径不清侧表、
  8486. // TurnComplete(cancelled) 清侧表,两条收口路径必须等价:pending SessionStart
  8487. // 不泄漏到异常 turn、不直挂死 turn、只归位下一条真实用户 turn。
  8488. const sessionStartLifecycle = (log: EventLog, invocationId: string, at: number) => {
  8489. log.push(
  8490. SessionEventType.HookRunStarted,
  8491. {
  8492. descriptor,
  8493. hookEventName: "SessionStart",
  8494. hookIndex: 0,
  8495. hookCount: 1,
  8496. hookInvocationId: invocationId,
  8497. hookRunId: `${invocationId}-run`,
  8498. startedAt: at,
  8499. },
  8500. { turnId: "turn-mt", timestampMs: at },
  8501. );
  8502. log.push(
  8503. SessionEventType.HookRunCompleted,
  8504. {
  8505. descriptor,
  8506. durationMs: 5,
  8507. hookEventName: "SessionStart",
  8508. hookIndex: 0,
  8509. hookCount: 1,
  8510. hookInvocationId: invocationId,
  8511. hookRunId: `${invocationId}-run`,
  8512. outcome: "success",
  8513. startedAt: at,
  8514. },
  8515. { turnId: "turn-mt", timestampMs: at + 5 },
  8516. );
  8517. };
  8518. const log = new EventLog();
  8519. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  8520. // model-only goal continuation 轮(executionKind 缺省为 agent,异常走非 controlOnly)。
  8521. log.push(
  8522. SessionEventType.TurnStarted,
  8523. { turnNumber: 1, input: "continue goal", inputVisibility: "model-only" },
  8524. { turnId: "turn-mt", timestampMs: 1_700_000_001_000 },
  8525. );
  8526. sessionStartLifecycle(log, "startup-hook", 1_700_000_002_000);
  8527. terminal(log, "turn-mt", 1_700_000_003_000);
  8528. // 异常收口瞬间:pending 保留,不挂异常 turn,也不泄漏成可见 row。
  8529. const afterTerminal = runAll(log.events).projection.getSnapshot();
  8530. expect(afterTerminal.rows.window.filter((row) => row.kind === "hookInvocation")).toHaveLength(
  8531. 0,
  8532. );
  8533. expect(afterTerminal.rows.window.map((row) => row.turnId)).not.toContain(
  8534. "session-hooks:session-1",
  8535. );
  8536. // 终态后紧接的下一个 SessionStart(resume epoch)同样必须 pending,
  8537. // 不得直挂已终止的死 turn。
  8538. sessionStartLifecycle(log, "resume-hook", 1_700_000_004_000);
  8539. const afterResumeHook = runAll(log.events).projection.getSnapshot();
  8540. expect(
  8541. afterResumeHook.rows.window.filter((row) => row.kind === "hookInvocation"),
  8542. ).toHaveLength(0);
  8543. // 下一条真实用户 turn 收口两条 pending 摘要,且只出现在该轮。
  8544. log.push(
  8545. SessionEventType.TurnStarted,
  8546. { turnNumber: 2, input: "real question" },
  8547. { turnId: "turn-real", timestampMs: 1_700_000_005_000 },
  8548. );
  8549. const finalRows = runAll(log.events)
  8550. .projection.getSnapshot()
  8551. .rows.window.filter((row) => row.kind === "hookInvocation");
  8552. expect(finalRows.map((row) => [row.hookInvocationId, row.turnId])).toEqual([
  8553. ["startup-hook", "turn-real"],
  8554. ["resume-hook", "turn-real"],
  8555. ]);
  8556. expect(finalRows.map((row) => row.turnId)).not.toContain("turn-mt");
  8557. },
  8558. );
  8559. it.each([
  8560. [SessionEventType.HookRunCompleted, { durationMs: 20, outcome: "success" }],
  8561. [SessionEventType.HookRunFailed, { durationMs: 20, outcome: "failed" }],
  8562. ] as const)(
  8563. "HK14 ignores late %s after its Hook branch was rewound",
  8564. (terminalType, terminal) => {
  8565. const log = new EventLog();
  8566. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8567. log.push(
  8568. SessionEventType.TurnStarted,
  8569. { turnNumber: 1, input: "run", messageId: "user-1" },
  8570. { turnId: "turn-1" },
  8571. );
  8572. log.push(
  8573. SessionEventType.ModelStreaming,
  8574. { kind: "text_start", delta: "", done: false, assistantMessageId: "assistant-1" },
  8575. { turnId: "turn-1" },
  8576. );
  8577. log.push(
  8578. SessionEventType.HookRunStarted,
  8579. {
  8580. descriptor,
  8581. hookEventName: "PreToolUse",
  8582. hookIndex: 0,
  8583. hookCount: 1,
  8584. hookInvocationId: "rewound-hook",
  8585. hookRunId: "rewound-run",
  8586. startedAt: 1_700_000_003_000,
  8587. },
  8588. { turnId: "turn-1", timestampMs: 1_700_000_003_000 },
  8589. );
  8590. log.push(SessionEventType.RewindTriggered, {
  8591. targetMessageId: "assistant-1",
  8592. scope: "conversation",
  8593. createdMessageId: "rewind-notice",
  8594. });
  8595. log.push(
  8596. terminalType,
  8597. {
  8598. descriptor,
  8599. hookEventName: "PreToolUse",
  8600. hookIndex: 0,
  8601. hookCount: 1,
  8602. hookInvocationId: "rewound-hook",
  8603. hookRunId: "rewound-run",
  8604. startedAt: 1_700_000_003_000,
  8605. ...terminal,
  8606. },
  8607. { turnId: "turn-1", timestampMs: 1_700_000_003_020 },
  8608. );
  8609. const { deltasPerEvent, projection } = runAll(log.events);
  8610. expect(deltasPerEvent[4]).toContainEqual({
  8611. op: "row.removed",
  8612. fromRowId: expect.any(Number),
  8613. });
  8614. expect(
  8615. projection
  8616. .getSnapshot()
  8617. .rows.window.some(
  8618. (row) => row.kind === "hookInvocation" && row.hookInvocationId === "rewound-hook",
  8619. ),
  8620. ).toBe(false);
  8621. expect(deltasPerEvent[5]).not.toContainEqual(
  8622. expect.objectContaining({
  8623. op: "row.appended",
  8624. row: expect.objectContaining({ hookInvocationId: "rewound-hook" }),
  8625. }),
  8626. );
  8627. },
  8628. );
  8629. it("projects workspace Hook review only as Settings-centered pending interaction", () => {
  8630. const log = new EventLog();
  8631. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8632. const request = {
  8633. kind: "workspaceHookReview",
  8634. reviewFlowId: "flow-1",
  8635. generation: 1,
  8636. interactionId: "interaction-1",
  8637. sessionId: "session-1",
  8638. taskId: "session-1",
  8639. runId: "run-1",
  8640. workspaceIdentity: "local:/workspace",
  8641. workspaceLabel: "workspace",
  8642. bundleDigest: "a".repeat(64),
  8643. createdAt: 1_700_000_001_000,
  8644. deadlineAt: 1_700_000_601_000,
  8645. sourceFiles: [
  8646. {
  8647. path: "/workspace/.zcode/config.json",
  8648. displayPath: ".zcode/config.json",
  8649. editable: true,
  8650. },
  8651. ],
  8652. summary: { eventCount: 1, hookCount: 1, pendingCount: 1 },
  8653. items: [
  8654. {
  8655. reviewItemId: "item-0",
  8656. event: "SessionStart",
  8657. matcher: "startup",
  8658. type: "command",
  8659. displayName: "SessionStart · startup",
  8660. displayCommand: "echo project",
  8661. sourcePath: ".zcode/config.json",
  8662. resolvedTimeoutMs: 60_000,
  8663. resolvedMaxOutputBytes: 32_768,
  8664. executionMode: "foreground",
  8665. configuredEnabled: true,
  8666. editable: true,
  8667. trustState: "pending_trust",
  8668. },
  8669. ],
  8670. warningCode: "workspace_hooks_execute_code",
  8671. } as const;
  8672. log.push(SessionEventType.WorkspaceHookReviewRequested, { request });
  8673. const { projection } = runAll(log.events);
  8674. expect(projection.getSnapshot().pendingInteractions).toEqual([
  8675. {
  8676. interactionId: "interaction-1",
  8677. kind: "workspaceHookReview",
  8678. anchorRowId: null,
  8679. createdAt: request.createdAt,
  8680. payload: request,
  8681. },
  8682. ]);
  8683. log.push(SessionEventType.WorkspaceHookReviewSettled, {
  8684. interactionId: "interaction-1",
  8685. state: "resolved",
  8686. });
  8687. projection.applyEvent(log.events.at(-1)!);
  8688. expect(projection.getSnapshot().pendingInteractions).toEqual([]);
  8689. });
  8690. it("superseded review generation removes only the stale interaction", () => {
  8691. const log = new EventLog();
  8692. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8693. const base = {
  8694. kind: "workspaceHookReview",
  8695. reviewFlowId: "flow-1",
  8696. sessionId: "session-1",
  8697. taskId: "session-1",
  8698. runId: "run-1",
  8699. workspaceIdentity: "local:/workspace",
  8700. workspaceLabel: "workspace",
  8701. createdAt: 1_700_000_001_000,
  8702. deadlineAt: 1_700_000_601_000,
  8703. sourceFiles: [],
  8704. summary: { eventCount: 0, hookCount: 0, pendingCount: 0 },
  8705. items: [],
  8706. warningCode: "workspace_hooks_execute_code",
  8707. } as const;
  8708. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  8709. request: {
  8710. ...base,
  8711. generation: 1,
  8712. interactionId: "interaction-1",
  8713. bundleDigest: "a".repeat(64),
  8714. },
  8715. });
  8716. log.push(SessionEventType.WorkspaceHookReviewSuperseded, {
  8717. interactionId: "interaction-1",
  8718. supersededByInteractionId: "interaction-2",
  8719. });
  8720. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  8721. request: {
  8722. ...base,
  8723. generation: 2,
  8724. interactionId: "interaction-2",
  8725. bundleDigest: "b".repeat(64),
  8726. },
  8727. });
  8728. const { projection } = runAll(log.events);
  8729. expect(projection.getSnapshot().pendingInteractions.map((item) => item.interactionId)).toEqual([
  8730. "interaction-2",
  8731. ]);
  8732. });
  8733. it("treats SessionResumed and the next requested review as a new runtime authority", () => {
  8734. const log = new EventLog();
  8735. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8736. const base = {
  8737. kind: "workspaceHookReview",
  8738. sessionId: "session-1",
  8739. taskId: "session-1",
  8740. runId: "run-1",
  8741. workspaceIdentity: "local:/workspace",
  8742. workspaceLabel: "workspace",
  8743. createdAt: 1_700_000_001_000,
  8744. deadlineAt: 1_700_000_601_000,
  8745. sourceFiles: [],
  8746. summary: { eventCount: 0, hookCount: 0, pendingCount: 0 },
  8747. items: [],
  8748. warningCode: "workspace_hooks_execute_code",
  8749. } as const;
  8750. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  8751. request: {
  8752. ...base,
  8753. reviewFlowId: "old-runtime-flow",
  8754. generation: 7,
  8755. interactionId: "old-runtime-interaction",
  8756. bundleDigest: "a".repeat(64),
  8757. },
  8758. });
  8759. log.push(SessionEventType.SessionResumed, {});
  8760. const { projection } = runAll(log.events);
  8761. expect(projection.getSnapshot().pendingInteractions).toEqual([]);
  8762. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  8763. request: {
  8764. ...base,
  8765. reviewFlowId: "new-runtime-flow",
  8766. generation: 1,
  8767. interactionId: "new-runtime-interaction",
  8768. bundleDigest: "b".repeat(64),
  8769. createdAt: 1_700_000_002_000,
  8770. deadlineAt: 1_700_000_602_000,
  8771. },
  8772. });
  8773. projection.applyEvent(log.events.at(-1)!);
  8774. expect(projection.getSnapshot().pendingInteractions.map((item) => item.interactionId)).toEqual([
  8775. "new-runtime-interaction",
  8776. ]);
  8777. });
  8778. it("ignores a different review flow until SessionResumed establishes a new runtime epoch", () => {
  8779. const log = new EventLog();
  8780. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8781. const base = {
  8782. kind: "workspaceHookReview",
  8783. generation: 1,
  8784. sessionId: "session-1",
  8785. taskId: "session-1",
  8786. runId: "run-1",
  8787. workspaceIdentity: "local:/workspace",
  8788. workspaceLabel: "workspace",
  8789. createdAt: 1_700_000_001_000,
  8790. deadlineAt: 1_700_000_601_000,
  8791. sourceFiles: [],
  8792. summary: { eventCount: 0, hookCount: 0, pendingCount: 0 },
  8793. items: [],
  8794. warningCode: "workspace_hooks_execute_code",
  8795. } as const;
  8796. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  8797. request: {
  8798. ...base,
  8799. reviewFlowId: "old-flow",
  8800. interactionId: "old-interaction",
  8801. bundleDigest: "a".repeat(64),
  8802. },
  8803. });
  8804. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  8805. request: {
  8806. ...base,
  8807. reviewFlowId: "new-flow",
  8808. interactionId: "new-interaction",
  8809. bundleDigest: "b".repeat(64),
  8810. createdAt: 1_700_000_002_000,
  8811. deadlineAt: 1_700_000_602_000,
  8812. },
  8813. });
  8814. const { projection } = runAll(log.events);
  8815. expect(projection.getSnapshot().pendingInteractions.map((item) => item.interactionId)).toEqual([
  8816. "old-interaction",
  8817. ]);
  8818. });
  8819. it("ignores equal-generation workspace Hook review requests with a conflicting interaction", () => {
  8820. const log = new EventLog();
  8821. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8822. const base = {
  8823. kind: "workspaceHookReview",
  8824. reviewFlowId: "flow-1",
  8825. generation: 3,
  8826. sessionId: "session-1",
  8827. taskId: "session-1",
  8828. runId: "run-1",
  8829. workspaceIdentity: "local:/workspace",
  8830. workspaceLabel: "workspace",
  8831. createdAt: 1_700_000_001_000,
  8832. deadlineAt: 1_700_000_601_000,
  8833. sourceFiles: [],
  8834. summary: { eventCount: 0, hookCount: 0, pendingCount: 0 },
  8835. items: [],
  8836. warningCode: "workspace_hooks_execute_code",
  8837. } as const;
  8838. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  8839. request: {
  8840. ...base,
  8841. interactionId: "interaction-authority",
  8842. bundleDigest: "a".repeat(64),
  8843. },
  8844. });
  8845. log.push(SessionEventType.WorkspaceHookReviewRequested, {
  8846. request: {
  8847. ...base,
  8848. interactionId: "interaction-conflict",
  8849. bundleDigest: "b".repeat(64),
  8850. },
  8851. });
  8852. const { projection } = runAll(log.events);
  8853. expect(projection.getSnapshot().pendingInteractions.map((item) => item.interactionId)).toEqual([
  8854. "interaction-authority",
  8855. ]);
  8856. });
  8857. it("does not project hidden internal or legacy lifecycle events", () => {
  8858. const log = new EventLog();
  8859. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8860. log.push(SessionEventType.HookRunStarted, {
  8861. descriptor: {
  8862. ...descriptor,
  8863. clientVisible: false,
  8864. sourceKind: "internal",
  8865. },
  8866. hookEventName: "SessionStart",
  8867. hookIndex: 0,
  8868. hookCount: 0,
  8869. hookInvocationId: "mailbox-hook",
  8870. hookRunId: "mailbox-run",
  8871. startedAt: 1_700_000_002_000,
  8872. });
  8873. log.push(SessionEventType.HookRunStarted, {
  8874. hookEventName: "SessionStart",
  8875. hookIndex: 0,
  8876. hookRunId: "legacy-run",
  8877. });
  8878. const { projection } = runAll(log.events);
  8879. expect(projection.getSnapshot().rows.window).not.toContainEqual(
  8880. expect.objectContaining({ kind: "hookInvocation" }),
  8881. );
  8882. });
  8883. });
  8884. describe("软门禁(D2): workspaceHookAdmission snapshot 投影", () => {
  8885. it("WorkspaceHookAdmissionUpdated pendingCount>0 写入 snapshot.workspaceHookAdmission", () => {
  8886. const log = new EventLog();
  8887. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8888. log.push(SessionEventType.WorkspaceHookAdmissionUpdated, {
  8889. pendingCount: 2,
  8890. bundleDigest: "a".repeat(64),
  8891. workspaceIdentity: "local:/workspace",
  8892. });
  8893. const { projection } = runAll(log.events);
  8894. expect(projection.getSnapshot().workspaceHookAdmission).toEqual({
  8895. pendingCount: 2,
  8896. bundleDigest: "a".repeat(64),
  8897. workspaceIdentity: "local:/workspace",
  8898. });
  8899. });
  8900. it("WorkspaceHookAdmissionUpdated pendingCount===0 → 置 null(提示条消失)", () => {
  8901. const log = new EventLog();
  8902. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8903. // 先有 pending
  8904. log.push(SessionEventType.WorkspaceHookAdmissionUpdated, {
  8905. pendingCount: 1,
  8906. bundleDigest: "a".repeat(64),
  8907. });
  8908. // settle 后清零
  8909. log.push(SessionEventType.WorkspaceHookAdmissionUpdated, {
  8910. pendingCount: 0,
  8911. bundleDigest: "a".repeat(64),
  8912. });
  8913. const { projection } = runAll(log.events);
  8914. expect(projection.getSnapshot().workspaceHookAdmission).toBeNull();
  8915. });
  8916. it("SessionResumed epoch 清理 → workspaceHookAdmission 置 null(resume 后 activate 重新上报)", () => {
  8917. const log = new EventLog();
  8918. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8919. log.push(SessionEventType.WorkspaceHookAdmissionUpdated, {
  8920. pendingCount: 3,
  8921. bundleDigest: "a".repeat(64),
  8922. workspaceIdentity: "local:/workspace",
  8923. });
  8924. log.push(SessionEventType.SessionResumed, {});
  8925. const { projection } = runAll(log.events);
  8926. expect(projection.getSnapshot().workspaceHookAdmission).toBeNull();
  8927. });
  8928. it("workspaceIdentity 可选:缺失时 snapshot 字段不含 workspaceIdentity", () => {
  8929. const log = new EventLog();
  8930. log.push(SessionEventType.SessionCreated, { mode: "default" });
  8931. log.push(SessionEventType.WorkspaceHookAdmissionUpdated, {
  8932. pendingCount: 1,
  8933. bundleDigest: "b".repeat(64),
  8934. });
  8935. const { projection } = runAll(log.events);
  8936. expect(projection.getSnapshot().workspaceHookAdmission).toEqual({
  8937. pendingCount: 1,
  8938. bundleDigest: "b".repeat(64),
  8939. });
  8940. expect(projection.getSnapshot().workspaceHookAdmission).not.toHaveProperty("workspaceIdentity");
  8941. });
  8942. });
  8943. // ── CreateWorkflow 运行确认(docs/dynamic-workflow/launch.md)──
  8944. describe("workflow 运行确认的 ask 预览", () => {
  8945. const causalityGraph = {
  8946. steps: [
  8947. {
  8948. id: "ask#1",
  8949. kind: "ask" as const,
  8950. label: "a",
  8951. line: 2,
  8952. column: 11,
  8953. lane: "actor#1",
  8954. },
  8955. ],
  8956. lanes: [{ id: "actor#1", name: "a" }],
  8957. // 第二层是子代理导向:每阶段一张参与者卡 + 交接边(docs/dynamic-workflow/presentation.md)。
  8958. participants: [
  8959. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] },
  8960. ],
  8961. handoffs: [],
  8962. sink: ["ask#1"],
  8963. };
  8964. function permissionRequestedLog(display?: unknown, toolName = "CreateWorkflow"): EventLog {
  8965. const turnId = "turn-1";
  8966. const log = new EventLog();
  8967. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  8968. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run it" }, { turnId });
  8969. log.push(
  8970. SessionEventType.ToolCallScheduled,
  8971. {
  8972. toolCallId: "tc-1",
  8973. toolName,
  8974. input: { script: "return 1;" },
  8975. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  8976. },
  8977. { turnId },
  8978. );
  8979. log.push(
  8980. SessionEventType.PermissionRequested,
  8981. {
  8982. requestId: "req-1",
  8983. toolCallId: "tc-1",
  8984. toolName,
  8985. riskLevel: "low",
  8986. reason: "createWorkflow.runConfirmation: user must confirm running the analyzed script",
  8987. input: { script: "return 1;" },
  8988. // CreateWorkflow 自 2026-09-11(第 7 轮)起声明会话作用域的免确认;Bash 用例只借
  8989. // 这条日志的形状,策略对它无意义(投影不看工具声明,只看事件上的策略)。
  8990. optionsPolicy: "session-always-allow",
  8991. ...(display === undefined ? {} : { display }),
  8992. },
  8993. { turnId },
  8994. );
  8995. return log;
  8996. }
  8997. it("把事件上的 display 投到 pendingInteraction,并按 optionsPolicy 把 always allow 换成会话免确认", () => {
  8998. const log = permissionRequestedLog({
  8999. kind: "create_workflow",
  9000. ok: true,
  9001. errorCount: 0,
  9002. diagnostics: [],
  9003. causalityGraph,
  9004. });
  9005. const snapshot = runAll(log.events).projection.getSnapshot();
  9006. const toolRow = snapshot.rows.window.find((row) => row.kind === "toolCall");
  9007. expect(toolRow).toMatchObject({
  9008. status: "pendingApproval",
  9009. approvalInteractionId: "req-1",
  9010. });
  9011. expect(snapshot.pendingInteractions).toHaveLength(1);
  9012. const payload = snapshot.pendingInteractions[0]?.payload;
  9013. expect(payload).toMatchObject({
  9014. kind: "permission",
  9015. display: { kind: "create_workflow", ok: true, causalityGraph },
  9016. });
  9017. // 产品裁决:项目级 always allow 被 optionsPolicy 裁掉,第 7 轮换成会话作用域的
  9018. // 免确认;第 4 轮在 v4 追加 Refine(拒绝并附修改意见),列表 = Run / Session / Deny / Refine。
  9019. expect(payload?.kind === "permission" && payload.options).toHaveLength(4);
  9020. expect(
  9021. payload?.kind === "permission" && payload.options.map((option) => option.optionId),
  9022. ).toEqual(["allowOnce", "allowSession", "deny", "workflowRefine"]);
  9023. const sessionOption =
  9024. payload?.kind === "permission"
  9025. ? payload.options.find((option) => option.optionId === "allowSession")
  9026. : undefined;
  9027. // wire 上的 kind 是闭集:会话选项映为 allowAlways(GUI 按 name 本地化);optionId 原样,
  9028. // broker 靠它精确命中。response 不带 permissionUpdates(strict schema,见 spec 第 7 轮)。
  9029. expect(sessionOption).toMatchObject({
  9030. kind: "allowAlways",
  9031. label: "Always allow in this session",
  9032. response: { decision: "allow" },
  9033. });
  9034. expect(sessionOption?.response).not.toHaveProperty("permissionUpdates");
  9035. expect(conversationSnapshotSchema.safeParse(snapshot).success).toBe(true);
  9036. const refineOption =
  9037. payload?.kind === "permission"
  9038. ? payload.options.find((option) => option.optionId === "workflowRefine")
  9039. : undefined;
  9040. // 静态 response 是普通 deny:不认识该选项的消费面(bot 直出、无 freeText 应答)
  9041. // 退化为拒绝;反馈升级只发生在 interaction-broker 的 freeText 特判。
  9042. expect(refineOption).toMatchObject({
  9043. kind: "custom",
  9044. label: "Refine",
  9045. response: { decision: "deny" },
  9046. });
  9047. });
  9048. it("Refine 选项只属于 CreateWorkflow:其他工具的权限 ask 不投放", () => {
  9049. const snapshot = runAll(
  9050. permissionRequestedLog(undefined, "Bash").events,
  9051. ).projection.getSnapshot();
  9052. const payload = snapshot.pendingInteractions[0]?.payload;
  9053. expect(payload?.kind).toBe("permission");
  9054. expect(
  9055. payload?.kind === "permission" && payload.options.map((option) => option.optionId),
  9056. ).toEqual(["allowOnce", "allowSession", "deny"]);
  9057. });
  9058. it("no-always-allow 策略(SaveWorkflow)仍只留 Run / Deny", () => {
  9059. const turnId = "turn-1";
  9060. const log = new EventLog();
  9061. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  9062. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "save it" }, { turnId });
  9063. log.push(
  9064. SessionEventType.PermissionRequested,
  9065. {
  9066. requestId: "req-1",
  9067. toolCallId: "tc-1",
  9068. toolName: "SaveWorkflow",
  9069. riskLevel: "low",
  9070. reason: "saveWorkflow.confirmation",
  9071. input: { name: "x", script: "return 1;" },
  9072. optionsPolicy: "no-always-allow",
  9073. },
  9074. { turnId },
  9075. );
  9076. const payload = runAll(log.events).projection.getSnapshot().pendingInteractions[0]?.payload;
  9077. expect(
  9078. payload?.kind === "permission" && payload.options.map((option) => option.optionId),
  9079. ).toEqual(["allowOnce", "deny"]);
  9080. });
  9081. it("没有 display 时保持纯文本 ask,pendingApproval 行为不变", () => {
  9082. const snapshot = runAll(permissionRequestedLog().events).projection.getSnapshot();
  9083. const payload = snapshot.pendingInteractions[0]?.payload;
  9084. expect(payload?.kind).toBe("permission");
  9085. expect(payload && "display" in payload).toBe(false);
  9086. expect(snapshot.rows.window.find((row) => row.kind === "toolCall")).toMatchObject({
  9087. status: "pendingApproval",
  9088. });
  9089. });
  9090. it("协议无法承载的 display kind 不进 ask 载荷", () => {
  9091. // file_diff 不在 v4 display 联合里;直接透传会让快照 schema 解析失败。
  9092. const log = permissionRequestedLog({
  9093. kind: "file_diff",
  9094. filePath: "/workspace/a.ts",
  9095. additions: 1,
  9096. deletions: 0,
  9097. structuredPatch: [],
  9098. });
  9099. const snapshot = runAll(log.events).projection.getSnapshot();
  9100. const payload = snapshot.pendingInteractions[0]?.payload;
  9101. expect(payload && "display" in payload).toBe(false);
  9102. expect(conversationSnapshotSchema.safeParse(snapshot).success).toBe(true);
  9103. });
  9104. });
  9105. // ── dwf 实时运行态:引擎事件 → 会话事件 → workflowRuns 状态键 ──
  9106. // 见 docs/dynamic-workflow/presentation.md「The run state the pane draws」「workflowRuns 形状与界」「终态权威 patch」。
  9107. describe("ProductProjection workflowRuns(dwf 进度投影)", () => {
  9108. const RUN_ID = "dwfrun-1";
  9109. function progress(
  9110. log: EventLog,
  9111. eventType: string,
  9112. payload: Record<string, unknown>,
  9113. extra: Record<string, unknown> = {},
  9114. ): SessionEvent {
  9115. return log.push(SessionEventType.DynamicWorkflowRunProgress, {
  9116. runId: RUN_ID,
  9117. toolCallId: "tc-1",
  9118. // sequence 是 journal sequence(appendEvent 从 0 起单调分配)。
  9119. sequence: (progressSequence[RUN_ID] = (progressSequence[RUN_ID] ?? -1) + 1),
  9120. eventType,
  9121. payload,
  9122. ...extra,
  9123. });
  9124. }
  9125. const progressSequence: Record<string, number> = {};
  9126. function startedLog(caps: Record<string, unknown> = { maxConcurrency: 4 }): EventLog {
  9127. progressSequence[RUN_ID] = -1;
  9128. const log = new EventLog();
  9129. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  9130. progress(log, "run-started", { runId: RUN_ID, caps });
  9131. return log;
  9132. }
  9133. function runsOf(log: EventLog) {
  9134. return runAll(log.events).projection.getSnapshot().workflowRuns;
  9135. }
  9136. it("run-started 建条目:状态 running,用量归零,快照过 strict schema", () => {
  9137. const log = startedLog({ maxConcurrency: 2 });
  9138. const snapshot = runAll(log.events).projection.getSnapshot();
  9139. expect(snapshot.workflowRuns).toMatchObject({
  9140. revision: 1,
  9141. runs: [
  9142. {
  9143. runId: RUN_ID,
  9144. toolCallId: "tc-1",
  9145. status: "running",
  9146. usage: { spentTokens: 0, nodesUsed: 0 },
  9147. actors: [],
  9148. nodes: [],
  9149. lastEventSequence: 0,
  9150. },
  9151. ],
  9152. });
  9153. expect(conversationSnapshotSchema.safeParse(snapshot).success).toBe(true);
  9154. });
  9155. it("节点相位按 (siteId, ordinal) upsert,不新增条目", () => {
  9156. const log = startedLog();
  9157. progress(log, "node-queued", {
  9158. instance: { siteId: "ask#1", ordinal: 1 },
  9159. kind: "ask",
  9160. actor: { siteId: "actor#1", ordinal: 1 },
  9161. actorSeq: 1,
  9162. });
  9163. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9164. progress(log, "node-repairing", {
  9165. instance: { siteId: "ask#1", ordinal: 1 },
  9166. attempt: 1,
  9167. violations: [],
  9168. });
  9169. progress(log, "node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" });
  9170. const runs = runsOf(log);
  9171. expect(runs?.runs[0]?.nodes).toEqual([
  9172. {
  9173. siteId: "ask#1",
  9174. ordinal: 1,
  9175. kind: "ask",
  9176. phase: "settled",
  9177. outcome: "ok",
  9178. actorSiteId: "actor#1",
  9179. actorOrdinal: 1,
  9180. },
  9181. ]);
  9182. });
  9183. it("cached 命中只发 node-settled(无 node-queued),kind 因此缺省而条目仍成立", () => {
  9184. const log = startedLog();
  9185. progress(log, "node-settled", {
  9186. instance: { siteId: "world-read#1", ordinal: 1 },
  9187. outcome: "ok",
  9188. cached: true,
  9189. });
  9190. expect(runsOf(log)?.runs[0]?.nodes).toEqual([
  9191. { siteId: "world-read#1", ordinal: 1, phase: "settled", outcome: "ok", cached: true },
  9192. ]);
  9193. });
  9194. it("actor-created 建 actor,其状态由自己的节点派生(三态:waiting / running / completed,决策 39)", () => {
  9195. const log = startedLog();
  9196. progress(
  9197. log,
  9198. "actor-created",
  9199. { actor: { siteId: "actor#1", ordinal: 1 }, name: "planner" },
  9200. { actorSessionId: "sess_dwf-1-actor.1" },
  9201. );
  9202. expect(runsOf(log)?.runs[0]?.actors).toEqual([
  9203. {
  9204. siteId: "actor#1",
  9205. ordinal: 1,
  9206. name: "planner",
  9207. sessionId: "sess_dwf-1-actor.1",
  9208. // 尚无节点且 run 未终态 → waiting("还没派到活"),不是 completed。
  9209. status: "waiting",
  9210. },
  9211. ]);
  9212. progress(log, "node-queued", {
  9213. instance: { siteId: "ask#1", ordinal: 1 },
  9214. kind: "ask",
  9215. actor: { siteId: "actor#1", ordinal: 1 },
  9216. });
  9217. // dispatched 只是会话就绪、请求尚未准入(docs/dynamic-workflow/concurrency.md「Protocol state」):仍是 waiting。
  9218. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9219. expect(runsOf(log)?.runs[0]?.actors[0]?.status).toBe("waiting");
  9220. // 模型请求真的发出去了 → running。
  9221. progress(log, "node-executing", { instance: { siteId: "ask#1", ordinal: 1 } });
  9222. expect(runsOf(log)?.runs[0]?.actors[0]?.status).toBe("running");
  9223. progress(log, "node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" });
  9224. expect(runsOf(log)?.runs[0]?.actors[0]?.status).toBe("completed");
  9225. });
  9226. it("用量:spentTokens 直接取 usage-updated 载荷,nodesUsed 按实例首次派发计数", () => {
  9227. // docs/dynamic-workflow/authoring.md:事件自带已花总量(不再是剩余量 + 派生字段),
  9228. // 步数由派发事件计数(不再从上限反算——没有上限了)。同一实例重复派发不重复计数。
  9229. const log = startedLog({ maxConcurrency: 4 });
  9230. progress(log, "usage-updated", { spentTokens: 1_234 });
  9231. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9232. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9233. progress(log, "node-dispatched", { instance: { siteId: "ask#2", ordinal: 1 } });
  9234. expect(runsOf(log)?.runs[0]?.usage).toEqual({
  9235. spentTokens: 1_234,
  9236. nodesUsed: 2,
  9237. });
  9238. });
  9239. /**
  9240. * 终态事件产**一条** `workflowRun.updated`,把这条 run 的结算事实(status / error)一次落地。
  9241. *
  9242. * 这里刻意不再断言「终态 patch 是整键替换、丢光中间态也能收口」:改成键级增量之后,丢失的
  9243. * 中间 op 不再被下一条事件顺带补回来——那份自愈让位给了帧的 seq 连续性判定与 snapshot 重同步
  9244. * (客户端 fromSeq 对不上就整份重取)。终态事实照旧在这一条 op 里,一条也没少。
  9245. */
  9246. it("run-settled 产一条该 run 的键级增量:结算事实一次落地", () => {
  9247. const log = startedLog();
  9248. progress(log, "node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" });
  9249. const settled = progress(log, "run-settled", {
  9250. status: "errored",
  9251. error: { code: "ReportCapExceeded", message: "报告条数超过上限" },
  9252. });
  9253. const { projection, deltasPerEvent } = runAll(log.events);
  9254. const terminalDeltas = deltasPerEvent[log.events.indexOf(settled)]!;
  9255. expect(terminalDeltas).toHaveLength(1);
  9256. const updated = terminalDeltas[0]!;
  9257. expect(updated.op).toBe("workflowRun.updated");
  9258. const op = updated as {
  9259. op: "workflowRun.updated";
  9260. runId: string;
  9261. revision: number;
  9262. run?: { status?: string; error?: string };
  9263. nodes?: unknown[];
  9264. };
  9265. expect(op.runId).toBe(RUN_ID);
  9266. expect(op.run).toMatchObject({ status: "errored", error: "报告条数超过上限" });
  9267. // 节点这一步没动,所以这条增量里一条节点都不带——线上的字节与**改动量**成正比。
  9268. expect(op.nodes).toBeUndefined();
  9269. expect(op.revision).toBe(projection.getSnapshot().workflowRuns?.revision);
  9270. const run = projection.getSnapshot().workflowRuns?.runs[0];
  9271. expect(run?.status).toBe("errored");
  9272. expect(run?.nodes).toHaveLength(1);
  9273. });
  9274. it("resume:同 runId 再收 run-started 时清掉上一世的 error(进程内 cancel→resume)", () => {
  9275. // run-started 分支原样展开旧条目:cancel → resume 不经重启时,run 以 running 重现
  9276. // 却还挂着上一世的结算错误——一个正在跑的 run 同时展示失败文案。
  9277. const log = startedLog();
  9278. progress(log, "run-settled", {
  9279. status: "stopped",
  9280. stopReason: "interrupted",
  9281. error: { code: "Interrupted", message: "owning process exited" },
  9282. });
  9283. progress(log, "run-started", { runId: RUN_ID, caps: { maxConcurrency: 4 } });
  9284. const runs = runsOf(log)?.runs ?? [];
  9285. expect(runs).toHaveLength(1);
  9286. expect(runs[0]).toMatchObject({ runId: RUN_ID, status: "running" });
  9287. expect(runs[0]?.error).toBeUndefined();
  9288. expect(runs[0]?.resultPreview).toBeUndefined();
  9289. });
  9290. it("revision 单调,lastEventSequence 随 journal sequence 抬升", () => {
  9291. const log = startedLog();
  9292. progress(log, "node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" });
  9293. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9294. const { snapshots } = runAll(log.events);
  9295. const revisions = snapshots
  9296. .map((snapshot) => snapshot.workflowRuns?.revision)
  9297. .filter((revision): revision is number => revision !== undefined);
  9298. expect(revisions).toEqual([1, 2, 3]);
  9299. expect(snapshots.at(-1)?.workflowRuns?.runs[0]?.lastEventSequence).toBe(2);
  9300. });
  9301. it("四个数组的界:nodes 超上限置 truncated 且不再增长,被拒实例进计数器", () => {
  9302. const rejected = 5;
  9303. const log = startedLog();
  9304. for (let ordinal = 1; ordinal <= WORKFLOW_RUNS_LIMITS.maxNodes + rejected; ordinal += 1) {
  9305. progress(log, "node-queued", { instance: { siteId: "ask#1", ordinal }, kind: "ask" });
  9306. }
  9307. const run = runsOf(log)?.runs[0];
  9308. expect(run?.nodes).toHaveLength(WORKFLOW_RUNS_LIMITS.maxNodes);
  9309. expect(run?.truncated).toBe(true);
  9310. // `truncated` 只说得出「有东西没进来」;到底少了几步要靠计数器,否则读面上的步数
  9311. // 会比真实步数小,而且小多少没人说得清。
  9312. expect(run?.usage.nodesUnlisted).toBe(rejected);
  9313. expect(run?.usage.nodesUnlistedSettled).toBeUndefined();
  9314. // 读面唯一允许的步数读法 = 表内 + 表外。
  9315. expect(workflowRunStepCounts(run!)).toEqual({
  9316. total: WORKFLOW_RUNS_LIMITS.maxNodes + rejected,
  9317. settled: 0,
  9318. });
  9319. // 已在表内的实例仍可继续更新相位(超界只拒绝**新**实例)。
  9320. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9321. expect(runsOf(log)?.runs[0]?.nodes[0]?.phase).toBe("dispatched");
  9322. // 表外实例的结算同样要数得出来:它一条节点行都没有,只能落在第二个计数器上。
  9323. progress(log, "node-settled", {
  9324. instance: { siteId: "ask#1", ordinal: WORKFLOW_RUNS_LIMITS.maxNodes + 1 },
  9325. outcome: "ok",
  9326. });
  9327. const settledRun = runsOf(log)!.runs[0]!;
  9328. expect(settledRun.usage.nodesUnlistedSettled).toBe(1);
  9329. expect(workflowRunStepCounts(settledRun)).toEqual({
  9330. total: WORKFLOW_RUNS_LIMITS.maxNodes + rejected,
  9331. settled: 1,
  9332. });
  9333. });
  9334. /**
  9335. * 一条引擎事件 → **一条**该 run 的键级增量,且只带动过的那条节点。
  9336. *
  9337. * 这一条是整次改造的验收点:旧编码在这里会重发整张表(此处 16 条节点),线上的字节因此与
  9338. * 状态大小成正比而不是与改动量成正比——O(N) 字节/事件、O(N²)/run,节点上界与宽 fan-out
  9339. * 撞界丢实例都是这笔账的下游。
  9340. */
  9341. it("一条事件只发动过的那条节点,别的 run 一个字节都不带", () => {
  9342. const log = startedLog();
  9343. for (let ordinal = 1; ordinal <= 16; ordinal += 1) {
  9344. progress(log, "node-queued", { instance: { siteId: "ask#1", ordinal }, kind: "ask" });
  9345. }
  9346. // 第二条 run:它这一步没变化,所以不该出现在增量里。
  9347. log.push(SessionEventType.DynamicWorkflowRunProgress, {
  9348. runId: "dwfrun-other",
  9349. sequence: 0,
  9350. eventType: "run-started",
  9351. payload: { runId: "dwfrun-other", caps: { maxConcurrency: 1 } },
  9352. });
  9353. const dispatched = progress(log, "node-dispatched", {
  9354. instance: { siteId: "ask#1", ordinal: 7 },
  9355. });
  9356. const { deltasPerEvent, projection } = runAll(log.events);
  9357. const deltas = deltasPerEvent[log.events.indexOf(dispatched)]!;
  9358. expect(deltas).toHaveLength(1);
  9359. const op = deltas[0] as {
  9360. op: string;
  9361. runId: string;
  9362. nodes?: { siteId: string; ordinal: number; phase: string; kind?: string }[];
  9363. run?: Record<string, unknown>;
  9364. actors?: unknown[];
  9365. };
  9366. expect(op.op).toBe("workflowRun.updated");
  9367. expect(op.runId).toBe(RUN_ID);
  9368. expect(op.nodes).toEqual([{ siteId: "ask#1", ordinal: 7, kind: "ask", phase: "dispatched" }]);
  9369. expect(op.actors).toBeUndefined();
  9370. // header 只带真的动过的键(水位与派发计数),不含 nodes/actors 之外的整表。
  9371. expect(Object.keys(op.run ?? {}).toSorted()).toEqual(["lastEventSequence", "usage"]);
  9372. // 增量应用回去之后,权威状态仍是归约本身的产物(契约:逐字节一致)。
  9373. const authoritative = projection.getSnapshot().workflowRuns!;
  9374. expect(authoritative.runs.map((run) => run.runId)).toEqual([RUN_ID, "dwfrun-other"]);
  9375. expect(authoritative.runs[0]!.nodes).toHaveLength(16);
  9376. expect(authoritative.runs[0]!.nodes[6]).toEqual({
  9377. siteId: "ask#1",
  9378. ordinal: 7,
  9379. kind: "ask",
  9380. phase: "dispatched",
  9381. });
  9382. });
  9383. it("run 被条数界淘汰时发 workflowRun.removed(只有生产者淘汰,而且必须说出来)", () => {
  9384. const log = new EventLog();
  9385. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  9386. for (let index = 0; index <= WORKFLOW_RUNS_LIMITS.maxRuns; index += 1) {
  9387. log.push(SessionEventType.DynamicWorkflowRunProgress, {
  9388. runId: `dwfrun-${index}`,
  9389. sequence: 0,
  9390. eventType: "run-started",
  9391. payload: { runId: `dwfrun-${index}`, caps: { maxConcurrency: 1 } },
  9392. });
  9393. }
  9394. const { deltasPerEvent } = runAll(log.events);
  9395. // 第 9 条 run 出生的那一条事件同时淘汰了第 1 条:淘汰先发,出生随后。
  9396. const evicting = deltasPerEvent.at(-1)!;
  9397. expect(evicting.map((delta) => delta.op)).toEqual([
  9398. "workflowRun.removed",
  9399. "workflowRun.updated",
  9400. ]);
  9401. expect((evicting[0] as { runId: string }).runId).toBe("dwfrun-0");
  9402. expect((evicting[1] as { runId: string }).runId).toBe(`dwfrun-${WORKFLOW_RUNS_LIMITS.maxRuns}`);
  9403. });
  9404. it("runs ≤ 8 且按最旧淘汰", () => {
  9405. const log = new EventLog();
  9406. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  9407. for (let index = 0; index < WORKFLOW_RUNS_LIMITS.maxRuns + 3; index += 1) {
  9408. log.push(SessionEventType.DynamicWorkflowRunProgress, {
  9409. runId: `dwfrun-${index}`,
  9410. sequence: 0,
  9411. eventType: "run-started",
  9412. payload: { runId: `dwfrun-${index}`, caps: { maxConcurrency: 1 } },
  9413. });
  9414. }
  9415. const runs = runAll(log.events).projection.getSnapshot().workflowRuns?.runs ?? [];
  9416. expect(runs).toHaveLength(WORKFLOW_RUNS_LIMITS.maxRuns);
  9417. expect(runs.map((run) => run.runId)).toEqual([
  9418. "dwfrun-3",
  9419. "dwfrun-4",
  9420. "dwfrun-5",
  9421. "dwfrun-6",
  9422. "dwfrun-7",
  9423. "dwfrun-8",
  9424. "dwfrun-9",
  9425. "dwfrun-10",
  9426. ]);
  9427. });
  9428. it("log 与 usage 事件不进图:它们没有 site id,只进事件日志", () => {
  9429. const log = startedLog();
  9430. progress(log, "log", { message: "开始" });
  9431. const run = runsOf(log)?.runs[0];
  9432. expect(run?.nodes).toEqual([]);
  9433. expect(run?.actors).toEqual([]);
  9434. // 但它仍抬升 lastEventSequence——事件日志需要知道有新内容可取。
  9435. expect(run?.lastEventSequence).toBe(1);
  9436. });
  9437. // R-10:两个 profile 的终态必须逐字节一致,所以 workflowRuns 的增量一条都不能被 profile 过滤
  9438. // 掉(`profiles.ts` 只滤 row.delta)。桌面 continuous 与手机 replayable 收到的是同一串 op。
  9439. it("键级增量不受 delivery profile 门控(记录在案的偏离)", () => {
  9440. const log = startedLog();
  9441. const dispatched = progress(log, "node-dispatched", {
  9442. instance: { siteId: "ask#1", ordinal: 1 },
  9443. });
  9444. const { deltasPerEvent } = runAll(log.events);
  9445. const deltas = deltasPerEvent[log.events.indexOf(dispatched)]!;
  9446. expect(deltas.some((delta) => delta.op === "workflowRun.updated")).toBe(true);
  9447. for (const profile of Object.values(DELIVERY_PROFILES) as DeliveryProfile[]) {
  9448. expect(filterConversationDeltasForProfile(deltas, profile)).toEqual(deltas);
  9449. }
  9450. });
  9451. it("同一 run 的重复事件幂等:内容不变不产 delta", () => {
  9452. const log = startedLog();
  9453. progress(log, "node-settled", { instance: { siteId: "ask#1", ordinal: 1 }, outcome: "ok" });
  9454. const { projection } = runAll(log.events);
  9455. const before = projection.getSnapshot().workflowRuns?.revision;
  9456. // 同一条事件重放(同 sequence、同内容)。
  9457. const replay = log.events.at(-1)!;
  9458. expect(projection.applyEvent(replay)).toEqual([]);
  9459. expect(projection.getSnapshot().workflowRuns?.revision).toBe(before);
  9460. });
  9461. // ── report 事件 → reports[](docs/dynamic-workflow/presentation.md「The run pane」)──
  9462. // 数据面是详情页 Results 区的全部输入;Results 区本身在 packages/ui 的 jsdom 用例里钉。
  9463. it("report 事件按顺序追加进 reports[]:string 原样,object 走 pretty JSON", () => {
  9464. const log = startedLog();
  9465. progress(log, "report", {
  9466. instance: { siteId: "report#1", ordinal: 1 },
  9467. item: "3 stale imports",
  9468. });
  9469. progress(log, "report", {
  9470. instance: { siteId: "report#2", ordinal: 1 },
  9471. item: { file: "a.ts", severity: "warn" },
  9472. });
  9473. const snapshot = runAll(log.events).projection.getSnapshot();
  9474. expect(snapshot.workflowRuns?.runs[0]?.reports).toEqual([
  9475. { siteId: "report#1", ordinal: 1, preview: "3 stale imports" },
  9476. {
  9477. siteId: "report#2",
  9478. ordinal: 1,
  9479. preview: '{\n "file": "a.ts",\n "severity": "warn"\n}',
  9480. },
  9481. ]);
  9482. // 序列化规则与 run 产物回投同源:字符串不加 JSON 引号。
  9483. expect(snapshot.workflowRuns?.runs[0]?.reports?.[0]?.preview).not.toContain('"');
  9484. expect(conversationSnapshotSchema.safeParse(snapshot).success).toBe(true);
  9485. });
  9486. it("零条 report 时 reports 键整个缺席(Results 区据此整区不渲染)", () => {
  9487. const log = startedLog();
  9488. progress(log, "node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" });
  9489. expect(runsOf(log)?.runs[0]).not.toHaveProperty("reports");
  9490. });
  9491. /**
  9492. * 这一条是 report 与 node 分类的凭证:report 有 site 身份、进 journal、有自己的 RunEvent,
  9493. * 但它**不是 step**。混进 nodes[] 的代价是可观测的——紧凑卡与任务岛的 `settled/observed`
  9494. * 步数读的就是 nodes,一个报得勤的工作流会显得步数虚高,状态叠加也会多亮一格。
  9495. */
  9496. it("report 不进 nodes[]/actors,也不动 nodesUsed;但抬升 lastEventSequence", () => {
  9497. const log = startedLog({ maxConcurrency: 4 });
  9498. progress(log, "node-queued", { instance: { siteId: "ask#1", ordinal: 1 }, kind: "ask" });
  9499. progress(log, "node-dispatched", { instance: { siteId: "ask#1", ordinal: 1 } });
  9500. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: "a finding" });
  9501. const run = runsOf(log)?.runs[0];
  9502. expect(run?.nodes).toHaveLength(1);
  9503. expect(run?.nodes.map((node) => node.siteId)).toEqual(["ask#1"]);
  9504. expect(run?.actors).toEqual([]);
  9505. expect(run?.usage.nodesUsed).toBe(1);
  9506. expect(run?.reports).toHaveLength(1);
  9507. // 事件日志要知道有新内容可取,所以水位照常抬升。
  9508. expect(run?.lastEventSequence).toBe(3);
  9509. });
  9510. it("失败结算之后 reports 原样留着:捞回半途产物正是 report 存在的理由", () => {
  9511. const log = startedLog();
  9512. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: "finding 1" });
  9513. progress(log, "run-settled", {
  9514. status: "errored",
  9515. error: { code: "DriverError", message: "boom" },
  9516. });
  9517. const run = runsOf(log)?.runs[0];
  9518. expect(run?.status).toBe("errored");
  9519. expect(run?.reports).toEqual([{ siteId: "report#1", ordinal: 1, preview: "finding 1" }]);
  9520. });
  9521. it("同一 report 事件重放(同 sequence 同内容)不产 delta、不重复条目", () => {
  9522. const log = startedLog();
  9523. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: "once" });
  9524. const { projection } = runAll(log.events);
  9525. const before = projection.getSnapshot().workflowRuns?.revision;
  9526. expect(projection.applyEvent(log.events.at(-1)!)).toEqual([]);
  9527. expect(projection.getSnapshot().workflowRuns?.revision).toBe(before);
  9528. expect(projection.getSnapshot().workflowRuns?.runs[0]?.reports).toHaveLength(1);
  9529. });
  9530. /**
  9531. * 去重键是实例(siteId × ordinal),不是事件 sequence——脚本 replay 时每个 report 调用都会
  9532. * 重跑。所以一条**新 sequence** 却带已见实例的事件只抬水位,绝不把同一条产物列两次。
  9533. */
  9534. it("新 sequence 带已见实例键:水位抬升,条目不重复", () => {
  9535. const log = startedLog();
  9536. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: "once" });
  9537. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: "once" });
  9538. const run = runsOf(log)?.runs[0];
  9539. expect(run?.reports).toEqual([{ siteId: "report#1", ordinal: 1, preview: "once" }]);
  9540. expect(run?.lastEventSequence).toBe(2);
  9541. });
  9542. it("reports 触到 64 条上限:拒绝新条目并置 truncated,已有条目照常更新", () => {
  9543. const log = startedLog();
  9544. for (let ordinal = 1; ordinal <= WORKFLOW_RUNS_LIMITS.maxReports + 3; ordinal += 1) {
  9545. progress(log, "report", {
  9546. instance: { siteId: "report#1", ordinal },
  9547. item: `finding ${ordinal}`,
  9548. });
  9549. }
  9550. const run = runsOf(log)?.runs[0];
  9551. expect(run?.reports).toHaveLength(WORKFLOW_RUNS_LIMITS.maxReports);
  9552. expect(run?.truncated).toBe(true);
  9553. // 先到的条目不被后来的挤掉(淘汰会让读者以为早期发现丢了;界的语义是拒新)。
  9554. expect(run?.reports?.[0]?.preview).toBe("finding 1");
  9555. // 触界之后其余键照常更新:结算与水位都不受影响。
  9556. progress(log, "run-settled", { status: "completed" });
  9557. const settled = runsOf(log)?.runs[0];
  9558. expect(settled?.status).toBe("completed");
  9559. expect(settled?.reports).toHaveLength(WORKFLOW_RUNS_LIMITS.maxReports);
  9560. });
  9561. it("单条预览超界即截断(带省略号),仍过 strict schema", () => {
  9562. const log = startedLog();
  9563. // 载荷有界化已经把单个字符串削到 2048,所以真正会超界的是「键多的对象展开成 pretty JSON」。
  9564. const wide: Record<string, string> = {};
  9565. for (let index = 0; index < 64; index += 1) wide[`key${index}`] = "x".repeat(64);
  9566. progress(log, "report", { instance: { siteId: "report#1", ordinal: 1 }, item: wide });
  9567. const snapshot = runAll(log.events).projection.getSnapshot();
  9568. const preview = snapshot.workflowRuns?.runs[0]?.reports?.[0]?.preview ?? "";
  9569. expect(preview.length).toBe(WORKFLOW_RUNS_LIMITS.maxReportPreviewLength);
  9570. expect(preview.endsWith("…")).toBe(true);
  9571. expect(conversationSnapshotSchema.safeParse(snapshot).success).toBe(true);
  9572. });
  9573. it("instance 缺失的 report 事件被忽略(不造无身份条目),但仍抬水位", () => {
  9574. const log = startedLog();
  9575. progress(log, "report", { item: "orphan" });
  9576. const run = runsOf(log)?.runs[0];
  9577. expect(run).not.toHaveProperty("reports");
  9578. expect(run?.lastEventSequence).toBe(1);
  9579. });
  9580. });
  9581. // 中枢直接启动已保存工作流(docs/dynamic-workflow/launch.md):controlOnly 启动轮的活投影。
  9582. // TurnStarted(workflow_launch) → turnHeader/userInput 双行 origin=workflowLaunch + 同一份元数据,
  9583. // 无助手行;TurnComplete 收口后 header 变 completed(controlOnly 不下发 running/工时)。
  9584. describe("workflow-direct-launch 启动轮投影", () => {
  9585. const workflowLaunch = {
  9586. runId: "dwfrun-9",
  9587. toolCallId: "launch-abc",
  9588. name: "deep-research",
  9589. scope: "global" as const,
  9590. path: "/home/u/.zcode/workflows/deep-research.ts",
  9591. args: { topic: "adaptive concurrency" },
  9592. description: "Deep-dive a topic",
  9593. };
  9594. function launchEvents(): SessionEvent[] {
  9595. const log = new EventLog();
  9596. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  9597. log.push(
  9598. SessionEventType.TurnStarted,
  9599. {
  9600. turnNumber: 1,
  9601. input: 'Started the saved workflow "deep-research" (global) as run dwfrun-9.',
  9602. messageId: "message-launch-1",
  9603. executionKind: "controlOnly",
  9604. inputSource: "workflow_launch",
  9605. workflowLaunch,
  9606. },
  9607. { turnId: "turn-launch" },
  9608. );
  9609. log.push(
  9610. SessionEventType.TurnComplete,
  9611. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  9612. { turnId: "turn-launch" },
  9613. );
  9614. return log.events;
  9615. }
  9616. it("双行 origin=workflowLaunch 且都带启动元数据,无助手行", () => {
  9617. const snapshot = runAll(launchEvents()).projection.getSnapshot();
  9618. expect(() => conversationSnapshotSchema.parse(snapshot)).not.toThrow();
  9619. const rows = snapshot.rows.window;
  9620. expect(rows.map((row) => row.kind)).toEqual(["turnHeader", "userInput"]);
  9621. const header = rows.find((row) => row.kind === "turnHeader");
  9622. expect(header).toMatchObject({
  9623. origin: "workflowLaunch",
  9624. executionKind: "controlOnly",
  9625. state: "completedSuccess",
  9626. workflowLaunch,
  9627. });
  9628. const userInput = rows.find((row) => row.kind === "userInput");
  9629. expect(userInput).toMatchObject({
  9630. origin: "workflowLaunch",
  9631. text: 'Started the saved workflow "deep-research" (global) as run dwfrun-9.',
  9632. workflowLaunch,
  9633. });
  9634. // controlOnly:不残留 running / activeWorks(旧 UI 会把 0ms 误显示成「已工作 1 秒」)。
  9635. expect(snapshot.control.activeWorks).toEqual([]);
  9636. });
  9637. it("启动轮收口让会话离开 draft:phase 成终态,sessions-index 摘要不再被当 draft 丢弃", () => {
  9638. // 2026-09-14 实机:只有一条 controlOnly 启动轮的会话活投影恒为 draft,task-index syncer 丢弃 draft
  9639. // 摘要,侧栏要等重启(store 种子给出终态 phase)才出现。冷热必须同形。
  9640. const events = launchEvents();
  9641. const { projection } = runAll(events.slice(0, 2));
  9642. expect(projection.getSnapshot().control.phase).toBe("draft");
  9643. projection.applyEvent(events[2]!);
  9644. const control = projection.getSnapshot().control;
  9645. expect(control.phase).toBe("completedSuccess");
  9646. expect(control.sessionEnded).toBe(true);
  9647. expect(control.canStop).toBe(false);
  9648. expect(control.activeWorks).toEqual([]);
  9649. });
  9650. it("非 draft 会话上的 controlOnly 轮照旧不碰 session control", () => {
  9651. const log = new EventLog();
  9652. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  9653. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "hi" }, { turnId: "turn-1" });
  9654. log.push(
  9655. SessionEventType.TurnComplete,
  9656. { response: "", tokenCount: 0, toolCallCount: 0, duration: 5, resultType: "cancelled" },
  9657. { turnId: "turn-1" },
  9658. );
  9659. log.push(
  9660. SessionEventType.TurnStarted,
  9661. { turnNumber: 2, input: "/goal x", executionKind: "controlOnly" },
  9662. { turnId: "turn-2" },
  9663. );
  9664. log.push(
  9665. SessionEventType.TurnComplete,
  9666. { response: "", tokenCount: 0, toolCallCount: 0, duration: 0, resultType: "success" },
  9667. { turnId: "turn-2" },
  9668. );
  9669. const snapshot = runAll(log.events).projection.getSnapshot();
  9670. // 上一轮的中断终态保留,控制轮的 success 不改写它。
  9671. expect(snapshot.control.phase).toBe("completedInterrupted");
  9672. });
  9673. });
  9674. // docs/dynamic-workflow/transcript-and-notifications.md:TurnStarted 上的 epilogueStart 原样落到
  9675. // userInput 行;缺席时行上没有这个键(老转录逐字不变)。
  9676. describe("userInput 行的 epilogueStart(热路径)", () => {
  9677. it("透传 TurnStarted.epilogueStart;缺席不写键", () => {
  9678. const log = new EventLog();
  9679. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  9680. log.push(
  9681. SessionEventType.TurnStarted,
  9682. { turnNumber: 1, input: "Summarize\n\n---\nStandard", epilogueStart: 9 },
  9683. { turnId: "turn-1" },
  9684. );
  9685. log.push(SessionEventType.TurnStarted, { turnNumber: 2, input: "plain" }, { turnId: "turn-2" });
  9686. const { projection } = runAll(log.events);
  9687. const rows = projection.getSnapshot().rows.window.filter((row) => row.kind === "userInput");
  9688. expect(rows[0]).toMatchObject({ text: "Summarize\n\n---\nStandard", epilogueStart: 9 });
  9689. expect(rows[1]).not.toHaveProperty("epilogueStart");
  9690. });
  9691. });