v4-gateway.test.ts 171 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143
  1. // ConversationV4Gateway 测试(M3 host 通道层 CLI 侧)。
  2. // 核心断言面:
  3. // 1. subscribe 内部 dispatch result 同时返回 ACK 与待入 outbox 的初始帧
  4. // 2. ingest 后按订阅者 profile.flushWindowMs 定时编码到 host.emitWireFrame(fake timers)
  5. // 3. v4/command:accepted 后台执行 + settle 固化;duplicate 重放终态;
  6. // sessionNotFound 拒绝;未接线命令 → failed fault.command.notImplemented
  7. // 4. 重订阅替换(R-01):旧订阅调度状态被清理、不再产帧
  8. // 5. disposeSession / dispose:定时器与 publisher 全量回收
  9. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  10. import { createSqliteSessionStore } from "@zcode/adapters/storage";
  11. import type {
  12. EventId,
  13. SessionEvent,
  14. SessionEventType as SessionEventTypeUnion,
  15. SessionId,
  16. TraceId,
  17. TurnId,
  18. } from "@zcode/contracts";
  19. import {
  20. SessionEventType,
  21. createMessageId,
  22. createPartId,
  23. createProjectId,
  24. createSessionId,
  25. } from "@zcode/contracts";
  26. import type {
  27. CommandAck,
  28. CommandEnvelope,
  29. CommandKey,
  30. CommandResult,
  31. ConversationTopicFrame,
  32. ConversationTelemetryFact,
  33. RoutedTopicWireFrame,
  34. V4ConversationFileChangesResult,
  35. V4ConversationFileRewindPreviewResult,
  36. } from "@zcode/shared/zcode-protocol-v4";
  37. import {
  38. DELIVERY_PROFILES,
  39. PROTOCOL_V4_LIMITS,
  40. utf8JsonByteLength,
  41. } from "@zcode/shared/zcode-protocol-v4";
  42. import {
  43. ConversationTopicPublisher,
  44. ConversationV4Gateway,
  45. PROJECTION_TERMINAL_RESERVE_BYTES,
  46. type CommandInbox,
  47. V4CommandNotImplementedError,
  48. } from "../src/zcode-protocol-v4/index.js";
  49. import type { SessionConfigSeed } from "../src/zcode-protocol-v4/index.js";
  50. import { V4CommandExecutor } from "../src/zcode-protocol-v4/commands/executor.js";
  51. import type { V4SessionRecordView } from "../src/zcode-protocol-v4/commands/types.js";
  52. import { loadPersistentCommandFacts } from "../src/zcode-protocol-v4/persistent-command-facts.js";
  53. import { registerCommittedForkBestEffort } from "../src/zcode-protocol/v4-bridge.js";
  54. // ── 事件构造(与 conversation-topic-publisher.test.ts 同一套)──
  55. class EventLog {
  56. private seq = 0;
  57. readonly events: SessionEvent[] = [];
  58. constructor(private readonly sessionId = "session-1") {}
  59. push(
  60. type: SessionEventTypeUnion,
  61. payload: unknown,
  62. opts: { turnId?: string } = {},
  63. ): SessionEvent {
  64. this.seq += 1;
  65. const event: SessionEvent = {
  66. id: `event-${this.seq}` as EventId,
  67. sessionId: this.sessionId as SessionId,
  68. turnId: opts.turnId as TurnId | undefined,
  69. type,
  70. timestamp: new Date(1_700_000_000_000 + this.seq * 1000),
  71. traceId: "trace-1" as TraceId,
  72. sequenceNumber: this.seq,
  73. payload,
  74. };
  75. this.events.push(event);
  76. return event;
  77. }
  78. }
  79. function sessionCreated(log: EventLog): SessionEvent {
  80. return log.push(SessionEventType.SessionCreated, {
  81. mode: "default",
  82. contextWindow: 200_000,
  83. });
  84. }
  85. function textDelta(log: EventLog, text: string): SessionEvent {
  86. return log.push(
  87. SessionEventType.ModelStreaming,
  88. { kind: "text_delta", delta: text, done: false },
  89. { turnId: "turn-1" },
  90. );
  91. }
  92. // ── 宿主打桩 ──
  93. interface HostStub {
  94. frames: ConversationTopicFrame[];
  95. telemetryFacts: ConversationTelemetryFact[];
  96. executed: CommandEnvelope[];
  97. errors: Array<{ scope: string; error: unknown }>;
  98. sessions: Set<string>;
  99. executeImpl: (
  100. envelope: CommandEnvelope,
  101. admission?: { admissionSeq: number; admittedAt: number; queueItemId: string },
  102. ) => Promise<CommandResult | undefined>;
  103. /** hydration 打桩:sessionId → 持久化事件序列。 */
  104. persistedEvents: Map<string, SessionEvent[]>;
  105. /** 标记哪些 session 的 loadPersistedEvents 走 transcript 合成(synthesized=true)。 */
  106. synthesizedSessions: Set<string>;
  107. loadPersistedEventsImpl?: (sessionId: string) => Promise<{
  108. events: SessionEvent[];
  109. synthesized: boolean;
  110. sourceEventSeq?: number;
  111. }>;
  112. /** R-19 config 种子打桩:sessionId → runtime 真值(缺省 = 钩子返回 null)。 */
  113. configSeeds: Map<string, SessionConfigSeed>;
  114. memorySettings?: Map<string, boolean>;
  115. fileChangeCalls: Array<{ sessionId: string; targetRowId: number; messageIds: string[] }>;
  116. fileChangesResult: V4ConversationFileChangesResult;
  117. fileRewindPreviewCalls: Array<{ sessionId: string; targetRowId: number; messageIds: string[] }>;
  118. fileRewindPreviewResult: V4ConversationFileRewindPreviewResult;
  119. persistentCommands: Record<
  120. "transcript" | "timeline" | "child" | "discarded",
  121. Map<string, CommandAck>
  122. >;
  123. inputAdmissions: Array<{ commandId: string; queueItemId: string }>;
  124. inputCancellations: Array<{ commandId: string; queueItemId: string; reason: string }>;
  125. resumeCalls: string[];
  126. resumeOutcome: "resumed" | "notFound";
  127. projectionTerminations: Array<{ sessionId: string; reasonCode: string }>;
  128. projectionEvents: Array<{ sessionId: string; event: SessionEvent }>;
  129. }
  130. function makeHost(): HostStub {
  131. return {
  132. frames: [],
  133. telemetryFacts: [],
  134. executed: [],
  135. errors: [],
  136. sessions: new Set(["session-1"]),
  137. executeImpl: async () => undefined,
  138. persistedEvents: new Map(),
  139. synthesizedSessions: new Set(),
  140. configSeeds: new Map(),
  141. fileChangeCalls: [],
  142. fileChangesResult: { files: 0, additions: 0, deletions: 0, items: [] },
  143. fileRewindPreviewCalls: [],
  144. fileRewindPreviewResult: {
  145. canApply: false,
  146. safeFiles: [],
  147. unsafeFiles: [],
  148. ignoredFiles: [],
  149. },
  150. persistentCommands: {
  151. transcript: new Map(),
  152. timeline: new Map(),
  153. child: new Map(),
  154. discarded: new Map(),
  155. },
  156. inputAdmissions: [],
  157. inputCancellations: [],
  158. resumeCalls: [],
  159. resumeOutcome: "notFound",
  160. projectionTerminations: [],
  161. projectionEvents: [],
  162. };
  163. }
  164. function makeGateway(host: HostStub): ConversationV4Gateway {
  165. return new ConversationV4Gateway(
  166. {
  167. sessionExists: (sessionId) => host.sessions.has(sessionId),
  168. resumePersistedSession: async (sessionId) => {
  169. host.resumeCalls.push(sessionId);
  170. if (host.resumeOutcome === "resumed") host.sessions.add(sessionId);
  171. return { status: host.resumeOutcome };
  172. },
  173. emitWireFrame: (wire) => collectCompleteConversationFrame(host.frames, wire),
  174. emitConversationTelemetryFact: (fact) => host.telemetryFacts.push(fact),
  175. onTargetCompleted: (sessionId, event) => {
  176. host.projectionEvents.push({ sessionId, event });
  177. },
  178. executeCommand: async (envelope, admission) => {
  179. host.executed.push(envelope);
  180. return await host.executeImpl(envelope, admission);
  181. },
  182. admitCommandInput: async (envelope, admission) => {
  183. if (envelope.type !== "sendText" && envelope.type !== "sendGoalCommand") return null;
  184. host.inputAdmissions.push({
  185. commandId: envelope.commandId,
  186. queueItemId: admission.queueItemId,
  187. });
  188. const payload = envelope.payload as { text: string; attachments?: never[] };
  189. return {
  190. sourceCommandId: envelope.commandId,
  191. queueItemId: admission.queueItemId,
  192. clientId: envelope.clientId,
  193. kind: envelope.type,
  194. text: payload.text,
  195. attachments: payload.attachments ?? [],
  196. delivery: { requested: "startNow", admitted: "startNow" },
  197. order: { admissionSeq: admission.admissionSeq },
  198. steer: { state: "notRequested" },
  199. dispatch: { state: "admitted" },
  200. admittedAt: admission.admittedAt,
  201. };
  202. },
  203. cancelCommandInput: async (envelope, queueItemId, reason) => {
  204. host.inputCancellations.push({ commandId: envelope.commandId, queueItemId, reason });
  205. },
  206. terminateTurnForProjectionFault: (sessionId, reasonCode) => {
  207. host.projectionTerminations.push({ sessionId, reasonCode });
  208. },
  209. loadPersistedEvents: async (sessionId) =>
  210. host.loadPersistedEventsImpl?.(sessionId) ?? {
  211. events: host.persistedEvents.get(sessionId) ?? [],
  212. synthesized: host.synthesizedSessions.has(sessionId),
  213. },
  214. getSessionConfigSeed: (sessionId) => host.configSeeds.get(sessionId) ?? null,
  215. getSessionMemoryEnabled: (sessionId) => host.memorySettings?.get(sessionId),
  216. getConversationFileChanges: async (sessionId, targetRowId, messageIds) => {
  217. host.fileChangeCalls.push({ sessionId, targetRowId, messageIds });
  218. return host.fileChangesResult;
  219. },
  220. previewConversationFileRewind: async (sessionId, targetRowId, messageIds) => {
  221. host.fileRewindPreviewCalls.push({ sessionId, targetRowId, messageIds });
  222. return host.fileRewindPreviewResult;
  223. },
  224. lookupTranscriptCommand: (key: CommandKey) =>
  225. host.persistentCommands.transcript.get(`${key.sessionId ?? "@global"}\0${key.commandId}`) ??
  226. null,
  227. lookupTimelineCommand: (key: CommandKey) =>
  228. host.persistentCommands.timeline.get(`${key.sessionId ?? "@global"}\0${key.commandId}`) ??
  229. null,
  230. lookupChildCommand: (key: CommandKey) =>
  231. host.persistentCommands.child.get(`${key.sessionId ?? "@global"}\0${key.commandId}`) ??
  232. null,
  233. lookupDiscardedCommand: (key: CommandKey) =>
  234. host.persistentCommands.discarded.get(`${key.sessionId ?? "@global"}\0${key.commandId}`) ??
  235. null,
  236. onError: (scope, error) => host.errors.push({ scope, error }),
  237. },
  238. { now: () => 1_700_000_999_000, createLogEpoch: () => "epoch-1" },
  239. );
  240. }
  241. function collectCompleteConversationFrame(
  242. frames: ConversationTopicFrame[],
  243. wire: RoutedTopicWireFrame,
  244. ): void {
  245. if (wire.kind !== "complete" || !wire.topic.startsWith("conversation/")) {
  246. throw new Error("gateway test adapter only accepts complete conversation wires");
  247. }
  248. frames.push(wire.frame as ConversationTopicFrame);
  249. }
  250. function subscribeParams(overrides: Record<string, unknown> = {}) {
  251. return {
  252. topic: "conversation/session-1",
  253. connectionId: "conn-1",
  254. clientMode: "desktop-continuous",
  255. ...overrides,
  256. };
  257. }
  258. function commandParams(overrides: Record<string, unknown> = {}) {
  259. return {
  260. commandId: "cmd-1",
  261. clientId: "client-1",
  262. sessionId: "session-1",
  263. type: "sendText",
  264. payload: { text: "你好" },
  265. issuedAt: 1_700_000_000_000,
  266. ...overrides,
  267. };
  268. }
  269. const CONTINUOUS_WINDOW = DELIVERY_PROFILES.continuous.flushWindowMs;
  270. const REPLAYABLE_WINDOW = DELIVERY_PROFILES.replayable.flushWindowMs;
  271. describe("订阅与帧调度", () => {
  272. beforeEach(() => vi.useFakeTimers());
  273. afterEach(() => vi.useRealTimers());
  274. it("raw cache slims request history without changing live events or sequence continuity", async () => {
  275. const gateway = makeGateway(makeHost());
  276. const log = new EventLog();
  277. gateway.ingest("session-1", sessionCreated(log));
  278. const request = log.push(SessionEventType.ModelRequest, {
  279. messages: [{ role: "user", content: "history" }],
  280. providerId: "fixture",
  281. modelId: "model",
  282. });
  283. gateway.ingest("session-1", request);
  284. gateway.ingest(
  285. "session-1",
  286. log.push(
  287. SessionEventType.TurnStarted,
  288. { turnNumber: 1, input: "next", inputId: "input" },
  289. { turnId: "turn-1" },
  290. ),
  291. );
  292. const states = (
  293. gateway as unknown as {
  294. rawSequenceStates: Map<
  295. string,
  296. {
  297. recentRawEventsById: Map<string, SessionEvent>;
  298. sourceEventSeq: number;
  299. }
  300. >;
  301. }
  302. ).rawSequenceStates;
  303. const state = states.get("session-1")!;
  304. expect(state.recentRawEventsById.get(String(request.id))).toEqual({
  305. ...request,
  306. payload: { providerId: "fixture", modelId: "model", messageCount: 1 },
  307. });
  308. expect(request.payload).toHaveProperty("messages");
  309. expect(state.sourceEventSeq).toBe(3);
  310. expect((await gateway.subscribe(subscribeParams())).ack.mode).toBe("snapshot");
  311. gateway.dispose();
  312. });
  313. it("subscribe 内部 dispatch result 携带待入 outbox 的 snapshot 初始帧", async () => {
  314. const host = makeHost();
  315. const gateway = makeGateway(host);
  316. const log = new EventLog();
  317. gateway.ingest("session-1", sessionCreated(log));
  318. const result = await gateway.subscribe(subscribeParams());
  319. expect(result.ack.mode).toBe("snapshot");
  320. expect(result.initialFrame?.payload.kind).toBe("snapshot");
  321. // 初始帧只进入 server 内部 dispatch result,不走 online notification 出口。
  322. expect(host.frames).toHaveLength(0);
  323. });
  324. it("只从 live ingest 发送 telemetry fact,并按 eventId 有界入口去重", () => {
  325. const host = makeHost();
  326. const gateway = makeGateway(host);
  327. const log = new EventLog();
  328. gateway.ingest("session-1", sessionCreated(log));
  329. const started = log.push(
  330. SessionEventType.TurnStarted,
  331. { turnNumber: 1, input: "不可进入 fact 的正文", inputId: "command-1" },
  332. { turnId: "turn-1" },
  333. );
  334. gateway.ingest("session-1", started);
  335. gateway.ingest("session-1", started);
  336. expect(host.telemetryFacts).toEqual([
  337. expect.objectContaining({
  338. kind: "turn.started",
  339. eventId: String(started.id),
  340. sourceCommandId: "command-1",
  341. }),
  342. ]);
  343. expect(JSON.stringify(host.telemetryFacts)).not.toContain("不可进入 fact 的正文");
  344. });
  345. it.each([
  346. {
  347. detailKind: "command",
  348. toolName: "Bash",
  349. perf: {
  350. totalMs: 130,
  351. permissionWaitMs: 20,
  352. detail: {
  353. kind: "command",
  354. command: {
  355. runMs: 100,
  356. firstOutputMs: 10,
  357. noOutputMs: 0,
  358. exitCode: 0,
  359. timedOut: false,
  360. outputBytes: 64,
  361. category: "git",
  362. name: "git",
  363. count: 1,
  364. status: "completed",
  365. hash: "0123456789abcdef",
  366. },
  367. },
  368. },
  369. expected: {
  370. totalMs: 130,
  371. permissionWaitMs: 20,
  372. commandRunMs: 100,
  373. firstOutputMs: 10,
  374. noOutputMs: 0,
  375. exitCode: 0,
  376. timedOut: false,
  377. outputBytes: 64,
  378. commandCategory: "git",
  379. commandName: "git",
  380. commandCount: 1,
  381. commandStatus: "completed",
  382. },
  383. },
  384. {
  385. detailKind: "filesystem",
  386. toolName: "Write",
  387. perf: {
  388. totalMs: 80,
  389. detail: {
  390. kind: "filesystem",
  391. filesystem: {
  392. readMs: 5,
  393. writeMs: 60,
  394. fileCount: 1,
  395. totalBytes: 256,
  396. maxFileBytes: 256,
  397. workspaceKind: "local",
  398. },
  399. },
  400. },
  401. expected: {
  402. totalMs: 80,
  403. fsReadMs: 5,
  404. fsWriteMs: 60,
  405. fileCount: 1,
  406. totalBytes: 256,
  407. maxFileBytes: 256,
  408. workspaceKind: "local",
  409. },
  410. },
  411. {
  412. detailKind: "patch",
  413. toolName: "Edit",
  414. perf: {
  415. totalMs: 90,
  416. detail: {
  417. kind: "patch",
  418. filesystem: {
  419. readMs: 6,
  420. writeMs: 20,
  421. fileCount: 1,
  422. totalBytes: 512,
  423. maxFileBytes: 512,
  424. workspaceKind: "remote",
  425. },
  426. patch: { matchMs: 12, hunkCount: 2, matchAttempts: 3 },
  427. },
  428. },
  429. expected: {
  430. totalMs: 90,
  431. fsReadMs: 6,
  432. fsWriteMs: 20,
  433. fileCount: 1,
  434. totalBytes: 512,
  435. maxFileBytes: 512,
  436. workspaceKind: "remote",
  437. patchMatchMs: 12,
  438. hunkCount: 2,
  439. matchAttempts: 3,
  440. },
  441. },
  442. {
  443. detailKind: "common-only",
  444. toolName: "Read",
  445. perf: { totalMs: 40, permissionWaitMs: 7 },
  446. expected: { totalMs: 40, permissionWaitMs: 7 },
  447. },
  448. ])("将 $detailKind runtime perf 映射为扁平工具终态 fact", ({ toolName, perf, expected }) => {
  449. const host = makeHost();
  450. const gateway = makeGateway(host);
  451. const log = new EventLog();
  452. gateway.ingest("session-1", sessionCreated(log));
  453. gateway.ingest(
  454. "session-1",
  455. log.push(
  456. SessionEventType.TurnStarted,
  457. { turnNumber: 1, input: "private prompt", inputId: "command-1" },
  458. { turnId: "turn-1" },
  459. ),
  460. );
  461. gateway.ingest(
  462. "session-1",
  463. log.push(
  464. SessionEventType.ToolCallScheduled,
  465. {
  466. toolCallId: "tool-1",
  467. toolName,
  468. input: { private: "must-not-leak" },
  469. schedule: { parallelGroups: [["tool-1"]], executionOrder: ["tool-1"] },
  470. },
  471. { turnId: "turn-1" },
  472. ),
  473. );
  474. gateway.ingest(
  475. "session-1",
  476. log.push(
  477. SessionEventType.ToolCallResult,
  478. {
  479. toolCallId: "tool-1",
  480. duration: 123,
  481. result: { success: true, content: "private tool output", perf },
  482. },
  483. { turnId: "turn-1" },
  484. ),
  485. );
  486. const terminalFact = host.telemetryFacts.find(
  487. (fact) =>
  488. fact.kind === "tool.lifecycle" &&
  489. fact.toolCallId === "tool-1" &&
  490. fact.phase === "completed",
  491. );
  492. expect(terminalFact).toMatchObject({
  493. kind: "tool.lifecycle",
  494. phase: "completed",
  495. toolName,
  496. durationMs: 123,
  497. performance: expected,
  498. });
  499. const serializedPerformance = JSON.stringify(
  500. terminalFact?.kind === "tool.lifecycle" ? terminalFact.performance : undefined,
  501. );
  502. expect(serializedPerformance).not.toContain("detail");
  503. expect(serializedPerformance).not.toContain("hash");
  504. expect(serializedPerformance).not.toContain("commandHash");
  505. expect(host.errors.filter((entry) => entry.scope === "v4.telemetry.normalize")).toEqual([]);
  506. });
  507. it("失败 ToolCallResult 同样保留扁平 performance 与错误事实", () => {
  508. const host = makeHost();
  509. const gateway = makeGateway(host);
  510. const log = new EventLog();
  511. gateway.ingest("session-1", sessionCreated(log));
  512. gateway.ingest(
  513. "session-1",
  514. log.push(
  515. SessionEventType.TurnStarted,
  516. { turnNumber: 1, input: "private prompt", inputId: "command-1" },
  517. { turnId: "turn-1" },
  518. ),
  519. );
  520. gateway.ingest(
  521. "session-1",
  522. log.push(
  523. SessionEventType.ToolCallScheduled,
  524. {
  525. toolCallId: "tool-1",
  526. toolName: "Bash",
  527. input: { command: "private command" },
  528. schedule: { parallelGroups: [["tool-1"]], executionOrder: ["tool-1"] },
  529. },
  530. { turnId: "turn-1" },
  531. ),
  532. );
  533. gateway.ingest(
  534. "session-1",
  535. log.push(
  536. SessionEventType.ToolCallResult,
  537. {
  538. toolCallId: "tool-1",
  539. duration: 50,
  540. result: {
  541. success: false,
  542. content: "private failure output",
  543. error: { type: "ToolExecutionFailed", code: "EXIT_2", message: "exit 2" },
  544. perf: {
  545. totalMs: 70,
  546. detail: {
  547. kind: "command",
  548. command: { runMs: 50, exitCode: 2, status: "failed" },
  549. },
  550. },
  551. },
  552. },
  553. { turnId: "turn-1" },
  554. ),
  555. );
  556. expect(host.telemetryFacts).toEqual(
  557. expect.arrayContaining([
  558. expect.objectContaining({
  559. kind: "tool.lifecycle",
  560. phase: "failed",
  561. toolName: "Bash",
  562. durationMs: 50,
  563. errorCode: "EXIT_2",
  564. errorMessage: "exit 2",
  565. performance: {
  566. totalMs: 70,
  567. commandRunMs: 50,
  568. exitCode: 2,
  569. commandStatus: "failed",
  570. },
  571. }),
  572. ]),
  573. );
  574. expect(host.errors.filter((entry) => entry.scope === "v4.telemetry.normalize")).toEqual([]);
  575. });
  576. it("automation admission 与 CronCreate 成功结果只透传稳定关联 ID", () => {
  577. const host = makeHost();
  578. const gateway = makeGateway(host);
  579. const log = new EventLog();
  580. gateway.ingest(
  581. "session-1",
  582. log.push(
  583. SessionEventType.TurnStarted,
  584. {
  585. turnNumber: 1,
  586. input: "定时任务正文不能进入 fact",
  587. inputId: "automation-1:1700000000000",
  588. automationId: "automation-1",
  589. },
  590. { turnId: "turn-automation" },
  591. ),
  592. );
  593. gateway.ingest(
  594. "session-1",
  595. log.push(
  596. SessionEventType.ToolCallScheduled,
  597. {
  598. toolCallId: "tool-cron",
  599. toolName: "CronCreate",
  600. schedule: { parallelGroups: [], executionOrder: [] },
  601. },
  602. { turnId: "turn-automation" },
  603. ),
  604. );
  605. gateway.ingest(
  606. "session-1",
  607. log.push(
  608. SessionEventType.ToolCallResult,
  609. {
  610. toolCallId: "tool-cron",
  611. duration: 10,
  612. result: {
  613. success: true,
  614. content: JSON.stringify({
  615. automation: { automationId: "automation-created", prompt: "不能透传" },
  616. }),
  617. },
  618. },
  619. { turnId: "turn-automation" },
  620. ),
  621. );
  622. expect(host.telemetryFacts).toEqual(
  623. expect.arrayContaining([
  624. expect.objectContaining({
  625. kind: "turn.started",
  626. automationId: "automation-1",
  627. taskTrigger: "schedule",
  628. scheduledAt: 1_700_000_000_000,
  629. }),
  630. expect.objectContaining({
  631. kind: "tool.lifecycle",
  632. phase: "completed",
  633. toolName: "CronCreate",
  634. automationId: "automation-created",
  635. }),
  636. ]),
  637. );
  638. expect(JSON.stringify(host.telemetryFacts)).not.toContain("定时任务正文");
  639. expect(JSON.stringify(host.telemetryFacts)).not.toContain("不能透传");
  640. });
  641. it.each([{ skill: "requested-skill" }, { name: "legacy-skill" }])(
  642. "Skill 调度不提取任何请求名称: %#",
  643. (input) => {
  644. const host = makeHost();
  645. const gateway = makeGateway(host);
  646. const log = new EventLog();
  647. gateway.ingest("session-1", sessionCreated(log));
  648. gateway.ingest(
  649. "session-1",
  650. log.push(
  651. SessionEventType.ToolCallScheduled,
  652. {
  653. toolCallId: "tool-skill-request",
  654. toolName: "Skill",
  655. input: { ...input, args: "private-arguments" },
  656. schedule: { parallelGroups: [], executionOrder: [] },
  657. },
  658. { turnId: "turn-skill" },
  659. ),
  660. );
  661. const fact = host.telemetryFacts.find((fact) => fact.kind === "tool.lifecycle");
  662. expect(fact).toMatchObject({ toolName: "Skill", phase: "scheduled" });
  663. expect(fact).not.toHaveProperty("skillName");
  664. expect(JSON.stringify(host.telemetryFacts)).not.toContain("private-arguments");
  665. const name = "skill" in input ? input.skill : input.name;
  666. if (typeof name === "string") expect(JSON.stringify(host.telemetryFacts)).not.toContain(name);
  667. },
  668. );
  669. it.each(["/Users/FAKE_USER/private", "demo\nsecret", "sk-" + "a".repeat(49), "a".repeat(5000)])(
  670. "Skill 已解析 metadata 仍需名称校验: %#",
  671. (name) => {
  672. const host = makeHost();
  673. const gateway = makeGateway(host);
  674. const log = new EventLog();
  675. gateway.ingest("session-1", sessionCreated(log));
  676. gateway.ingest(
  677. "session-1",
  678. log.push(
  679. SessionEventType.ToolCallScheduled,
  680. {
  681. toolCallId: "skill-private",
  682. toolName: "Skill",
  683. input: { skill: "demo" },
  684. schedule: { parallelGroups: [], executionOrder: [] },
  685. },
  686. { turnId: "turn-skill" },
  687. ),
  688. );
  689. gateway.ingest(
  690. "session-1",
  691. log.push(
  692. SessionEventType.ToolCallResult,
  693. {
  694. toolCallId: "skill-private",
  695. duration: 10,
  696. skillMetadata: { name, source: "zcode" },
  697. result: { success: true, content: "not-for-telemetry" },
  698. },
  699. { turnId: "turn-skill" },
  700. ),
  701. );
  702. expect(
  703. host.telemetryFacts.find(
  704. (fact) => fact.kind === "tool.lifecycle" && fact.phase === "completed",
  705. ),
  706. ).toMatchObject({ skillName: "unknown", skillSource: "zcode" });
  707. expect(JSON.stringify(host.telemetryFacts)).not.toContain(name);
  708. },
  709. );
  710. it("Skill tool result 只透传受限 metadata", () => {
  711. const host = makeHost();
  712. const gateway = makeGateway(host);
  713. const log = new EventLog();
  714. gateway.ingest("session-1", sessionCreated(log));
  715. gateway.ingest(
  716. "session-1",
  717. log.push(
  718. SessionEventType.ToolCallScheduled,
  719. {
  720. toolCallId: "tool-skill",
  721. toolName: "Skill",
  722. input: { skill: "document-skills:pptx", args: "" },
  723. schedule: { parallelGroups: [], executionOrder: [] },
  724. },
  725. { turnId: "turn-skill" },
  726. ),
  727. );
  728. gateway.ingest(
  729. "session-1",
  730. log.push(
  731. SessionEventType.ToolCallResult,
  732. {
  733. toolCallId: "tool-skill",
  734. duration: 10,
  735. skillMetadata: {
  736. name: "pptx",
  737. qualifiedName: "document-skills:pptx",
  738. pluginId: "document-skills@zcode-plugins-official",
  739. source: "plugin",
  740. },
  741. result: { success: true, content: "<skill_content>正文不进入 fact</skill_content>" },
  742. },
  743. { turnId: "turn-skill" },
  744. ),
  745. );
  746. const skillFact = host.telemetryFacts.find(
  747. (fact) => fact.kind === "tool.lifecycle" && fact.phase === "completed",
  748. );
  749. expect(skillFact).toMatchObject({
  750. toolName: "Skill",
  751. skillName: "pptx",
  752. skillQualifiedName: "document-skills:pptx",
  753. skillPluginId: "document-skills@zcode-plugins-official",
  754. skillSource: "plugin",
  755. });
  756. expect(JSON.stringify(host.telemetryFacts)).not.toContain("正文不进入 fact");
  757. });
  758. it("Skill tool error 保留已解析的 metadata", () => {
  759. const host = makeHost();
  760. const gateway = makeGateway(host);
  761. const log = new EventLog();
  762. gateway.ingest("session-1", sessionCreated(log));
  763. gateway.ingest(
  764. "session-1",
  765. log.push(
  766. SessionEventType.ToolCallScheduled,
  767. {
  768. toolCallId: "tool-skill-error",
  769. toolName: "Skill",
  770. input: { skill: "document-skills:pptx", args: "" },
  771. schedule: { parallelGroups: [], executionOrder: [] },
  772. },
  773. { turnId: "turn-skill-error" },
  774. ),
  775. );
  776. gateway.ingest(
  777. "session-1",
  778. log.push(
  779. SessionEventType.ToolCallError,
  780. {
  781. toolCallId: "tool-skill-error",
  782. skillMetadata: {
  783. name: "pptx",
  784. qualifiedName: "document-skills:pptx",
  785. pluginId: "document-skills@zcode-plugins-official",
  786. source: "plugin",
  787. },
  788. error: { type: "SERIALIZATION_ERROR", message: "post hook failed" },
  789. },
  790. { turnId: "turn-skill-error" },
  791. ),
  792. );
  793. expect(host.telemetryFacts).toEqual(
  794. expect.arrayContaining([
  795. expect.objectContaining({
  796. kind: "tool.lifecycle",
  797. phase: "failed",
  798. toolName: "Skill",
  799. skillName: "pptx",
  800. skillQualifiedName: "document-skills:pptx",
  801. skillPluginId: "document-skills@zcode-plugins-official",
  802. skillSource: "plugin",
  803. }),
  804. ]),
  805. );
  806. });
  807. it("Off-Peak TurnStarted 只透传稳定 task attribution,不透传正文", () => {
  808. const host = makeHost();
  809. const gateway = makeGateway(host);
  810. const log = new EventLog();
  811. gateway.ingest("session-1", sessionCreated(log));
  812. gateway.ingest(
  813. "session-1",
  814. log.push(
  815. SessionEventType.TurnStarted,
  816. {
  817. turnNumber: 1,
  818. input: "闲时任务 prompt 不能进入 fact",
  819. inputId: "message-offpeak-run-1",
  820. offPeakTaskId: "offpeak-stable-1",
  821. offPeakRunType: "init",
  822. },
  823. { turnId: "turn-offpeak" },
  824. ),
  825. );
  826. expect(host.telemetryFacts).toEqual(
  827. expect.arrayContaining([
  828. expect.objectContaining({
  829. kind: "turn.started",
  830. sourceCommandId: "message-offpeak-run-1",
  831. offPeakTaskId: "offpeak-stable-1",
  832. offPeakRunType: "init",
  833. }),
  834. ]),
  835. );
  836. expect(JSON.stringify(host.telemetryFacts)).not.toContain("闲时任务 prompt 不能进入 fact");
  837. });
  838. it("manual run 无调度字段;非 runId 输入与 CronCreate 解析失败只降级不误标", () => {
  839. const host = makeHost();
  840. const gateway = makeGateway(host);
  841. const log = new EventLog();
  842. gateway.ingest(
  843. "session-1",
  844. log.push(
  845. SessionEventType.TurnStarted,
  846. {
  847. turnNumber: 1,
  848. input: "manual 正文",
  849. inputId: "automation-1:manual:run-1",
  850. automationId: "automation-1",
  851. },
  852. { turnId: "turn-manual" },
  853. ),
  854. );
  855. gateway.ingest(
  856. "session-1",
  857. log.push(
  858. SessionEventType.TurnStarted,
  859. {
  860. turnNumber: 2,
  861. input: "普通输入",
  862. inputId: "cmd-1700000000000",
  863. automationId: "automation-2",
  864. },
  865. { turnId: "turn-mismatch" },
  866. ),
  867. );
  868. gateway.ingest(
  869. "session-1",
  870. log.push(
  871. SessionEventType.ToolCallScheduled,
  872. {
  873. toolCallId: "tool-cron-bad",
  874. toolName: "CronCreate",
  875. schedule: { parallelGroups: [], executionOrder: [] },
  876. },
  877. { turnId: "turn-manual" },
  878. ),
  879. );
  880. gateway.ingest(
  881. "session-1",
  882. log.push(
  883. SessionEventType.ToolCallResult,
  884. {
  885. toolCallId: "tool-cron-bad",
  886. duration: 10,
  887. result: { success: true, content: "created (not json)" },
  888. },
  889. { turnId: "turn-manual" },
  890. ),
  891. );
  892. const manualStart = host.telemetryFacts.find(
  893. (fact) =>
  894. fact.kind === "turn.started" && fact.sourceCommandId === "automation-1:manual:run-1",
  895. );
  896. expect(manualStart).toMatchObject({ automationId: "automation-1", taskTrigger: "manual" });
  897. expect(manualStart).not.toHaveProperty("scheduledAt");
  898. // inputId 不是该 automation 的 runId:只保留关联 ID,不猜触发方式,也不切出伪 scheduledAt。
  899. const mismatchStart = host.telemetryFacts.find(
  900. (fact) => fact.kind === "turn.started" && fact.sourceCommandId === "cmd-1700000000000",
  901. );
  902. expect(mismatchStart).toMatchObject({ automationId: "automation-2" });
  903. expect(mismatchStart).not.toHaveProperty("taskTrigger");
  904. expect(mismatchStart).not.toHaveProperty("scheduledAt");
  905. const cronResult = host.telemetryFacts.find(
  906. (fact) => fact.kind === "tool.lifecycle" && fact.phase === "completed",
  907. );
  908. expect(cronResult).toMatchObject({ toolName: "CronCreate" });
  909. expect(cronResult).not.toHaveProperty("automationId");
  910. });
  911. it("model request fact 只保留 URL 解析后的 hostname", () => {
  912. const host = makeHost();
  913. const gateway = makeGateway(host);
  914. const log = new EventLog();
  915. const network = log.push(
  916. SessionEventType.ModelNetworkStatus,
  917. {
  918. type: "model_request_started",
  919. timestamp: "2026-07-17T00:00:00.000Z",
  920. traceId: "trace-1",
  921. requestId: "request-1",
  922. providerId: "provider-1",
  923. modelId: "model-1",
  924. baseURL: "https://user:secret@example.com/private/path?token=secret#fragment",
  925. transport: "sse",
  926. attempt: 1,
  927. maxAttempts: 3,
  928. requestHeaders: { authorization: "Bearer secret" },
  929. responseHeaders: { "set-cookie": "secret" },
  930. },
  931. { turnId: "turn-1" },
  932. );
  933. gateway.ingest("session-1", network);
  934. expect(host.telemetryFacts).toEqual([
  935. expect.objectContaining({
  936. kind: "model.request.status",
  937. providerHostname: "example.com",
  938. }),
  939. ]);
  940. const serialized = JSON.stringify(host.telemetryFacts);
  941. expect(serialized).not.toContain("private/path");
  942. expect(serialized).not.toContain("token=secret");
  943. expect(serialized).not.toContain("authorization");
  944. expect(serialized).not.toContain("set-cookie");
  945. const failed = log.push(
  946. SessionEventType.ModelNetworkStatus,
  947. {
  948. type: "model_request_failed",
  949. timestamp: "2026-07-17T00:00:01.000Z",
  950. traceId: "trace-1",
  951. requestId: "request-1",
  952. providerId: "provider-1",
  953. modelId: "model-1",
  954. baseURL: "https://example.com/v1/messages",
  955. transport: "sse",
  956. attempt: 1,
  957. maxAttempts: 3,
  958. durationMs: 10,
  959. reason: "server_error",
  960. retryable: true,
  961. message: "上游响应正文不能穿过 fact",
  962. statusCode: 503,
  963. },
  964. { turnId: "turn-1" },
  965. );
  966. gateway.ingest("session-1", failed);
  967. expect(JSON.stringify(host.telemetryFacts)).not.toContain("上游响应正文不能穿过 fact");
  968. });
  969. it("准入等待的两端不产出 model.request.status fact,也不让 schema 抛出(v3 决策 44)", () => {
  970. const host = makeHost();
  971. const gateway = makeGateway(host);
  972. const log = new EventLog();
  973. const base = {
  974. timestamp: "2026-09-08T00:00:00.000Z",
  975. traceId: "trace-1",
  976. requestId: "request-q",
  977. model: { providerId: "provider-1", modelId: "model-1" },
  978. transport: "sse",
  979. attempt: 1,
  980. maxAttempts: 0,
  981. };
  982. gateway.ingest(
  983. "session-1",
  984. log.push(
  985. SessionEventType.ModelNetworkStatus,
  986. { ...base, type: "model_request_queued" },
  987. { turnId: "turn-1" },
  988. ),
  989. );
  990. gateway.ingest(
  991. "session-1",
  992. log.push(
  993. SessionEventType.ModelNetworkStatus,
  994. { ...base, type: "model_request_admitted", queuedMs: 800 },
  995. { turnId: "turn-1" },
  996. ),
  997. );
  998. expect(host.telemetryFacts.filter((fact) => fact.kind === "model.request.status")).toEqual([]);
  999. });
  1000. it("usage fact 的 totalTokens fallback 与 contracts 公式一致,不重复加 reasoning", () => {
  1001. const host = makeHost();
  1002. const gateway = makeGateway(host);
  1003. const log = new EventLog();
  1004. gateway.ingest(
  1005. "session-1",
  1006. log.push(
  1007. SessionEventType.ModelComplete,
  1008. {
  1009. content: "done",
  1010. stopReason: "stop",
  1011. querySource: "main_turn",
  1012. usage: {
  1013. inputTokens: 10,
  1014. outputTokens: 4,
  1015. reasoningTokens: 3,
  1016. cacheReadTokens: 2,
  1017. cacheWriteTokens: 1,
  1018. },
  1019. },
  1020. { turnId: "turn-1" },
  1021. ),
  1022. );
  1023. expect(host.telemetryFacts).toEqual([
  1024. expect.objectContaining({
  1025. kind: "usage.delta",
  1026. totalTokens: 14,
  1027. reasoningTokens: 3,
  1028. }),
  1029. ]);
  1030. });
  1031. it("usage fact 不把标题 sidecar、compact 或 tool_internal 累加到 prompt", () => {
  1032. const host = makeHost();
  1033. const gateway = makeGateway(host);
  1034. const log = new EventLog();
  1035. for (const [querySource, stopReason] of [
  1036. ["session_title", "end_turn"],
  1037. ["compact", "end_turn"],
  1038. ] as const) {
  1039. gateway.ingest(
  1040. "session-1",
  1041. log.push(
  1042. SessionEventType.ModelComplete,
  1043. {
  1044. content: "sidecar private content",
  1045. ...(querySource ? { querySource } : {}),
  1046. stopReason,
  1047. usage: { inputTokens: 64, outputTokens: 8 },
  1048. },
  1049. { turnId: "turn-1" },
  1050. ),
  1051. );
  1052. }
  1053. for (const requestId of ["request-tool-internal", "request-main"]) {
  1054. gateway.ingest(
  1055. "session-1",
  1056. log.push(
  1057. SessionEventType.ModelNetworkStatus,
  1058. {
  1059. type: "model_request_completed",
  1060. timestamp: "2026-07-24T00:00:00.000Z",
  1061. traceId: `trace-${requestId}`,
  1062. requestId,
  1063. providerId: "provider-1",
  1064. modelId: "model-1",
  1065. baseURL: "https://example.com/v1/messages",
  1066. transport: "sse",
  1067. attempt: 1,
  1068. maxAttempts: 1,
  1069. durationMs: 20,
  1070. },
  1071. { turnId: "turn-1" },
  1072. ),
  1073. );
  1074. gateway.ingest(
  1075. "session-1",
  1076. log.push(
  1077. SessionEventType.ModelComplete,
  1078. {
  1079. content: "private content",
  1080. stopReason: requestId === "request-tool-internal" ? "tool_internal" : "stop",
  1081. usage: { inputTokens: 64, outputTokens: 8 },
  1082. },
  1083. { turnId: "turn-1" },
  1084. ),
  1085. );
  1086. }
  1087. expect(host.telemetryFacts.filter((fact) => fact.kind === "usage.delta")).toEqual([
  1088. expect.objectContaining({
  1089. requestId: "request-main",
  1090. totalTokens: 72,
  1091. }),
  1092. ]);
  1093. });
  1094. it("main/subagent ModelComplete 关联最近完成 request 的真实模型与 usage", () => {
  1095. const host = makeHost();
  1096. const gateway = makeGateway(host);
  1097. const mainLog = new EventLog("session-1");
  1098. gateway.ingest(
  1099. "session-1",
  1100. mainLog.push(
  1101. SessionEventType.ModelNetworkStatus,
  1102. {
  1103. type: "model_request_completed",
  1104. timestamp: "2026-07-24T00:00:00.000Z",
  1105. traceId: "trace-main",
  1106. requestId: "request-main",
  1107. providerId: "main-provider",
  1108. modelId: "main-model",
  1109. baseURL: "https://main.example.com/v1/messages?secret=1",
  1110. transport: "sse",
  1111. querySource: "main_turn",
  1112. attempt: 1,
  1113. maxAttempts: 1,
  1114. durationMs: 20,
  1115. },
  1116. { turnId: "turn-main" },
  1117. ),
  1118. );
  1119. gateway.ingest(
  1120. "session-1",
  1121. mainLog.push(
  1122. SessionEventType.ModelComplete,
  1123. {
  1124. content: "main private content",
  1125. stopReason: "stop",
  1126. querySource: "main_turn",
  1127. usage: { inputTokens: 10, outputTokens: 4, totalTokens: 14 },
  1128. },
  1129. { turnId: "turn-main" },
  1130. ),
  1131. );
  1132. const childLog = new EventLog("child-session");
  1133. gateway.ingestDetachedLiveSession(
  1134. "child-session",
  1135. childLog.push(
  1136. SessionEventType.ModelNetworkStatus,
  1137. {
  1138. type: "model_request_completed",
  1139. timestamp: "2026-07-24T00:00:01.000Z",
  1140. traceId: "trace-child",
  1141. requestId: "request-child",
  1142. providerId: "child-provider",
  1143. modelId: "child-model",
  1144. baseURL: "https://child.example.com/v1/messages?secret=1",
  1145. transport: "sse",
  1146. querySource: "subagent",
  1147. attempt: 1,
  1148. maxAttempts: 1,
  1149. durationMs: 30,
  1150. },
  1151. { turnId: "turn-child" },
  1152. ),
  1153. );
  1154. gateway.ingestDetachedLiveSession(
  1155. "child-session",
  1156. childLog.push(
  1157. SessionEventType.ModelComplete,
  1158. {
  1159. content: "child private content",
  1160. stopReason: "stop",
  1161. querySource: "subagent",
  1162. usage: { inputTokens: 20, outputTokens: 5, totalTokens: 25 },
  1163. },
  1164. { turnId: "turn-child" },
  1165. ),
  1166. );
  1167. expect(host.telemetryFacts.filter((fact) => fact.kind === "usage.delta")).toEqual([
  1168. expect.objectContaining({
  1169. sessionId: "session-1",
  1170. requestId: "request-main",
  1171. providerId: "main-provider",
  1172. modelId: "main-model",
  1173. providerHostname: "main.example.com",
  1174. totalTokens: 14,
  1175. }),
  1176. expect.objectContaining({
  1177. sessionId: "child-session",
  1178. requestId: "request-child",
  1179. providerId: "child-provider",
  1180. modelId: "child-model",
  1181. providerHostname: "child.example.com",
  1182. totalTokens: 25,
  1183. }),
  1184. ]);
  1185. expect(JSON.stringify(host.telemetryFacts)).not.toContain("private content");
  1186. expect(JSON.stringify(host.telemetryFacts)).not.toContain("secret=1");
  1187. });
  1188. it("SubagentSpawned/Stopped 只透传父子关联和 background 状态", () => {
  1189. const host = makeHost();
  1190. const gateway = makeGateway(host);
  1191. const log = new EventLog();
  1192. gateway.ingest(
  1193. "session-1",
  1194. log.push(
  1195. SessionEventType.TurnStarted,
  1196. { inputId: "command-1", input: "private prompt" },
  1197. { turnId: "turn-1" },
  1198. ),
  1199. );
  1200. gateway.ingest(
  1201. "session-1",
  1202. log.push(
  1203. SessionEventType.SubagentSpawned,
  1204. {
  1205. agentId: "agent-1",
  1206. agentType: "explore",
  1207. childSessionId: "child-session-1",
  1208. parentToolCallId: "tool-agent-1",
  1209. background: false,
  1210. status: "running",
  1211. prompt: "private child prompt",
  1212. },
  1213. { turnId: "turn-1" },
  1214. ),
  1215. );
  1216. gateway.ingest(
  1217. "session-1",
  1218. log.push(
  1219. SessionEventType.SubagentStopped,
  1220. {
  1221. agentId: "agent-1",
  1222. agentType: "explore",
  1223. childSessionId: "child-session-1",
  1224. parentToolCallId: "tool-agent-1",
  1225. background: false,
  1226. status: "completed",
  1227. output: "private child output",
  1228. },
  1229. { turnId: "turn-1" },
  1230. ),
  1231. );
  1232. expect(host.telemetryFacts.filter((fact) => fact.kind === "subagent.lifecycle")).toEqual([
  1233. expect.objectContaining({
  1234. phase: "spawned",
  1235. sourceCommandId: "command-1",
  1236. childSessionId: "child-session-1",
  1237. parentToolCallId: "tool-agent-1",
  1238. background: false,
  1239. }),
  1240. expect.objectContaining({
  1241. phase: "stopped",
  1242. sourceCommandId: "command-1",
  1243. childSessionId: "child-session-1",
  1244. background: false,
  1245. }),
  1246. ]);
  1247. expect(JSON.stringify(host.telemetryFacts)).not.toContain("private child");
  1248. });
  1249. it("background stopped fact 保留既有 Runtime 错误但不透传结果正文", () => {
  1250. const host = makeHost();
  1251. const gateway = makeGateway(host);
  1252. const log = new EventLog();
  1253. gateway.ingest(
  1254. "session-1",
  1255. log.push(SessionEventType.SubagentStopped, {
  1256. agentId: "agent-bg",
  1257. childSessionId: "child-bg",
  1258. parentToolCallId: "tool-bg",
  1259. background: true,
  1260. status: "failed",
  1261. error: "provider returned 429",
  1262. output: "private child output",
  1263. }),
  1264. );
  1265. expect(host.telemetryFacts).toEqual([
  1266. expect.objectContaining({
  1267. kind: "subagent.lifecycle",
  1268. phase: "stopped",
  1269. background: true,
  1270. status: "failed",
  1271. errorMessage: "provider returned 429",
  1272. }),
  1273. ]);
  1274. expect(JSON.stringify(host.telemetryFacts)).not.toContain("private child output");
  1275. });
  1276. it("镜像 Subagent 工具从 payload 顶层透传 agent_id 与 child 关联", () => {
  1277. const host = makeHost();
  1278. const gateway = makeGateway(host);
  1279. const log = new EventLog("parent-session");
  1280. gateway.ingest(
  1281. "parent-session",
  1282. log.push(
  1283. SessionEventType.TurnStarted,
  1284. { inputId: "parent-command", input: "private prompt" },
  1285. { turnId: "parent-turn" },
  1286. ),
  1287. );
  1288. const relation = {
  1289. agentId: "agent-child",
  1290. agentType: "Explore",
  1291. childSessionId: "child-session",
  1292. childToolCallId: "toolu-child",
  1293. parentToolCallId: "call-parent-agent",
  1294. source: "subagent",
  1295. background: true,
  1296. };
  1297. gateway.ingest(
  1298. "parent-session",
  1299. log.push(
  1300. SessionEventType.ToolCallScheduled,
  1301. {
  1302. toolCallId: "tool_subagent_agent-child_toolu-child",
  1303. toolName: "WebFetch",
  1304. input: { secret: "must-not-leak" },
  1305. schedule: { parallelGroups: [], executionOrder: [] },
  1306. ...relation,
  1307. },
  1308. { turnId: "parent-turn" },
  1309. ),
  1310. );
  1311. gateway.ingest(
  1312. "parent-session",
  1313. log.push(
  1314. SessionEventType.ToolCallResult,
  1315. {
  1316. toolCallId: "tool_subagent_agent-child_toolu-child",
  1317. duration: 42,
  1318. result: { success: true, content: "private child tool output" },
  1319. ...relation,
  1320. },
  1321. { turnId: "parent-turn" },
  1322. ),
  1323. );
  1324. const toolFacts = host.telemetryFacts.filter(
  1325. (fact) => fact.kind === "tool.lifecycle" && fact.toolName === "WebFetch",
  1326. );
  1327. expect(toolFacts).toEqual([
  1328. expect.objectContaining({
  1329. phase: "scheduled",
  1330. agentId: "agent-child",
  1331. childSessionId: "child-session",
  1332. childToolCallId: "toolu-child",
  1333. parentToolCallId: "call-parent-agent",
  1334. background: true,
  1335. }),
  1336. expect.objectContaining({
  1337. phase: "completed",
  1338. agentId: "agent-child",
  1339. childSessionId: "child-session",
  1340. childToolCallId: "toolu-child",
  1341. parentToolCallId: "call-parent-agent",
  1342. background: true,
  1343. }),
  1344. ]);
  1345. expect(JSON.stringify(toolFacts)).not.toContain("must-not-leak");
  1346. expect(JSON.stringify(toolFacts)).not.toContain("private child tool output");
  1347. });
  1348. it("stream fact 保留 parentToolCallId 供主对话统计排除子代理正文", () => {
  1349. const host = makeHost();
  1350. const gateway = makeGateway(host);
  1351. const log = new EventLog();
  1352. gateway.ingest(
  1353. "session-1",
  1354. log.push(
  1355. SessionEventType.ModelStreaming,
  1356. {
  1357. kind: "text_delta",
  1358. delta: "child private content",
  1359. done: false,
  1360. parentToolCallId: "parent-agent-tool",
  1361. },
  1362. { turnId: "turn-1" },
  1363. ),
  1364. );
  1365. expect(host.telemetryFacts).toEqual([
  1366. expect.objectContaining({
  1367. kind: "stream.chunk",
  1368. chunkLength: 21,
  1369. parentToolCallId: "parent-agent-tool",
  1370. }),
  1371. ]);
  1372. expect(JSON.stringify(host.telemetryFacts)).not.toContain("child private content");
  1373. });
  1374. it("cancelled turn fact 保留旧 user interrupt 固定错误字段", () => {
  1375. const host = makeHost();
  1376. const gateway = makeGateway(host);
  1377. const log = new EventLog();
  1378. gateway.ingest(
  1379. "session-1",
  1380. log.push(
  1381. SessionEventType.TurnComplete,
  1382. {
  1383. resultType: "cancelled",
  1384. response: "",
  1385. duration: 10,
  1386. tokenCount: 0,
  1387. toolCallCount: 0,
  1388. },
  1389. { turnId: "turn-1" },
  1390. ),
  1391. );
  1392. expect(host.telemetryFacts).toEqual([
  1393. expect.objectContaining({
  1394. kind: "turn.terminal",
  1395. status: "interrupted",
  1396. errorCode: "USER_INTERRUPT",
  1397. errorMessage: "User stopped generation",
  1398. }),
  1399. ]);
  1400. });
  1401. it("turn terminal fact 保留 active-loop 消费的 subagent 来源标记", () => {
  1402. const host = makeHost();
  1403. const gateway = makeGateway(host);
  1404. const log = new EventLog();
  1405. gateway.ingest(
  1406. "session-1",
  1407. log.push(
  1408. SessionEventType.TurnComplete,
  1409. {
  1410. resultType: "success",
  1411. response: "",
  1412. duration: 10,
  1413. tokenCount: 0,
  1414. toolCallCount: 0,
  1415. backgroundSubagentResultConsumed: true,
  1416. },
  1417. { turnId: "turn-1" },
  1418. ),
  1419. );
  1420. expect(host.telemetryFacts).toEqual([
  1421. expect.objectContaining({
  1422. kind: "turn.terminal",
  1423. backgroundSubagentResultConsumed: true,
  1424. }),
  1425. ]);
  1426. });
  1427. it("turn error fact 保留 active-loop 消费的 subagent 来源标记", () => {
  1428. const host = makeHost();
  1429. const gateway = makeGateway(host);
  1430. const log = new EventLog();
  1431. gateway.ingest(
  1432. "session-1",
  1433. log.push(
  1434. SessionEventType.TurnError,
  1435. {
  1436. error: { type: "MODEL_ERROR", message: "failed" },
  1437. turnPhase: "regular_turn_loop",
  1438. backgroundSubagentResultConsumed: true,
  1439. },
  1440. { turnId: "turn-1" },
  1441. ),
  1442. );
  1443. expect(host.telemetryFacts).toEqual([
  1444. expect.objectContaining({
  1445. kind: "turn.terminal",
  1446. backgroundSubagentResultConsumed: true,
  1447. }),
  1448. ]);
  1449. });
  1450. it("compact terminal 在尚无 network status 时回落 session config 模型", () => {
  1451. const host = makeHost();
  1452. host.configSeeds.set("session-1", {
  1453. provider: "provider-from-config",
  1454. model: "model-from-config",
  1455. });
  1456. const gateway = makeGateway(host);
  1457. const log = new EventLog();
  1458. const compact = log.push(SessionEventType.CompactFailed, {
  1459. operationId: "compact-1",
  1460. messageId: "compact-message-1",
  1461. status: "failed",
  1462. trigger: "manual",
  1463. reason: "api_error",
  1464. attempt: 1,
  1465. startedAt: 100,
  1466. endedAt: 200,
  1467. });
  1468. gateway.ingest("session-1", compact);
  1469. expect(host.telemetryFacts).toEqual([
  1470. expect.objectContaining({
  1471. kind: "compaction.terminal",
  1472. modelName: "model-from-config",
  1473. modelProvider: "provider-from-config",
  1474. }),
  1475. ]);
  1476. });
  1477. it("persisted hydration 与 initial snapshot 不产生 telemetry fact", async () => {
  1478. const host = makeHost();
  1479. const gateway = makeGateway(host);
  1480. const log = new EventLog();
  1481. host.persistedEvents.set("session-1", [
  1482. sessionCreated(log),
  1483. log.push(
  1484. SessionEventType.TurnStarted,
  1485. { turnNumber: 1, input: "历史正文", inputId: "historical-command" },
  1486. { turnId: "turn-history" },
  1487. ),
  1488. ]);
  1489. await gateway.subscribe(subscribeParams());
  1490. expect(host.telemetryFacts).toEqual([]);
  1491. });
  1492. it("hydration await 窗口里的真实 live event 只发一次 fact", async () => {
  1493. const host = makeHost();
  1494. const gateway = makeGateway(host);
  1495. const log = new EventLog();
  1496. const created = sessionCreated(log);
  1497. let releaseLoad!: () => void;
  1498. let loadStarted = false;
  1499. const loadGate = new Promise<void>((resolve) => {
  1500. releaseLoad = resolve;
  1501. });
  1502. host.loadPersistedEventsImpl = async () => {
  1503. loadStarted = true;
  1504. await loadGate;
  1505. return { events: [created], synthesized: false, sourceEventSeq: created.sequenceNumber };
  1506. };
  1507. const subscribing = gateway.subscribe(subscribeParams());
  1508. await vi.waitFor(() => expect(loadStarted).toBe(true));
  1509. const live = log.push(
  1510. SessionEventType.TurnStarted,
  1511. { turnNumber: 1, input: "live", inputId: "live-command" },
  1512. { turnId: "turn-live" },
  1513. );
  1514. gateway.ingest("session-1", live);
  1515. releaseLoad();
  1516. await subscribing;
  1517. expect(host.telemetryFacts).toHaveLength(1);
  1518. expect(host.telemetryFacts[0]).toMatchObject({
  1519. kind: "turn.started",
  1520. eventId: String(live.id),
  1521. sourceCommandId: "live-command",
  1522. });
  1523. });
  1524. it("subscribes an existing live child publisher without cold-resuming a second runtime", async () => {
  1525. const host = makeHost();
  1526. const gateway = makeGateway(host);
  1527. const childLog = new EventLog("child-session");
  1528. gateway.ingestDetachedLiveSession("child-session", sessionCreated(childLog));
  1529. const subscribed = await gateway.subscribe(
  1530. subscribeParams({ topic: "conversation/child-session" }),
  1531. );
  1532. expect(subscribed.initialFrame).toMatchObject({
  1533. toSeq: 1,
  1534. payload: { kind: "snapshot" },
  1535. });
  1536. expect(host.resumeCalls).toEqual([]);
  1537. gateway.ingestDetachedLiveSession("child-session", textDelta(childLog, "live child delta"));
  1538. vi.advanceTimersByTime(CONTINUOUS_WINDOW);
  1539. expect(host.frames.at(-1)).toMatchObject({
  1540. toSeq: 2,
  1541. payload: { kind: "deltas" },
  1542. });
  1543. expect(host.resumeCalls).toEqual([]);
  1544. });
  1545. it("cold-resumes and hydrates a completed child when no live publisher remains", async () => {
  1546. const host = makeHost();
  1547. const gateway = makeGateway(host);
  1548. const childLog = new EventLog("completed-child");
  1549. host.resumeOutcome = "resumed";
  1550. host.persistedEvents.set("completed-child", [sessionCreated(childLog)]);
  1551. const subscribed = await gateway.subscribe(
  1552. subscribeParams({ topic: "conversation/completed-child" }),
  1553. );
  1554. expect(host.resumeCalls).toEqual(["completed-child"]);
  1555. expect(subscribed.initialFrame).toMatchObject({
  1556. toSeq: 1,
  1557. payload: { kind: "snapshot" },
  1558. });
  1559. });
  1560. it("plans query cold-resumes and hydrates the same authoritative branch", async () => {
  1561. const host = makeHost();
  1562. const gateway = makeGateway(host);
  1563. const sessionId = "completed-plan-session";
  1564. const log = new EventLog(sessionId);
  1565. const turnId = "turn-plan";
  1566. sessionCreated(log);
  1567. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "写计划" }, { turnId });
  1568. log.push(
  1569. SessionEventType.ModelStreaming,
  1570. {
  1571. kind: "tool_input_start",
  1572. delta: "",
  1573. done: false,
  1574. toolCallId: "cold-plan",
  1575. toolName: "ExitPlanMode",
  1576. },
  1577. { turnId },
  1578. );
  1579. log.push(
  1580. SessionEventType.ToolCallScheduled,
  1581. {
  1582. toolCallId: "cold-plan",
  1583. toolName: "ExitPlanMode",
  1584. input: { plan: "# 冷恢复计划" },
  1585. schedule: { parallelGroups: [["cold-plan"]], executionOrder: ["cold-plan"] },
  1586. },
  1587. { turnId },
  1588. );
  1589. log.push(
  1590. SessionEventType.ToolCallResult,
  1591. {
  1592. toolCallId: "cold-plan",
  1593. result: { success: true, content: "done" },
  1594. duration: 10,
  1595. },
  1596. { turnId },
  1597. );
  1598. log.push(
  1599. SessionEventType.TurnComplete,
  1600. {
  1601. response: "",
  1602. tokenCount: 0,
  1603. toolCallCount: 1,
  1604. duration: 20,
  1605. resultType: "success",
  1606. },
  1607. { turnId },
  1608. );
  1609. host.resumeOutcome = "resumed";
  1610. host.persistedEvents.set(sessionId, log.events);
  1611. const result = await gateway.plans({ sessionId });
  1612. expect(host.resumeCalls).toEqual([sessionId]);
  1613. expect(result.plans).toMatchObject([
  1614. {
  1615. toolCallId: "cold-plan",
  1616. toolName: "ExitPlanMode",
  1617. status: "success",
  1618. },
  1619. ]);
  1620. expect(result.atLogEpoch).toBeTruthy();
  1621. });
  1622. it("does not treat an unregistered orphan publisher as a live child", async () => {
  1623. const host = makeHost();
  1624. const gateway = makeGateway(host);
  1625. const orphanLog = new EventLog("orphan-session");
  1626. host.resumeOutcome = "resumed";
  1627. gateway.ingest("orphan-session", sessionCreated(orphanLog));
  1628. await gateway.subscribe(subscribeParams({ topic: "conversation/orphan-session" }));
  1629. expect(host.resumeCalls).toEqual(["orphan-session"]);
  1630. });
  1631. it("same-sub resync 保留 owner/subId 并按客户端 base 生成 recovery dispatch", async () => {
  1632. const host = makeHost();
  1633. const gateway = makeGateway(host);
  1634. const log = new EventLog();
  1635. gateway.ingest("session-1", sessionCreated(log));
  1636. const subscribed = await gateway.subscribe(subscribeParams({ connectionId: "mobile" }));
  1637. gateway.ingest("session-1", textDelta(log, "after-base"));
  1638. const recovered = await gateway.resyncReserved({
  1639. topic: "conversation/session-1",
  1640. connectionId: "mobile",
  1641. subscriptionId: subscribed.ack.subscriptionId,
  1642. base: { logEpoch: subscribed.ack.logEpoch, seq: 1 },
  1643. });
  1644. expect(recovered.ack).toEqual({
  1645. subscriptionId: subscribed.ack.subscriptionId,
  1646. mode: "resume",
  1647. logEpoch: subscribed.ack.logEpoch,
  1648. });
  1649. expect(recovered.initialFrame).toMatchObject({
  1650. subscriptionId: subscribed.ack.subscriptionId,
  1651. fromSeq: 1,
  1652. toSeq: 2,
  1653. payload: { kind: "deltas" },
  1654. });
  1655. expect(recovered.commit()).toBe(true);
  1656. expect(() =>
  1657. gateway.resyncReserved({
  1658. topic: "conversation/session-1",
  1659. connectionId: "forged",
  1660. subscriptionId: subscribed.ack.subscriptionId,
  1661. base: null,
  1662. }),
  1663. ).toThrow("fault.subscription.notOwned");
  1664. });
  1665. it("conversation recovery timer 在 control commit 前触发后,无新 ingest 也会重新 flush", async () => {
  1666. const host = makeHost();
  1667. const gateway = makeGateway(host);
  1668. const log = new EventLog();
  1669. gateway.ingest("session-1", sessionCreated(log));
  1670. const subscribed = await gateway.subscribe(subscribeParams());
  1671. const recovery = gateway.resyncReserved({
  1672. topic: "conversation/session-1",
  1673. connectionId: "conn-1",
  1674. subscriptionId: subscribed.ack.subscriptionId,
  1675. base: { logEpoch: subscribed.ack.logEpoch, seq: 1 },
  1676. });
  1677. gateway.ingest(
  1678. "session-1",
  1679. log.push(SessionEventType.SessionTitleUpdated, {
  1680. previousTitle: "",
  1681. source: "custom",
  1682. title: "during-recovery",
  1683. }),
  1684. );
  1685. // timer 已消费,但 control reservation 仍要等 ACK/outbox 全部 admission,不能抢发。
  1686. vi.advanceTimersByTime(CONTINUOUS_WINDOW);
  1687. expect(host.frames).toEqual([]);
  1688. expect(recovery.commit()).toBe(true);
  1689. // commit 必须重新驱动残留 buffer;这里刻意不再 ingest。
  1690. vi.advanceTimersByTime(CONTINUOUS_WINDOW);
  1691. expect(host.frames).toHaveLength(1);
  1692. expect(host.frames[0]).toMatchObject({
  1693. fromSeq: 1,
  1694. toSeq: 2,
  1695. payload: { kind: "deltas" },
  1696. });
  1697. });
  1698. it("initial physical encode 失败会回滚 conversation subscription 与 flush state", async () => {
  1699. const host = makeHost();
  1700. host.configSeeds.set("session-1", {
  1701. provider: "provider",
  1702. model: "x".repeat(17 * 1024 * 1024),
  1703. thought: "high",
  1704. mode: "default",
  1705. });
  1706. const gateway = makeGateway(host);
  1707. const log = new EventLog();
  1708. gateway.ingest("session-1", sessionCreated(log));
  1709. await expect(gateway.subscribeReserved(subscribeParams())).rejects.toThrow(
  1710. "proto.frameAssemblyTooLarge",
  1711. );
  1712. const internals = gateway as unknown as {
  1713. flushStates: Map<unknown, unknown>;
  1714. publishers: Map<string, { subscriptions: Map<unknown, unknown> }>;
  1715. };
  1716. expect(internals.flushStates.size).toBe(0);
  1717. expect(internals.publishers.get("session-1")?.subscriptions.size).toBe(0);
  1718. });
  1719. it("resync physical encode 失败不 admission,旧 online buffer 可继续 flush 后再重试", async () => {
  1720. const host = makeHost();
  1721. const gateway = makeGateway(host);
  1722. const log = new EventLog();
  1723. gateway.ingest("session-1", sessionCreated(log));
  1724. const subscribed = await gateway.subscribe(subscribeParams());
  1725. gateway.ingest(
  1726. "session-1",
  1727. log.push(SessionEventType.SessionTitleUpdated, {
  1728. title: "small-online-delta",
  1729. source: "custom",
  1730. }),
  1731. );
  1732. const publisher = (
  1733. gateway as unknown as {
  1734. publishers: Map<
  1735. string,
  1736. { seedConfig(seed: SessionConfigSeed): void; hasSubscription(id: string): boolean }
  1737. >;
  1738. }
  1739. ).publishers.get("session-1")!;
  1740. publisher.seedConfig({
  1741. provider: "provider",
  1742. model: "x".repeat(17 * 1024 * 1024),
  1743. thought: "high",
  1744. mode: "default",
  1745. });
  1746. expect(() =>
  1747. gateway.resyncReserved({
  1748. topic: "conversation/session-1",
  1749. connectionId: "conn-1",
  1750. subscriptionId: subscribed.ack.subscriptionId,
  1751. base: null,
  1752. forceSnapshot: true,
  1753. }),
  1754. ).toThrow("proto.frameAssemblyTooLarge");
  1755. expect(host.frames).toEqual([]);
  1756. expect(publisher.hasSubscription(subscribed.ack.subscriptionId)).toBe(true);
  1757. vi.advanceTimersByTime(CONTINUOUS_WINDOW);
  1758. expect(host.frames).toHaveLength(1);
  1759. expect(host.frames[0]).toMatchObject({
  1760. subscriptionId: subscribed.ack.subscriptionId,
  1761. payload: { kind: "deltas" },
  1762. });
  1763. publisher.seedConfig({
  1764. provider: "provider",
  1765. model: "small",
  1766. thought: "high",
  1767. mode: "default",
  1768. });
  1769. const retry = gateway.resyncReserved({
  1770. topic: "conversation/session-1",
  1771. connectionId: "conn-1",
  1772. subscriptionId: subscribed.ack.subscriptionId,
  1773. base: null,
  1774. forceSnapshot: true,
  1775. });
  1776. expect(retry.ack.subscriptionId).toBe(subscribed.ack.subscriptionId);
  1777. expect(retry.commit()).toBe(true);
  1778. });
  1779. it("oversize structural event 在 ingest 原子拒绝,re-subscribe 返回最后可传输 snapshot", async () => {
  1780. const host = makeHost();
  1781. const gateway = makeGateway(host);
  1782. const log = new EventLog();
  1783. gateway.ingest("session-1", sessionCreated(log));
  1784. const first = await gateway.subscribe(subscribeParams());
  1785. gateway.ingest(
  1786. "session-1",
  1787. log.push(SessionEventType.SessionTitleUpdated, {
  1788. title: "x".repeat(17 * 1024 * 1024),
  1789. source: "custom",
  1790. }),
  1791. );
  1792. const retry = await gateway.subscribeReserved(subscribeParams());
  1793. expect(retry.initialFrame?.payload).toMatchObject({
  1794. kind: "snapshot",
  1795. snapshot: { meta: { title: "" } },
  1796. });
  1797. const internals = gateway as unknown as {
  1798. flushStates: Map<unknown, { subscriptionId: string }>;
  1799. publishers: Map<
  1800. string,
  1801. { hasSubscription(subscriptionId: string, connectionId?: string): boolean }
  1802. >;
  1803. };
  1804. expect(
  1805. internals.publishers.get("session-1")?.hasSubscription(first.ack.subscriptionId, "conn-1"),
  1806. ).toBe(false);
  1807. expect([...internals.flushStates.values()].map((state) => state.subscriptionId)).toEqual([
  1808. retry.ack.subscriptionId,
  1809. ]);
  1810. });
  1811. it("ingest 后按 flushWindowMs 合并打到 physical wire,帧区间无缝衔接", async () => {
  1812. const host = makeHost();
  1813. const gateway = makeGateway(host);
  1814. const log = new EventLog();
  1815. gateway.ingest("session-1", sessionCreated(log));
  1816. const { initialFrame: initial } = await gateway.subscribe(subscribeParams());
  1817. gateway.ingest(
  1818. "session-1",
  1819. log.push(
  1820. SessionEventType.TurnStarted,
  1821. { turnNumber: 1, input: "任务 1" },
  1822. { turnId: "turn-1" },
  1823. ),
  1824. );
  1825. gateway.ingest("session-1", textDelta(log, "上半"));
  1826. gateway.ingest("session-1", textDelta(log, " 下半"));
  1827. // 窗口未到不产帧。
  1828. expect(host.frames).toHaveLength(0);
  1829. vi.advanceTimersByTime(CONTINUOUS_WINDOW);
  1830. // 三个事件合并成一帧,fromSeq 接住 snapshot 帧的 toSeq。
  1831. expect(host.frames).toHaveLength(1);
  1832. expect(host.frames[0]!.fromSeq).toBe(initial!.toSeq);
  1833. expect(host.frames[0]!.toSeq).toBe(4);
  1834. // 后续 ingest 重新开窗。
  1835. gateway.ingest("session-1", textDelta(log, "尾巴"));
  1836. vi.advanceTimersByTime(CONTINUOUS_WINDOW);
  1837. expect(host.frames).toHaveLength(2);
  1838. expect(host.frames[1]!.fromSeq).toBe(host.frames[0]!.toSeq);
  1839. });
  1840. it("host clientMode 固定 desktop continuous / mobile replayable 调度边界", async () => {
  1841. const host = makeHost();
  1842. const gateway = makeGateway(host);
  1843. const log = new EventLog();
  1844. gateway.ingest("session-1", sessionCreated(log));
  1845. const desktop = await gateway.subscribe(subscribeParams({ connectionId: "desktop-a" }));
  1846. const mobile = await gateway.subscribe(
  1847. subscribeParams({
  1848. connectionId: "mobile-b",
  1849. clientMode: "web-remote-replayable",
  1850. }),
  1851. );
  1852. gateway.ingest("session-1", textDelta(log, "跨端"));
  1853. vi.advanceTimersByTime(CONTINUOUS_WINDOW);
  1854. expect(host.frames.map((frame) => frame.subscriptionId)).toEqual([desktop.ack.subscriptionId]);
  1855. vi.advanceTimersByTime(REPLAYABLE_WINDOW - CONTINUOUS_WINDOW);
  1856. expect(host.frames.map((frame) => frame.subscriptionId)).toEqual([
  1857. desktop.ack.subscriptionId,
  1858. mobile.ack.subscriptionId,
  1859. ]);
  1860. });
  1861. it("saturated mobile pauses only its connection and drained catches up immediately", async () => {
  1862. const host = makeHost();
  1863. const gateway = makeGateway(host);
  1864. const log = new EventLog();
  1865. gateway.ingest("session-1", sessionCreated(log));
  1866. const desktop = await gateway.subscribe(
  1867. subscribeParams({ connectionId: "desktop-a", clientMode: "desktop-continuous" }),
  1868. );
  1869. const mobile = await gateway.subscribe(
  1870. subscribeParams({
  1871. connectionId: "mobile-b",
  1872. clientMode: "web-remote-replayable",
  1873. }),
  1874. );
  1875. gateway.setConnectionFlowState({ connectionId: "mobile-b", state: "saturated" });
  1876. gateway.ingest("session-1", textDelta(log, "while-mobile-paused"));
  1877. vi.advanceTimersByTime(REPLAYABLE_WINDOW);
  1878. expect(host.frames.map((frame) => frame.subscriptionId)).toEqual([desktop.ack.subscriptionId]);
  1879. gateway.setConnectionFlowState({ connectionId: "mobile-b", state: "drained" });
  1880. expect(host.frames.map((frame) => frame.subscriptionId)).toEqual([
  1881. desktop.ack.subscriptionId,
  1882. mobile.ack.subscriptionId,
  1883. ]);
  1884. expect(host.frames[1]).toMatchObject({
  1885. fromSeq: 1,
  1886. toSeq: 2,
  1887. payload: { kind: "deltas" },
  1888. });
  1889. });
  1890. it("saturated clears an already scheduled timer and closed clears pause state", async () => {
  1891. const host = makeHost();
  1892. const gateway = makeGateway(host);
  1893. const log = new EventLog();
  1894. gateway.ingest("session-1", sessionCreated(log));
  1895. await gateway.subscribe(
  1896. subscribeParams({
  1897. connectionId: "mobile-race",
  1898. clientMode: "web-remote-replayable",
  1899. }),
  1900. );
  1901. gateway.ingest("session-1", textDelta(log, "scheduled"));
  1902. gateway.setConnectionFlowState({ connectionId: "mobile-race", state: "saturated" });
  1903. vi.advanceTimersByTime(REPLAYABLE_WINDOW * 2);
  1904. expect(host.frames).toEqual([]);
  1905. gateway.setConnectionFlowState({ connectionId: "mobile-race", state: "closed" });
  1906. const paused = (gateway as unknown as { pausedConnections: Set<string> }).pausedConnections;
  1907. expect(paused.has("mobile-race")).toBe(false);
  1908. });
  1909. it("paused mobile overflow recovers with one latest snapshot while desktop keeps draining", async () => {
  1910. const host = makeHost();
  1911. const gateway = makeGateway(host);
  1912. const log = new EventLog();
  1913. gateway.ingest("session-1", sessionCreated(log));
  1914. const desktop = await gateway.subscribe(
  1915. subscribeParams({ connectionId: "desktop-overflow", clientMode: "desktop-continuous" }),
  1916. );
  1917. const mobile = await gateway.subscribe(
  1918. subscribeParams({
  1919. connectionId: "mobile-overflow",
  1920. clientMode: "web-remote-replayable",
  1921. }),
  1922. );
  1923. gateway.setConnectionFlowState({ connectionId: "mobile-overflow", state: "saturated" });
  1924. for (let index = 0; index < 501; index += 1) {
  1925. gateway.ingest(
  1926. "session-1",
  1927. log.push(
  1928. SessionEventType.TurnStarted,
  1929. { turnNumber: index + 1, input: `queued-${index}` },
  1930. { turnId: `turn-overflow-${index}` },
  1931. ),
  1932. );
  1933. vi.advanceTimersByTime(CONTINUOUS_WINDOW);
  1934. }
  1935. const desktopFrames = host.frames.filter(
  1936. (frame) => frame.subscriptionId === desktop.ack.subscriptionId,
  1937. );
  1938. expect(desktopFrames.length).toBeGreaterThan(0);
  1939. expect(
  1940. host.frames.filter((frame) => frame.subscriptionId === mobile.ack.subscriptionId),
  1941. ).toEqual([]);
  1942. gateway.setConnectionFlowState({ connectionId: "mobile-overflow", state: "drained" });
  1943. const mobileFrames = host.frames.filter(
  1944. (frame) => frame.subscriptionId === mobile.ack.subscriptionId,
  1945. );
  1946. expect(mobileFrames).toHaveLength(1);
  1947. expect(mobileFrames[0]).toMatchObject({
  1948. fromSeq: 0,
  1949. payload: { kind: "snapshot" },
  1950. });
  1951. });
  1952. it("非法 topic / 未知会话拒绝订阅", async () => {
  1953. const host = makeHost();
  1954. const gateway = makeGateway(host);
  1955. await expect(gateway.subscribe(subscribeParams({ topic: "bogus" }))).rejects.toThrow(
  1956. /Unsupported topic/,
  1957. );
  1958. await expect(
  1959. gateway.subscribe(subscribeParams({ topic: "conversation/ghost" })),
  1960. ).rejects.toThrow(/not active/);
  1961. });
  1962. it("重订阅替换(R-01):旧订阅停止产帧且调度状态被清理", async () => {
  1963. const host = makeHost();
  1964. const gateway = makeGateway(host);
  1965. const log = new EventLog();
  1966. gateway.ingest("session-1", sessionCreated(log));
  1967. const first = await gateway.subscribe(subscribeParams());
  1968. const second = await gateway.subscribe(subscribeParams());
  1969. expect(second.ack.subscriptionId).not.toBe(first.ack.subscriptionId);
  1970. // 旧订阅的调度状态已清(flushNow 找不到),新订阅正常。
  1971. expect(gateway.flushNow(first.ack.subscriptionId)).toBeNull();
  1972. gateway.ingest("session-1", textDelta(log, "x"));
  1973. vi.advanceTimersByTime(CONTINUOUS_WINDOW);
  1974. expect(host.frames).toHaveLength(1);
  1975. expect(host.frames[0]!.subscriptionId).toBe(second.ack.subscriptionId);
  1976. });
  1977. it("unsubscribe 后不再产帧", async () => {
  1978. const host = makeHost();
  1979. const gateway = makeGateway(host);
  1980. const log = new EventLog();
  1981. gateway.ingest("session-1", sessionCreated(log));
  1982. const { ack } = await gateway.subscribe(subscribeParams());
  1983. gateway.unsubscribe({
  1984. topic: "conversation/session-1",
  1985. subscriptionId: ack.subscriptionId,
  1986. connectionId: "conn-1",
  1987. });
  1988. gateway.ingest("session-1", textDelta(log, "x"));
  1989. vi.advanceTimersByTime(CONTINUOUS_WINDOW * 4);
  1990. expect(host.frames).toHaveLength(0);
  1991. });
  1992. it("相同裸 subscriptionId 的不同 topic/connection 只退订精确 route", async () => {
  1993. const host = makeHost();
  1994. host.sessions.add("session-2");
  1995. const gateway = makeGateway(host);
  1996. const firstLog = new EventLog("session-1");
  1997. const secondLog = new EventLog("session-2");
  1998. gateway.ingest("session-1", sessionCreated(firstLog));
  1999. gateway.ingest("session-2", sessionCreated(secondLog));
  2000. const first = await gateway.subscribe(
  2001. subscribeParams({
  2002. topic: "conversation/session-1",
  2003. connectionId: "conn-1",
  2004. }),
  2005. );
  2006. const second = await gateway.subscribe(
  2007. subscribeParams({
  2008. topic: "conversation/session-2",
  2009. connectionId: "conn-2",
  2010. }),
  2011. );
  2012. expect(first.ack.subscriptionId).toBe(second.ack.subscriptionId);
  2013. gateway.unsubscribe({
  2014. topic: "conversation/session-1",
  2015. subscriptionId: first.ack.subscriptionId,
  2016. connectionId: "conn-1",
  2017. });
  2018. gateway.ingest("session-1", textDelta(firstLog, "first"));
  2019. gateway.ingest("session-2", textDelta(secondLog, "second"));
  2020. vi.advanceTimersByTime(CONTINUOUS_WINDOW);
  2021. expect(host.frames).toHaveLength(1);
  2022. expect(host.frames[0]).toMatchObject({
  2023. topic: "conversation/session-2",
  2024. subscriptionId: second.ack.subscriptionId,
  2025. });
  2026. });
  2027. it("disposeSession 清理全部订阅与 publisher;重订阅走冷启动 snapshot", async () => {
  2028. const host = makeHost();
  2029. const gateway = makeGateway(host);
  2030. const log = new EventLog();
  2031. gateway.ingest("session-1", sessionCreated(log));
  2032. await gateway.subscribe(subscribeParams());
  2033. gateway.ingest("session-1", textDelta(log, "x"));
  2034. gateway.disposeSession("session-1");
  2035. vi.advanceTimersByTime(CONTINUOUS_WINDOW * 4);
  2036. expect(host.frames).toHaveLength(0);
  2037. // 新 publisher 冷启动:seq 从 0 开始(旧事件日志已随 dispose 丢弃)。
  2038. const again = await gateway.subscribe(subscribeParams());
  2039. expect(again.initialFrame?.toSeq).toBe(0);
  2040. });
  2041. // ── M4 hydration:冷订阅从持久化事件重建投影(fork child / resume / 重启)──
  2042. it("冷订阅无 live projection 的会话 → 重放持久化事件,snapshot 含历史 rows", async () => {
  2043. const host = makeHost();
  2044. // 构造一段持久化历史:SessionCreated + turn + assistant 文本。
  2045. const persistLog = new EventLog("session-cold");
  2046. host.sessions.add("session-cold");
  2047. persistLog.push(SessionEventType.SessionCreated, {
  2048. mode: "default",
  2049. contextWindow: 200_000,
  2050. });
  2051. persistLog.push(
  2052. SessionEventType.TurnStarted,
  2053. { turnNumber: 1, input: "历史输入" },
  2054. { turnId: "turn-1" },
  2055. );
  2056. persistLog.push(
  2057. SessionEventType.ModelStreaming,
  2058. { kind: "text_start", delta: "", done: false },
  2059. { turnId: "turn-1" },
  2060. );
  2061. persistLog.push(
  2062. SessionEventType.ModelStreaming,
  2063. { kind: "text_delta", delta: "历史回复", done: false },
  2064. { turnId: "turn-1" },
  2065. );
  2066. persistLog.push(
  2067. SessionEventType.ModelStreaming,
  2068. { kind: "text_end", delta: "", done: false },
  2069. { turnId: "turn-1" },
  2070. );
  2071. host.persistedEvents.set("session-cold", persistLog.events);
  2072. const gateway = makeGateway(host);
  2073. // 从未 ingest 过 session-cold(冷)——subscribe 触发 hydration。
  2074. const result = await gateway.subscribe(subscribeParams({ topic: "conversation/session-cold" }));
  2075. expect(result.initialFrame?.payload.kind).toBe("snapshot");
  2076. const snapshot =
  2077. result.initialFrame?.payload.kind === "snapshot"
  2078. ? result.initialFrame.payload.snapshot
  2079. : null;
  2080. const texts = snapshot?.rows.window.map((row) =>
  2081. row.kind === "userInput" || row.kind === "assistantText" ? row.text : "",
  2082. );
  2083. expect(texts).toContain("历史输入");
  2084. expect(texts).toContain("历史回复");
  2085. // 冷订阅 seq 已推进到持久化尾部。
  2086. expect(result.initialFrame?.toSeq).toBe(persistLog.events.length);
  2087. });
  2088. it("synthesized=true:cold publisher(fork resume ingest 抢先建)→ 重建含 transcript 历史", async () => {
  2089. const host = makeHost();
  2090. host.sessions.add("session-fork");
  2091. host.synthesizedSessions.add("session-fork");
  2092. // 模拟 fork resume 的 ingest 抢先建了个只含 fork 事件的 cold publisher(无 user 轮)。
  2093. const gateway = makeGateway(host);
  2094. const forkLog = new EventLog("session-fork");
  2095. gateway.ingest("session-fork", {
  2096. ...forkLog.push(SessionEventType.SessionCreated, {
  2097. mode: "default",
  2098. contextWindow: 200_000,
  2099. }),
  2100. });
  2101. // transcript 合成的历史事件(loadPersistedEvents 返回,synthesized=true)。
  2102. const synthLog = new EventLog("session-fork");
  2103. synthLog.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  2104. synthLog.push(
  2105. SessionEventType.TurnStarted,
  2106. { turnNumber: 1, input: "继承历史" },
  2107. { turnId: "t1" },
  2108. );
  2109. synthLog.push(
  2110. SessionEventType.ModelStreaming,
  2111. { kind: "text_delta", delta: "继承回复", done: false },
  2112. { turnId: "t1" },
  2113. );
  2114. synthLog.push(
  2115. SessionEventType.ModelStreaming,
  2116. { kind: "text_end", delta: "", done: false },
  2117. { turnId: "t1" },
  2118. );
  2119. host.persistedEvents.set("session-fork", synthLog.events);
  2120. const result = await gateway.subscribe(subscribeParams({ topic: "conversation/session-fork" }));
  2121. const texts = (
  2122. result.initialFrame?.payload.kind === "snapshot"
  2123. ? result.initialFrame.payload.snapshot.rows.window
  2124. : []
  2125. )
  2126. .filter((r) => r.kind === "userInput" || r.kind === "assistantText")
  2127. .map((r) => (r.kind === "userInput" || r.kind === "assistantText" ? r.text : ""));
  2128. // cold publisher 被丢弃重建 → transcript 历史进投影。
  2129. expect(texts).toContain("继承历史");
  2130. expect(texts).toContain("继承回复");
  2131. });
  2132. it("synthesized rehydrate keeps existing subscription ownership", async () => {
  2133. const host = makeHost();
  2134. const gateway = makeGateway(host);
  2135. const rawLog = new EventLog("session-1");
  2136. gateway.ingest(
  2137. "session-1",
  2138. rawLog.push(SessionEventType.SessionCreated, {
  2139. mode: "default",
  2140. contextWindow: 200_000,
  2141. }),
  2142. );
  2143. const persisted = new EventLog("session-1");
  2144. persisted.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 200_000 });
  2145. persisted.push(
  2146. SessionEventType.TurnStarted,
  2147. { turnNumber: 1, input: "persisted question", messageId: "persisted-user" },
  2148. { turnId: "persisted-turn" },
  2149. );
  2150. persisted.push(
  2151. SessionEventType.ModelStreaming,
  2152. {
  2153. kind: "text_start",
  2154. delta: "",
  2155. done: false,
  2156. assistantMessageId: "persisted-assistant",
  2157. },
  2158. { turnId: "persisted-turn" },
  2159. );
  2160. persisted.push(
  2161. SessionEventType.ModelStreaming,
  2162. {
  2163. kind: "text_delta",
  2164. delta: "persisted answer",
  2165. done: false,
  2166. assistantMessageId: "persisted-assistant",
  2167. },
  2168. { turnId: "persisted-turn" },
  2169. );
  2170. persisted.push(
  2171. SessionEventType.TurnComplete,
  2172. { response: "", tokenCount: 0, toolCallCount: 0, duration: 1, resultType: "success" },
  2173. { turnId: "persisted-turn" },
  2174. );
  2175. let loadCount = 0;
  2176. host.loadPersistedEventsImpl = async () => {
  2177. loadCount += 1;
  2178. return loadCount === 1
  2179. ? { events: [], synthesized: false, sourceEventSeq: 1 }
  2180. : { events: persisted.events, synthesized: true, sourceEventSeq: 2 };
  2181. };
  2182. const first = await gateway.subscribe(subscribeParams({ connectionId: "conn-1" }));
  2183. // 非 running publisher 拒收正文后必须以 persisted source 重物化;该路径过去
  2184. // delete/replace publisher,导致 conn-1 的 subscription registry 一并丢失。
  2185. gateway.ingest(
  2186. "session-1",
  2187. rawLog.push(
  2188. SessionEventType.ModelStreaming,
  2189. {
  2190. kind: "text_delta",
  2191. delta: "missed live content",
  2192. done: false,
  2193. assistantMessageId: "missed-assistant",
  2194. },
  2195. { turnId: "missed-turn" },
  2196. ),
  2197. );
  2198. host.frames.length = 0;
  2199. const second = await gateway.subscribe(subscribeParams({ connectionId: "conn-2" }));
  2200. const secondRows =
  2201. second.initialFrame?.payload.kind === "snapshot"
  2202. ? second.initialFrame.payload.snapshot.rows.window
  2203. : [];
  2204. expect(
  2205. secondRows.some((row) => row.kind === "assistantText" && row.text === "persisted answer"),
  2206. ).toBe(true);
  2207. expect(host.frames).toEqual(
  2208. expect.arrayContaining([
  2209. expect.objectContaining({ subscriptionId: first.ack.subscriptionId }),
  2210. ]),
  2211. );
  2212. host.frames.length = 0;
  2213. const titleChanged = rawLog.push(SessionEventType.SessionTitleUpdated, {
  2214. previousTitle: "old",
  2215. title: "new",
  2216. source: "custom",
  2217. });
  2218. gateway.ingest("session-1", { ...titleChanged, id: "raw-title-changed" as EventId });
  2219. vi.advanceTimersByTime(CONTINUOUS_WINDOW);
  2220. expect(host.frames).toEqual(
  2221. expect.arrayContaining([
  2222. expect.objectContaining({ subscriptionId: first.ack.subscriptionId }),
  2223. ]),
  2224. );
  2225. });
  2226. it("首次 cold hydration 等待期间到达的 live queue/stream 不丢失,后续 topic seq 仍单调", async () => {
  2227. const host = makeHost();
  2228. const gateway = makeGateway(host);
  2229. const rawLog = new EventLog("session-race");
  2230. host.sessions.add("session-race");
  2231. gateway.ingest(
  2232. "session-race",
  2233. rawLog.push(SessionEventType.SessionCreated, {
  2234. mode: "default",
  2235. contextWindow: 200_000,
  2236. }),
  2237. );
  2238. let resolveLoad:
  2239. | ((value: { events: SessionEvent[]; synthesized: boolean; sourceEventSeq?: number }) => void)
  2240. | undefined;
  2241. const loadStarted = vi.fn();
  2242. host.loadPersistedEventsImpl = async () => {
  2243. loadStarted();
  2244. return await new Promise((resolve) => {
  2245. resolveLoad = resolve;
  2246. });
  2247. };
  2248. const subscribing = gateway.subscribe(subscribeParams({ topic: "conversation/session-race" }));
  2249. await vi.waitFor(() => expect(loadStarted).toHaveBeenCalledTimes(1));
  2250. const secondSubscribing = gateway.subscribe(
  2251. subscribeParams({ topic: "conversation/session-race", connectionId: "conn-2" }),
  2252. );
  2253. expect(loadStarted).toHaveBeenCalledTimes(1);
  2254. gateway.ingest(
  2255. "session-race",
  2256. rawLog.push(SessionEventType.TurnSteerQueued, {
  2257. pendingInputId: "queue-live",
  2258. intent: {
  2259. sourceCommandId: "cmd-live",
  2260. queueItemId: "queue-live",
  2261. clientId: "client-live",
  2262. kind: "sendText",
  2263. text: "等待期间排队",
  2264. attachments: [],
  2265. delivery: { requested: "queue", admitted: "queue" },
  2266. order: { admissionSeq: 1, queuePosition: 0 },
  2267. steer: { state: "notRequested" },
  2268. dispatch: { state: "queued" },
  2269. admittedAt: 1_700_000_001_000,
  2270. },
  2271. }),
  2272. );
  2273. gateway.ingest(
  2274. "session-race",
  2275. rawLog.push(
  2276. SessionEventType.TurnStarted,
  2277. { turnNumber: 2, input: "等待期间运行", messageId: "msg-live-user" },
  2278. { turnId: "turn-live" },
  2279. ),
  2280. );
  2281. gateway.ingest(
  2282. "session-race",
  2283. rawLog.push(
  2284. SessionEventType.ModelStreaming,
  2285. { kind: "text_start", delta: "", done: false, messageId: "msg-live-assistant" },
  2286. { turnId: "turn-live" },
  2287. ),
  2288. );
  2289. gateway.ingest(
  2290. "session-race",
  2291. rawLog.push(
  2292. SessionEventType.ModelStreaming,
  2293. { kind: "text_delta", delta: "live-1", done: false, messageId: "msg-live-assistant" },
  2294. { turnId: "turn-live" },
  2295. ),
  2296. );
  2297. const synthesizedLog = new EventLog("session-race");
  2298. synthesizedLog.push(SessionEventType.SessionCreated, {
  2299. mode: "default",
  2300. contextWindow: 200_000,
  2301. });
  2302. synthesizedLog.push(
  2303. SessionEventType.TurnStarted,
  2304. { turnNumber: 1, input: "历史输入", messageId: "msg-history-user" },
  2305. { turnId: "turn-history" },
  2306. );
  2307. synthesizedLog.push(
  2308. SessionEventType.ModelStreaming,
  2309. { kind: "text_start", delta: "", done: false, messageId: "msg-history-assistant" },
  2310. { turnId: "turn-history" },
  2311. );
  2312. synthesizedLog.push(
  2313. SessionEventType.ModelStreaming,
  2314. { kind: "text_delta", delta: "历史回复", done: false, messageId: "msg-history-assistant" },
  2315. { turnId: "turn-history" },
  2316. );
  2317. synthesizedLog.push(
  2318. SessionEventType.ModelStreaming,
  2319. { kind: "text_end", delta: "", done: false, messageId: "msg-history-assistant" },
  2320. { turnId: "turn-history" },
  2321. );
  2322. resolveLoad?.({
  2323. events: synthesizedLog.events.map((event, index) => ({
  2324. ...event,
  2325. id: `hydrate-race-${index + 1}` as EventId,
  2326. })),
  2327. synthesized: true,
  2328. // memory eventStore 在 load 开始时只看到了 SessionCreated;后四条是 await 窗口内 live。
  2329. sourceEventSeq: 1,
  2330. });
  2331. const subscribed = await subscribing;
  2332. const secondSubscribed = await secondSubscribing;
  2333. expect(secondSubscribed.initialFrame?.toSeq).toBe(subscribed.initialFrame?.toSeq);
  2334. const snapshot =
  2335. subscribed.initialFrame?.payload.kind === "snapshot"
  2336. ? subscribed.initialFrame.payload.snapshot
  2337. : null;
  2338. expect(snapshot?.queue.items.map((item) => item.queueItemId)).toContain("queue-live");
  2339. expect(
  2340. snapshot?.rows.window.filter((row) => row.kind === "assistantText").map((row) => row.text),
  2341. ).toEqual(expect.arrayContaining(["历史回复", "live-1"]));
  2342. const initialSeq = subscribed.initialFrame?.toSeq ?? -1;
  2343. gateway.ingest(
  2344. "session-race",
  2345. rawLog.push(
  2346. SessionEventType.ModelStreaming,
  2347. { kind: "text_delta", delta: "live-2", done: false, messageId: "msg-live-assistant" },
  2348. { turnId: "turn-live" },
  2349. ),
  2350. );
  2351. vi.advanceTimersByTime(CONTINUOUS_WINDOW);
  2352. expect(host.frames.at(-1)).toMatchObject({
  2353. fromSeq: initialSeq,
  2354. toSeq: initialSeq + 1,
  2355. payload: { kind: "deltas" },
  2356. });
  2357. const frameCountBeforeOutOfOrder = host.frames.length;
  2358. const lateQueue = rawLog.push(SessionEventType.TurnSteerQueued, {
  2359. pendingInputId: "queue-late",
  2360. input: "sqlite 较慢的入队",
  2361. inputPreview: "sqlite 较慢的入队",
  2362. inputSize: 21,
  2363. queueLength: 2,
  2364. targetTurnId: "turn-live",
  2365. });
  2366. const laterStream = rawLog.push(
  2367. SessionEventType.ModelStreaming,
  2368. { kind: "text_delta", delta: "live-3", done: false, messageId: "msg-live-assistant" },
  2369. { turnId: "turn-live" },
  2370. );
  2371. // runtime 先给事件编号,各事件的持久化 await 会让 notify sink 乱序;
  2372. // N+1 不能推进高水位后把迟到的 queue N 当成 duplicate 丢掉。
  2373. gateway.ingest("session-race", laterStream);
  2374. vi.advanceTimersByTime(CONTINUOUS_WINDOW);
  2375. expect(host.frames).toHaveLength(frameCountBeforeOutOfOrder);
  2376. gateway.ingest("session-race", lateQueue);
  2377. vi.advanceTimersByTime(CONTINUOUS_WINDOW);
  2378. expect(gateway.getQueueItem("session-race", "queue-late")?.text).toBe("sqlite 较慢的入队");
  2379. expect(host.frames.at(-1)).toMatchObject({
  2380. fromSeq: initialSeq + 1,
  2381. toSeq: initialSeq + 3,
  2382. payload: { kind: "deltas" },
  2383. });
  2384. });
  2385. it("synthesized hydration 不应让 source 水位与 live 水位之间的事件形成永久 gap", async () => {
  2386. const host = makeHost();
  2387. host.sessions.add("session-hydration-boundary-gap");
  2388. const gateway = makeGateway(host);
  2389. const rawLog = new EventLog("session-hydration-boundary-gap");
  2390. const created = rawLog.push(SessionEventType.SessionCreated, {
  2391. mode: "default",
  2392. contextWindow: 200_000,
  2393. });
  2394. gateway.ingest("session-hydration-boundary-gap", created);
  2395. gateway.ingest(
  2396. "session-hydration-boundary-gap",
  2397. rawLog.push(
  2398. SessionEventType.TurnStarted,
  2399. { turnNumber: 1, input: "live turn before hydration" },
  2400. { turnId: "turn-live" },
  2401. ),
  2402. );
  2403. let releaseLoad:
  2404. | ((value: { events: SessionEvent[]; synthesized: boolean; sourceEventSeq?: number }) => void)
  2405. | undefined;
  2406. const loadStarted = vi.fn();
  2407. host.loadPersistedEventsImpl = async () => {
  2408. loadStarted();
  2409. return await new Promise((resolve) => {
  2410. releaseLoad = resolve;
  2411. });
  2412. };
  2413. const subscribing = gateway.subscribe(
  2414. subscribeParams({ topic: "conversation/session-hydration-boundary-gap" }),
  2415. );
  2416. await vi.waitFor(() => expect(loadStarted).toHaveBeenCalledTimes(1));
  2417. gateway.ingest(
  2418. "session-hydration-boundary-gap",
  2419. rawLog.push(
  2420. SessionEventType.SubagentSpawned,
  2421. {
  2422. agentId: "agent-live",
  2423. agentType: "general-purpose",
  2424. background: true,
  2425. childSessionId: "session-child-live",
  2426. description: "live Agent during hydration",
  2427. parentToolCallId: "tool-agent-live",
  2428. status: "running",
  2429. },
  2430. { turnId: "turn-live" },
  2431. ),
  2432. );
  2433. releaseLoad?.({
  2434. events: [created],
  2435. synthesized: true,
  2436. // 持久读取只覆盖 seq=1;seq=2 已在 hydration 开始前进入 live publisher。
  2437. sourceEventSeq: 1,
  2438. });
  2439. const subscribed = await subscribing;
  2440. const snapshot =
  2441. subscribed.initialFrame?.payload.kind === "snapshot"
  2442. ? subscribed.initialFrame.payload.snapshot
  2443. : null;
  2444. expect(snapshot?.subagents.running).toEqual([
  2445. expect.objectContaining({
  2446. agentId: "agent-live",
  2447. childSessionId: "session-child-live",
  2448. }),
  2449. ]);
  2450. });
  2451. it("已有 live projection 的会话订阅 → 跳过 hydration,不双计", async () => {
  2452. const host = makeHost();
  2453. const gateway = makeGateway(host);
  2454. const log = new EventLog();
  2455. gateway.ingest("session-1", sessionCreated(log));
  2456. gateway.ingest(
  2457. "session-1",
  2458. log.push(
  2459. SessionEventType.TurnStarted,
  2460. { turnNumber: 1, input: "live 输入" },
  2461. { turnId: "turn-1" },
  2462. ),
  2463. );
  2464. // 即使 persistedEvents 有内容,live publisher 已存在 → 不重放。
  2465. host.persistedEvents.set("session-1", [sessionCreated(new EventLog())]);
  2466. const result = await gateway.subscribe(subscribeParams());
  2467. const userRows = (
  2468. result.initialFrame?.payload.kind === "snapshot"
  2469. ? result.initialFrame.payload.snapshot.rows.window
  2470. : []
  2471. ).filter((row) => row.kind === "userInput");
  2472. // 只有 live 的一条 userInput,没有被 hydration 重复注入。
  2473. expect(userRows).toHaveLength(1);
  2474. });
  2475. it("detached child cold resume 后以新 raw epoch 投影文件撤销", async () => {
  2476. const sessionId = "session-child-rewind";
  2477. const host = makeHost();
  2478. const gateway = makeGateway(host);
  2479. const live = new EventLog(sessionId);
  2480. const ingestLive = (event: SessionEvent) => gateway.ingestDetachedLiveSession(sessionId, event);
  2481. ingestLive(
  2482. live.push(SessionEventType.SessionCreated, {
  2483. mode: "default",
  2484. contextWindow: 200_000,
  2485. }),
  2486. );
  2487. ingestLive(
  2488. live.push(
  2489. SessionEventType.TurnStarted,
  2490. { turnNumber: 1, input: "child input", messageId: "msg-child-user" },
  2491. { turnId: "turn-child" },
  2492. ),
  2493. );
  2494. ingestLive(
  2495. live.push(
  2496. SessionEventType.ModelStreaming,
  2497. {
  2498. kind: "text_start",
  2499. delta: "",
  2500. done: false,
  2501. assistantMessageId: "msg-child-assistant",
  2502. },
  2503. { turnId: "turn-child" },
  2504. ),
  2505. );
  2506. ingestLive(
  2507. live.push(
  2508. SessionEventType.ModelStreaming,
  2509. {
  2510. kind: "text_delta",
  2511. delta: "done",
  2512. done: false,
  2513. assistantMessageId: "msg-child-assistant",
  2514. },
  2515. { turnId: "turn-child" },
  2516. ),
  2517. );
  2518. ingestLive(
  2519. live.push(
  2520. SessionEventType.ModelStreaming,
  2521. { kind: "text_end", delta: "", done: false },
  2522. { turnId: "turn-child" },
  2523. ),
  2524. );
  2525. ingestLive(
  2526. live.push(
  2527. SessionEventType.ModelComplete,
  2528. {
  2529. content: "done",
  2530. stopReason: "stop",
  2531. querySource: "subagent",
  2532. usage: { inputTokens: 1, outputTokens: 1 },
  2533. fileChanges: {
  2534. files: 1,
  2535. additions: 1,
  2536. deletions: 0,
  2537. items: [
  2538. {
  2539. path: "/work/child.txt",
  2540. additions: 1,
  2541. deletions: 0,
  2542. writeCount: 1,
  2543. },
  2544. ],
  2545. },
  2546. },
  2547. { turnId: "turn-child" },
  2548. ),
  2549. );
  2550. ingestLive(
  2551. live.push(
  2552. SessionEventType.TurnComplete,
  2553. { response: "done", tokenCount: 1, toolCallCount: 1, duration: 1, resultType: "success" },
  2554. { turnId: "turn-child" },
  2555. ),
  2556. );
  2557. const initial = await gateway.subscribe(
  2558. subscribeParams({ topic: `conversation/${sessionId}`, connectionId: "conn-child-1" }),
  2559. );
  2560. const initialHeader =
  2561. initial.initialFrame?.payload.kind === "snapshot"
  2562. ? initial.initialFrame.payload.snapshot.rows.window.find((row) => row.kind === "turnHeader")
  2563. : undefined;
  2564. expect(initialHeader).toMatchObject({
  2565. kind: "turnHeader",
  2566. fileChanges: { files: 1, state: "active" },
  2567. });
  2568. const resumed = new EventLog(sessionId);
  2569. gateway.ingest(sessionId, {
  2570. ...resumed.push(SessionEventType.SessionResumed, {
  2571. directory: "/work",
  2572. messageCount: 2,
  2573. partCount: 2,
  2574. }),
  2575. id: "event-child-resumed" as EventId,
  2576. });
  2577. gateway.ingest(sessionId, {
  2578. ...resumed.push(SessionEventType.RewindTriggered, {
  2579. rewindId: "rewind-child",
  2580. scope: "workspace",
  2581. strategy: "active_chain",
  2582. targetMessageId: "msg-child-user",
  2583. reason: "file_summary_rewind",
  2584. }),
  2585. id: "event-child-rewind" as EventId,
  2586. });
  2587. const after = await gateway.subscribe(
  2588. subscribeParams({ topic: `conversation/${sessionId}`, connectionId: "conn-child-2" }),
  2589. );
  2590. const afterHeader =
  2591. after.initialFrame?.payload.kind === "snapshot"
  2592. ? after.initialFrame.payload.snapshot.rows.window.find((row) => row.kind === "turnHeader")
  2593. : undefined;
  2594. expect(afterHeader).toMatchObject({
  2595. kind: "turnHeader",
  2596. fileChanges: { files: 1, state: "reverted" },
  2597. });
  2598. });
  2599. });
  2600. describe("文件摘要 query", () => {
  2601. it("reads a live child projection without cold-resuming the child", async () => {
  2602. const host = makeHost();
  2603. const gateway = makeGateway(host);
  2604. const childLog = new EventLog("live-child");
  2605. gateway.ingestDetachedLiveSession("live-child", sessionCreated(childLog));
  2606. gateway.ingestDetachedLiveSession(
  2607. "live-child",
  2608. childLog.push(
  2609. SessionEventType.TurnStarted,
  2610. { turnNumber: 1, input: "child input", messageId: "msg-child-user" },
  2611. { turnId: "child-turn" },
  2612. ),
  2613. );
  2614. const snapshot = (
  2615. await gateway.subscribe(subscribeParams({ topic: "conversation/live-child" }))
  2616. ).initialFrame?.payload;
  2617. const conversation = snapshot?.kind === "snapshot" ? snapshot.snapshot : undefined;
  2618. const targetRow =
  2619. snapshot?.kind === "snapshot"
  2620. ? snapshot.snapshot.rows.window.find((row) => row.kind === "turnHeader")
  2621. : undefined;
  2622. const targetRowId = targetRow?.rowId;
  2623. await gateway.fileChanges({
  2624. sessionId: "live-child",
  2625. target: { rowId: targetRow!.rowId, entityId: targetRow!.entityId! },
  2626. baseRevision: conversation!.revision,
  2627. baseLogEpoch: conversation!.logEpoch,
  2628. });
  2629. expect(host.resumeCalls).toEqual([]);
  2630. expect(host.fileChangeCalls).toEqual([
  2631. { sessionId: "live-child", targetRowId, messageIds: ["msg-child-user"] },
  2632. ]);
  2633. });
  2634. it("detached child 首次撤销预览会冷恢复持久化 record,随后撤销命令仍落到 child", async () => {
  2635. const host = makeHost();
  2636. host.resumeOutcome = "resumed";
  2637. host.fileRewindPreviewResult = {
  2638. canApply: true,
  2639. safeFiles: [
  2640. {
  2641. action: "restore",
  2642. operationCount: 1,
  2643. path: "/work/src/child.ts",
  2644. toolNames: ["Write"],
  2645. },
  2646. ],
  2647. unsafeFiles: [],
  2648. ignoredFiles: [],
  2649. };
  2650. const gateway = makeGateway(host);
  2651. const childLog = new EventLog("detached-child");
  2652. gateway.ingestDetachedLiveSession("detached-child", sessionCreated(childLog));
  2653. gateway.ingestDetachedLiveSession(
  2654. "detached-child",
  2655. childLog.push(
  2656. SessionEventType.TurnStarted,
  2657. { turnNumber: 1, input: "child 写文件", messageId: "msg-child-user" },
  2658. { turnId: "child-turn" },
  2659. ),
  2660. );
  2661. gateway.ingestDetachedLiveSession(
  2662. "detached-child",
  2663. childLog.push(
  2664. SessionEventType.ModelComplete,
  2665. {
  2666. content: "done",
  2667. stopReason: "stop",
  2668. querySource: "main_turn",
  2669. contextWindow: 200_000,
  2670. usage: { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 },
  2671. fileChanges: {
  2672. files: 1,
  2673. additions: 1,
  2674. deletions: 0,
  2675. items: [{ path: "/work/src/child.ts", additions: 1, deletions: 0, writeCount: 1 }],
  2676. },
  2677. },
  2678. { turnId: "child-turn" },
  2679. ),
  2680. );
  2681. gateway.ingestDetachedLiveSession(
  2682. "detached-child",
  2683. childLog.push(
  2684. SessionEventType.TurnComplete,
  2685. { response: "done", tokenCount: 2, toolCallCount: 0, duration: 1, resultType: "success" },
  2686. { turnId: "child-turn" },
  2687. ),
  2688. );
  2689. const subscribed = await gateway.subscribe(
  2690. subscribeParams({ topic: "conversation/detached-child" }),
  2691. );
  2692. const snapshot =
  2693. subscribed.initialFrame?.payload.kind === "snapshot"
  2694. ? subscribed.initialFrame.payload.snapshot
  2695. : undefined;
  2696. const targetRow = snapshot?.rows.window.find(
  2697. (row) => row.kind === "turnHeader" && row.actions?.canRewindFiles === true,
  2698. );
  2699. expect(targetRow).toBeDefined();
  2700. expect(host.resumeCalls).toEqual([]);
  2701. await gateway.fileRewindPreview({
  2702. sessionId: "detached-child",
  2703. target: { rowId: targetRow!.rowId, entityId: targetRow!.entityId! },
  2704. baseRevision: snapshot!.revision,
  2705. baseLogEpoch: snapshot!.logEpoch,
  2706. });
  2707. expect(host.resumeCalls).toEqual(["detached-child"]);
  2708. expect(host.sessions).toContain("detached-child");
  2709. expect(host.fileRewindPreviewCalls).toEqual([
  2710. {
  2711. sessionId: "detached-child",
  2712. targetRowId: targetRow!.rowId,
  2713. messageIds: ["msg-child-user"],
  2714. },
  2715. ]);
  2716. const ack = await gateway.handleCommand(
  2717. commandParams({
  2718. commandId: "cmd-child-rewind",
  2719. sessionId: "detached-child",
  2720. type: "applyFileRewind",
  2721. payload: { target: { rowId: targetRow!.rowId, entityId: targetRow!.entityId! } },
  2722. baseRevision: snapshot!.revision,
  2723. baseLogEpoch: snapshot!.logEpoch,
  2724. }),
  2725. );
  2726. expect(ack).toMatchObject({ status: "accepted" });
  2727. await vi.waitFor(() => expect(host.executed).toHaveLength(1));
  2728. expect(host.executed[0]).toMatchObject({
  2729. commandId: "cmd-child-rewind",
  2730. sessionId: "detached-child",
  2731. type: "applyFileRewind",
  2732. });
  2733. });
  2734. it("fileChanges query 能用普通 TurnStarted 的 user messageId 定位文件 checkpoint", async () => {
  2735. const host = makeHost();
  2736. host.fileChangesResult = {
  2737. files: 1,
  2738. additions: 1,
  2739. deletions: 0,
  2740. items: [
  2741. {
  2742. path: "/work/input.html",
  2743. additions: 1,
  2744. deletions: 0,
  2745. writeCount: 1,
  2746. toolNames: ["Write"],
  2747. patches: [],
  2748. },
  2749. ],
  2750. };
  2751. const gateway = makeGateway(host);
  2752. const log = new EventLog();
  2753. gateway.ingest("session-1", sessionCreated(log));
  2754. gateway.ingest(
  2755. "session-1",
  2756. log.push(
  2757. SessionEventType.TurnStarted,
  2758. { turnNumber: 1, input: "改文件", messageId: "msg-user-1" },
  2759. { turnId: "turn-1" },
  2760. ),
  2761. );
  2762. const snapshot = (await gateway.subscribe(subscribeParams())).initialFrame?.payload;
  2763. const conversation = snapshot?.kind === "snapshot" ? snapshot.snapshot : undefined;
  2764. const targetRow =
  2765. snapshot?.kind === "snapshot"
  2766. ? snapshot.snapshot.rows.window.find((row) => row.kind === "turnHeader")
  2767. : undefined;
  2768. const targetRowId = targetRow?.rowId;
  2769. expect(targetRowId).toBeDefined();
  2770. await gateway.fileChanges({
  2771. sessionId: "session-1",
  2772. target: { rowId: targetRow!.rowId, entityId: targetRow!.entityId! },
  2773. baseRevision: conversation!.revision,
  2774. baseLogEpoch: conversation!.logEpoch,
  2775. });
  2776. expect(host.fileChangeCalls).toEqual([
  2777. { sessionId: "session-1", targetRowId, messageIds: ["msg-user-1"] },
  2778. ]);
  2779. });
  2780. it("fileChanges query 能用 background model-only TurnStarted 的隐藏 messageId 定位文件 checkpoint", async () => {
  2781. const host = makeHost();
  2782. const gateway = makeGateway(host);
  2783. const log = new EventLog();
  2784. gateway.ingest("session-1", sessionCreated(log));
  2785. gateway.ingest(
  2786. "session-1",
  2787. log.push(
  2788. SessionEventType.TurnStarted,
  2789. {
  2790. turnNumber: 2,
  2791. input: "<task-notification>background task completed</task-notification>",
  2792. inputSource: "background_task",
  2793. inputVisibility: "model-only",
  2794. messageId: "msg-background-wake",
  2795. },
  2796. { turnId: "turn-background-wake" },
  2797. ),
  2798. );
  2799. gateway.ingest(
  2800. "session-1",
  2801. log.push(
  2802. SessionEventType.ModelComplete,
  2803. {
  2804. content: "done",
  2805. stopReason: "stop",
  2806. querySource: "main_turn",
  2807. contextWindow: 200_000,
  2808. usage: { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 },
  2809. fileChanges: {
  2810. files: 1,
  2811. additions: 1,
  2812. deletions: 0,
  2813. items: [
  2814. {
  2815. path: "/work/background-result.md",
  2816. additions: 1,
  2817. deletions: 0,
  2818. writeCount: 1,
  2819. },
  2820. ],
  2821. },
  2822. },
  2823. { turnId: "turn-background-wake" },
  2824. ),
  2825. );
  2826. const snapshot = (await gateway.subscribe(subscribeParams())).initialFrame?.payload;
  2827. const conversation = snapshot?.kind === "snapshot" ? snapshot.snapshot : undefined;
  2828. const targetRow =
  2829. snapshot?.kind === "snapshot"
  2830. ? snapshot.snapshot.rows.window.find((row) => row.kind === "turnHeader")
  2831. : undefined;
  2832. expect(targetRow).toBeDefined();
  2833. expect(conversation?.rows.window.some((row) => row.kind === "userInput")).toBe(false);
  2834. await gateway.fileChanges({
  2835. sessionId: "session-1",
  2836. target: { rowId: targetRow!.rowId, entityId: targetRow!.entityId! },
  2837. baseRevision: conversation!.revision,
  2838. baseLogEpoch: conversation!.logEpoch,
  2839. });
  2840. expect(host.fileChangeCalls).toEqual([
  2841. {
  2842. sessionId: "session-1",
  2843. targetRowId: targetRow!.rowId,
  2844. messageIds: ["msg-background-wake"],
  2845. },
  2846. ]);
  2847. });
  2848. it("fileChanges query 通过 turn rowId 解析同轮 messageIds 后转发宿主", async () => {
  2849. const host = makeHost();
  2850. host.fileChangesResult = {
  2851. files: 1,
  2852. additions: 1,
  2853. deletions: 0,
  2854. items: [
  2855. {
  2856. path: "/work/src/demo.ts",
  2857. additions: 1,
  2858. deletions: 0,
  2859. writeCount: 1,
  2860. toolNames: ["Write"],
  2861. patches: [],
  2862. },
  2863. ],
  2864. };
  2865. const gateway = makeGateway(host);
  2866. const log = new EventLog();
  2867. gateway.ingest("session-1", sessionCreated(log));
  2868. const turnStarted = log.push(
  2869. SessionEventType.TurnStarted,
  2870. { turnNumber: 1, input: "改文件" },
  2871. { turnId: "turn-1" },
  2872. );
  2873. gateway.ingest("session-1", turnStarted);
  2874. gateway.ingest(
  2875. "session-1",
  2876. log.push(
  2877. SessionEventType.ModelStreaming,
  2878. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  2879. { turnId: "turn-1" },
  2880. ),
  2881. );
  2882. const header = gateway.getQueueHead("session-1"); // no-op read to keep type surface exercised
  2883. expect(header).toBeNull();
  2884. const snapshot = (await gateway.subscribe(subscribeParams())).initialFrame?.payload;
  2885. const conversation = snapshot?.kind === "snapshot" ? snapshot.snapshot : undefined;
  2886. const targetRow =
  2887. snapshot?.kind === "snapshot"
  2888. ? snapshot.snapshot.rows.window.find((row) => row.kind === "turnHeader")
  2889. : undefined;
  2890. const targetRowId = targetRow?.rowId;
  2891. expect(targetRowId).toBeDefined();
  2892. const result = await gateway.fileChanges({
  2893. sessionId: "session-1",
  2894. target: { rowId: targetRow!.rowId, entityId: targetRow!.entityId! },
  2895. baseRevision: conversation!.revision,
  2896. baseLogEpoch: conversation!.logEpoch,
  2897. });
  2898. expect(result.files).toBe(1);
  2899. expect(host.fileChangeCalls).toEqual([
  2900. { sessionId: "session-1", targetRowId, messageIds: ["msg-a1"] },
  2901. ]);
  2902. });
  2903. it("fileRewindPreview query 通过 turn rowId 解析同轮 messageIds 后转发宿主", async () => {
  2904. const host = makeHost();
  2905. host.fileRewindPreviewResult = {
  2906. canApply: true,
  2907. safeFiles: [
  2908. {
  2909. action: "restore",
  2910. operationCount: 1,
  2911. path: "/work/src/demo.ts",
  2912. toolNames: ["Write"],
  2913. },
  2914. ],
  2915. unsafeFiles: [],
  2916. ignoredFiles: [],
  2917. };
  2918. const gateway = makeGateway(host);
  2919. const log = new EventLog();
  2920. gateway.ingest("session-1", sessionCreated(log));
  2921. gateway.ingest(
  2922. "session-1",
  2923. log.push(
  2924. SessionEventType.TurnStarted,
  2925. { turnNumber: 1, input: "改文件" },
  2926. { turnId: "turn-1" },
  2927. ),
  2928. );
  2929. gateway.ingest(
  2930. "session-1",
  2931. log.push(
  2932. SessionEventType.ModelStreaming,
  2933. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-a1" },
  2934. { turnId: "turn-1" },
  2935. ),
  2936. );
  2937. gateway.ingest(
  2938. "session-1",
  2939. log.push(
  2940. SessionEventType.ModelComplete,
  2941. {
  2942. content: "done",
  2943. stopReason: "stop",
  2944. querySource: "main_turn",
  2945. contextWindow: 200_000,
  2946. usage: { inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 },
  2947. fileChanges: {
  2948. files: 1,
  2949. additions: 1,
  2950. deletions: 0,
  2951. items: [{ path: "/work/src/demo.ts", additions: 1, deletions: 0, writeCount: 1 }],
  2952. },
  2953. },
  2954. { turnId: "turn-1" },
  2955. ),
  2956. );
  2957. gateway.ingest(
  2958. "session-1",
  2959. log.push(
  2960. SessionEventType.TurnComplete,
  2961. { response: "done", tokenCount: 2, toolCallCount: 0, duration: 1, resultType: "success" },
  2962. { turnId: "turn-1" },
  2963. ),
  2964. );
  2965. const snapshot = (await gateway.subscribe(subscribeParams())).initialFrame?.payload;
  2966. const conversation = snapshot?.kind === "snapshot" ? snapshot.snapshot : undefined;
  2967. const targetRow =
  2968. snapshot?.kind === "snapshot"
  2969. ? snapshot.snapshot.rows.window.find((row) => row.kind === "turnHeader")
  2970. : undefined;
  2971. const targetRowId = targetRow?.rowId;
  2972. expect(targetRowId).toBeDefined();
  2973. const result = await gateway.fileRewindPreview({
  2974. sessionId: "session-1",
  2975. target: { rowId: targetRow!.rowId, entityId: targetRow!.entityId! },
  2976. baseRevision: conversation!.revision,
  2977. baseLogEpoch: conversation!.logEpoch,
  2978. });
  2979. expect(result.canApply).toBe(true);
  2980. expect(host.fileRewindPreviewCalls).toEqual([
  2981. { sessionId: "session-1", targetRowId, messageIds: ["msg-a1"] },
  2982. ]);
  2983. });
  2984. });
  2985. describe("projection 16MiB fault 与恢复", () => {
  2986. it("oversize model event 原子拒绝并只终止一次,TurnError 与 cold hydrate 均保持可传输", async () => {
  2987. const host = makeHost();
  2988. const gateway = makeGateway(host);
  2989. const probe = new ConversationTopicPublisher("session-1", "epoch-1", {
  2990. now: () => 1_700_000_999_000,
  2991. });
  2992. const log = new EventLog();
  2993. const prefix = [
  2994. sessionCreated(log),
  2995. log.push(
  2996. SessionEventType.TurnStarted,
  2997. { turnNumber: 1, input: "生成长回复", messageId: "msg-user-limit" },
  2998. { turnId: "turn-1" },
  2999. ),
  3000. log.push(
  3001. SessionEventType.ModelStreaming,
  3002. { kind: "text_start", delta: "", done: false, assistantMessageId: "msg-assistant-limit" },
  3003. { turnId: "turn-1" },
  3004. ),
  3005. ];
  3006. for (const event of prefix) {
  3007. probe.ingest(event);
  3008. gateway.ingest("session-1", event);
  3009. }
  3010. const emptyDeltaEvent = log.push(
  3011. SessionEventType.ModelStreaming,
  3012. { kind: "text_delta", delta: "", done: false },
  3013. { turnId: "turn-1" },
  3014. );
  3015. probe.ingest(emptyDeltaEvent);
  3016. const runtimeLimit =
  3017. PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxBytes - PROJECTION_TERMINAL_RESERVE_BYTES;
  3018. const exactText = "a".repeat(runtimeLimit - probe.getWireSnapshotLogicalBytes());
  3019. const exactDeltaEvent: SessionEvent = {
  3020. ...emptyDeltaEvent,
  3021. payload: { kind: "text_delta", delta: exactText, done: false },
  3022. };
  3023. gateway.ingest("session-1", exactDeltaEvent);
  3024. const overflow = log.push(
  3025. SessionEventType.ModelStreaming,
  3026. { kind: "text_delta", delta: "a", done: false },
  3027. { turnId: "turn-1" },
  3028. );
  3029. gateway.ingest("session-1", overflow);
  3030. gateway.ingest(
  3031. "session-1",
  3032. log.push(
  3033. SessionEventType.ModelStreaming,
  3034. { kind: "text_delta", delta: "b", done: false },
  3035. { turnId: "turn-1" },
  3036. ),
  3037. );
  3038. expect(host.projectionTerminations).toEqual([
  3039. { sessionId: "session-1", reasonCode: "proto.payloadTooLarge" },
  3040. ]);
  3041. const turnError = log.push(
  3042. SessionEventType.TurnError,
  3043. {
  3044. error: { type: "proto.payloadTooLarge", message: "projection payload too large" },
  3045. turnPhase: "model",
  3046. },
  3047. { turnId: "turn-1" },
  3048. );
  3049. gateway.ingest("session-1", turnError);
  3050. const live = await gateway.subscribe(subscribeParams());
  3051. expect(live.initialFrame).not.toBeNull();
  3052. expect(utf8JsonByteLength(live.initialFrame)).toBeLessThanOrEqual(
  3053. PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxBytes,
  3054. );
  3055. expect(
  3056. live.initialFrame?.payload.kind === "snapshot"
  3057. ? live.initialFrame.payload.snapshot.control.phase
  3058. : null,
  3059. ).toBe("error");
  3060. const coldHost = makeHost();
  3061. coldHost.persistedEvents.set("session-1", [...prefix, exactDeltaEvent, overflow, turnError]);
  3062. const cold = await makeGateway(coldHost).subscribe(subscribeParams());
  3063. expect(cold.initialFrame).not.toBeNull();
  3064. expect(utf8JsonByteLength(cold.initialFrame)).toBeLessThanOrEqual(
  3065. PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxBytes,
  3066. );
  3067. expect(coldHost.errors.some((entry) => entry.scope === "v4.hydrate.payloadTooLarge")).toBe(
  3068. true,
  3069. );
  3070. });
  3071. it("oversize tool input 不进入 projection,并以同一 protocol fault 终止 turn", async () => {
  3072. const host = makeHost();
  3073. const gateway = makeGateway(host);
  3074. const log = new EventLog();
  3075. gateway.ingest("session-1", sessionCreated(log));
  3076. gateway.ingest(
  3077. "session-1",
  3078. log.push(
  3079. SessionEventType.TurnStarted,
  3080. { turnNumber: 1, input: "调用工具", messageId: "msg-user-tool-limit" },
  3081. { turnId: "turn-1" },
  3082. ),
  3083. );
  3084. gateway.ingest(
  3085. "session-1",
  3086. log.push(
  3087. SessionEventType.ModelStreaming,
  3088. {
  3089. kind: "tool_call",
  3090. toolCallId: "tool-limit",
  3091. toolName: "write",
  3092. input: { content: "x".repeat(PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxBytes) },
  3093. },
  3094. { turnId: "turn-1" },
  3095. ),
  3096. );
  3097. expect(host.projectionTerminations).toEqual([
  3098. { sessionId: "session-1", reasonCode: "proto.payloadTooLarge" },
  3099. ]);
  3100. gateway.ingest(
  3101. "session-1",
  3102. log.push(
  3103. SessionEventType.TurnError,
  3104. {
  3105. error: { type: "proto.payloadTooLarge", message: "projection payload too large" },
  3106. turnPhase: "tool",
  3107. },
  3108. { turnId: "turn-1" },
  3109. ),
  3110. );
  3111. const subscribed = await gateway.subscribe(subscribeParams());
  3112. const snapshot =
  3113. subscribed.initialFrame?.payload.kind === "snapshot"
  3114. ? subscribed.initialFrame.payload.snapshot
  3115. : null;
  3116. expect(snapshot?.rows.window.some((row) => row.kind === "toolCall")).toBe(false);
  3117. expect(snapshot?.control.lastError?.code).toBe("proto.payloadTooLarge");
  3118. expect(utf8JsonByteLength(subscribed.initialFrame)).toBeLessThanOrEqual(
  3119. PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxBytes,
  3120. );
  3121. });
  3122. });
  3123. describe("projection event commit waiter", () => {
  3124. beforeEach(() => vi.useFakeTimers());
  3125. afterEach(() => vi.useRealTimers());
  3126. it.each(["desktop-continuous", "web-remote-replayable"])(
  3127. "PA158 %s:已提交授权投影超时后重建日志,不覆盖后来模式",
  3128. async (profileId) => {
  3129. const host = makeHost();
  3130. const gateway = makeGateway(host);
  3131. const log = new EventLog();
  3132. gateway.ingest("session-1", sessionCreated(log));
  3133. log.push(SessionEventType.SessionTitleUpdated, {
  3134. title: "missing transport",
  3135. source: "custom",
  3136. });
  3137. const grant = log.push(SessionEventType.SessionModeChanged, {
  3138. mode: "yolo",
  3139. planEnabled: true,
  3140. source: "command",
  3141. permissionGrant: { interactionId: "p", queueItemIds: [] },
  3142. });
  3143. gateway.ingest("session-1", grant);
  3144. const timedOut = expect(
  3145. gateway.waitForPermissionGrantCommit("session-1", String(grant.id)),
  3146. ).rejects.toMatchObject({ reasonCode: "fault.projectionEventCommit.timeout" });
  3147. await vi.advanceTimersByTimeAsync(25_000);
  3148. await timedOut;
  3149. log.push(SessionEventType.SessionModeChanged, {
  3150. mode: "edit",
  3151. planEnabled: false,
  3152. source: "command",
  3153. });
  3154. host.persistedEvents.set("session-1", log.events);
  3155. await gateway.waitForPermissionGrantCommit("session-1", String(grant.id));
  3156. const subscribed = await gateway.subscribe(subscribeParams({ clientMode: profileId }));
  3157. const snapshot =
  3158. subscribed.initialFrame?.payload.kind === "snapshot"
  3159. ? subscribed.initialFrame.payload.snapshot
  3160. : null;
  3161. expect(snapshot?.config).toMatchObject({
  3162. mode: "edit",
  3163. planEnabled: false,
  3164. permissionGrant: { interactionId: "p" },
  3165. });
  3166. },
  3167. );
  3168. it("raw gap pending 时不 resolve;缺失 seq 到达并 apply 目标 event 后才 resolve", async () => {
  3169. const gateway = makeGateway(makeHost());
  3170. const log = new EventLog();
  3171. gateway.ingest("session-1", sessionCreated(log));
  3172. const missing = log.push(SessionEventType.SessionTitleUpdated, {
  3173. previousTitle: "old",
  3174. title: "new",
  3175. source: "custom",
  3176. });
  3177. const target = log.push(
  3178. SessionEventType.TurnStarted,
  3179. { turnNumber: 1, input: "gap 后启动", messageId: "msg-gap-user" },
  3180. { turnId: "turn-gap" },
  3181. );
  3182. gateway.ingest("session-1", target);
  3183. let committed = false;
  3184. const waiting = gateway
  3185. .waitForProjectionEventCommit("session-1", String(target.id))
  3186. .then(() => {
  3187. committed = true;
  3188. });
  3189. await Promise.resolve();
  3190. expect(committed).toBe(false);
  3191. gateway.ingest("session-1", missing);
  3192. await waiting;
  3193. expect(committed).toBe(true);
  3194. await expect(
  3195. gateway.waitForProjectionEventCommit("session-1", String(target.id)),
  3196. ).resolves.toBeUndefined();
  3197. });
  3198. it("SessionResumed 前跳会开启新 raw epoch,不让旧 runtime gap 阻塞 TurnStarted", async () => {
  3199. const gateway = makeGateway(makeHost());
  3200. const log = new EventLog();
  3201. gateway.ingest("session-1", sessionCreated(log));
  3202. const resumed = {
  3203. ...log.push(SessionEventType.SessionResumed, {
  3204. directory: "/repo",
  3205. interruptedToolCount: 0,
  3206. messageCount: 10,
  3207. partCount: 20,
  3208. }),
  3209. id: "event-resumed-new-epoch" as EventId,
  3210. sequenceNumber: 100,
  3211. };
  3212. const started = {
  3213. ...log.push(
  3214. SessionEventType.TurnStarted,
  3215. { turnNumber: 2, input: "恢复后立即发送", messageId: "msg-new-epoch" },
  3216. { turnId: "turn-new-epoch" },
  3217. ),
  3218. id: "event-started-new-epoch" as EventId,
  3219. sequenceNumber: 101,
  3220. };
  3221. gateway.ingest("session-1", resumed);
  3222. gateway.ingest("session-1", started);
  3223. let committed = false;
  3224. const waiting = gateway
  3225. .waitForProjectionEventCommit("session-1", String(started.id))
  3226. .then(() => {
  3227. committed = true;
  3228. });
  3229. await Promise.resolve();
  3230. expect(committed).toBe(true);
  3231. await waiting;
  3232. });
  3233. it("canonical event apply 后通知宿主,供 goal 终态重评 queue gate", () => {
  3234. const host = makeHost();
  3235. const gateway = makeGateway(host);
  3236. const log = new EventLog();
  3237. const created = sessionCreated(log);
  3238. const targetActive = log.push(SessionEventType.TargetChanged, {
  3239. action: "created",
  3240. previousTarget: null,
  3241. source: "command",
  3242. target: {
  3243. targetID: "goal-1",
  3244. objective: "验证 background goal queue",
  3245. status: "active",
  3246. },
  3247. });
  3248. const targetCompleted = log.push(SessionEventType.TargetChanged, {
  3249. action: "status_updated",
  3250. previousTarget: {
  3251. targetID: "goal-1",
  3252. objective: "验证 background goal queue",
  3253. status: "active",
  3254. },
  3255. source: "runtime",
  3256. target: {
  3257. targetID: "goal-1",
  3258. objective: "验证 background goal queue",
  3259. status: "complete",
  3260. },
  3261. });
  3262. gateway.ingest("session-1", created);
  3263. gateway.ingest("session-1", targetActive);
  3264. gateway.ingest("session-1", targetCompleted);
  3265. expect(host.projectionEvents).toEqual([{ sessionId: "session-1", event: targetCompleted }]);
  3266. });
  3267. it("disposeSession/rehydrate 会 reject pending waiter 并清理", async () => {
  3268. const host = makeHost();
  3269. const gateway = makeGateway(host);
  3270. const log = new EventLog();
  3271. gateway.ingest("session-1", sessionCreated(log));
  3272. log.push(SessionEventType.SessionTitleUpdated, {
  3273. previousTitle: "old",
  3274. title: "new",
  3275. source: "custom",
  3276. });
  3277. const pendingForDispose = log.push(
  3278. SessionEventType.TurnStarted,
  3279. { turnNumber: 1, input: "pending dispose", messageId: "msg-dispose" },
  3280. { turnId: "turn-dispose" },
  3281. );
  3282. gateway.ingest("session-1", pendingForDispose);
  3283. const disposed = expect(
  3284. gateway.waitForProjectionEventCommit("session-1", String(pendingForDispose.id)),
  3285. ).rejects.toMatchObject({ reasonCode: "fault.projectionEventCommit.disposed" });
  3286. gateway.disposeSession("session-1");
  3287. await disposed;
  3288. const rehydrateLog = new EventLog();
  3289. gateway.ingest("session-1", sessionCreated(rehydrateLog));
  3290. rehydrateLog.push(SessionEventType.SessionTitleUpdated, {
  3291. previousTitle: "old",
  3292. title: "new",
  3293. source: "custom",
  3294. });
  3295. const pendingForRehydrate = rehydrateLog.push(
  3296. SessionEventType.TurnStarted,
  3297. { turnNumber: 1, input: "pending rehydrate", messageId: "msg-rehydrate" },
  3298. { turnId: "turn-rehydrate" },
  3299. );
  3300. gateway.ingest("session-1", pendingForRehydrate);
  3301. const rehydrated = expect(
  3302. gateway.waitForProjectionEventCommit("session-1", String(pendingForRehydrate.id)),
  3303. ).rejects.toMatchObject({ reasonCode: "fault.projectionEventCommit.rehydrated" });
  3304. host.loadPersistedEventsImpl = async () => ({
  3305. events: [sessionCreated(new EventLog())],
  3306. synthesized: true,
  3307. sourceEventSeq: 1,
  3308. });
  3309. await gateway.subscribe(subscribeParams({ connectionId: "rehydrate-waiter" }));
  3310. await rehydrated;
  3311. const wholeGateway = makeGateway(makeHost());
  3312. const wholeLog = new EventLog();
  3313. wholeGateway.ingest("session-1", sessionCreated(wholeLog));
  3314. wholeLog.push(SessionEventType.SessionTitleUpdated, {
  3315. previousTitle: "old",
  3316. title: "new",
  3317. source: "custom",
  3318. });
  3319. const pendingForGatewayDispose = wholeLog.push(
  3320. SessionEventType.TurnStarted,
  3321. { turnNumber: 1, input: "pending gateway dispose", messageId: "msg-gateway-dispose" },
  3322. { turnId: "turn-gateway-dispose" },
  3323. );
  3324. wholeGateway.ingest("session-1", pendingForGatewayDispose);
  3325. const gatewayDisposed = expect(
  3326. wholeGateway.waitForProjectionEventCommit("session-1", String(pendingForGatewayDispose.id)),
  3327. ).rejects.toMatchObject({ reasonCode: "fault.projectionEventCommit.gatewayDisposed" });
  3328. wholeGateway.dispose();
  3329. await gatewayDisposed;
  3330. });
  3331. it("projection apply error 会留下 event failure fact,迟到 waiter 立即 reject", async () => {
  3332. const gateway = makeGateway(makeHost());
  3333. const log = new EventLog();
  3334. gateway.ingest("session-1", sessionCreated(log));
  3335. const oversized = log.push(
  3336. SessionEventType.TurnStarted,
  3337. {
  3338. turnNumber: 1,
  3339. input: "x".repeat(PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxBytes),
  3340. messageId: "msg-oversized-commit",
  3341. },
  3342. { turnId: "turn-oversized-commit" },
  3343. );
  3344. gateway.ingest("session-1", oversized);
  3345. await expect(
  3346. gateway.waitForProjectionEventCommit("session-1", String(oversized.id)),
  3347. ).rejects.toMatchObject({ reasonCode: "fault.projectionEventCommit.applyFailed" });
  3348. });
  3349. it("25s timeout 后固化 event failure;补齐 raw gap 也不得迟到 apply", async () => {
  3350. const gateway = makeGateway(makeHost());
  3351. const log = new EventLog();
  3352. gateway.ingest("session-1", sessionCreated(log));
  3353. const missing = log.push(SessionEventType.SessionTitleUpdated, {
  3354. previousTitle: "old",
  3355. title: "new",
  3356. source: "custom",
  3357. });
  3358. const target = log.push(
  3359. SessionEventType.TurnStarted,
  3360. {
  3361. turnNumber: 1,
  3362. input: "pending timeout",
  3363. inputId: "cmd-waiter-timeout",
  3364. messageId: "msg-timeout",
  3365. },
  3366. { turnId: "turn-timeout" },
  3367. );
  3368. gateway.ingest("session-1", target);
  3369. const timedOut = expect(
  3370. gateway.waitForProjectionEventCommit("session-1", String(target.id)),
  3371. ).rejects.toMatchObject({ reasonCode: "fault.projectionEventCommit.timeout" });
  3372. await vi.advanceTimersByTimeAsync(25_000);
  3373. await timedOut;
  3374. gateway.ingest("session-1", missing);
  3375. await expect(
  3376. gateway.waitForProjectionEventCommit("session-1", String(target.id)),
  3377. ).rejects.toMatchObject({ reasonCode: "fault.projectionEventCommit.timeout" });
  3378. const subscribed = await gateway.subscribe(
  3379. subscribeParams({ connectionId: "post-waiter-timeout-gap-recovery" }),
  3380. );
  3381. const snapshot =
  3382. subscribed.initialFrame?.payload.kind === "snapshot"
  3383. ? subscribed.initialFrame.payload.snapshot
  3384. : null;
  3385. expect(
  3386. snapshot?.rows.window.some(
  3387. (row) => row.kind === "userInput" && row.sourceCommandId === "cmd-waiter-timeout",
  3388. ),
  3389. ).toBe(false);
  3390. });
  3391. it("abort 后固化 event failure;补齐 raw gap 也不得迟到 apply", async () => {
  3392. const gateway = makeGateway(makeHost());
  3393. const log = new EventLog();
  3394. gateway.ingest("session-1", sessionCreated(log));
  3395. const missing = log.push(SessionEventType.SessionTitleUpdated, {
  3396. previousTitle: "old",
  3397. title: "new",
  3398. source: "custom",
  3399. });
  3400. const target = log.push(
  3401. SessionEventType.TurnStarted,
  3402. {
  3403. turnNumber: 1,
  3404. input: "pending abort",
  3405. inputId: "cmd-waiter-abort",
  3406. messageId: "msg-abort",
  3407. },
  3408. { turnId: "turn-abort" },
  3409. );
  3410. gateway.ingest("session-1", target);
  3411. const controller = new AbortController();
  3412. const aborted = expect(
  3413. gateway.waitForProjectionEventCommit("session-1", String(target.id), {
  3414. signal: controller.signal,
  3415. }),
  3416. ).rejects.toMatchObject({ reasonCode: "fault.projectionEventCommit.aborted" });
  3417. controller.abort(new Error("command cancelled before projection commit"));
  3418. await aborted;
  3419. gateway.ingest("session-1", missing);
  3420. await expect(
  3421. gateway.waitForProjectionEventCommit("session-1", String(target.id)),
  3422. ).rejects.toMatchObject({ reasonCode: "fault.projectionEventCommit.aborted" });
  3423. const subscribed = await gateway.subscribe(
  3424. subscribeParams({ connectionId: "post-waiter-abort-gap-recovery" }),
  3425. );
  3426. const snapshot =
  3427. subscribed.initialFrame?.payload.kind === "snapshot"
  3428. ? subscribed.initialFrame.payload.snapshot
  3429. : null;
  3430. expect(
  3431. snapshot?.rows.window.some(
  3432. (row) => row.kind === "userInput" && row.sourceCommandId === "cmd-waiter-abort",
  3433. ),
  3434. ).toBe(false);
  3435. });
  3436. });
  3437. describe("v4/command 收口", () => {
  3438. it("durable create 首发在启动前可观察 pending,启动与快速完成后不残留", async () => {
  3439. const host = makeHost();
  3440. const gateway = makeGateway(host);
  3441. const log = new EventLog();
  3442. gateway.ingest("session-1", sessionCreated(log));
  3443. const command = commandParams({
  3444. commandId: "app-control-create",
  3445. type: "createSession",
  3446. sessionId: null,
  3447. payload: { workspaceId: "/work", firstInput: { text: "first" } },
  3448. });
  3449. gateway.admitPendingInput("session-1", command as CommandEnvelope, 100);
  3450. const before = await gateway.subscribe(subscribeParams());
  3451. expect(before.initialFrame?.payload).toMatchObject({
  3452. kind: "snapshot",
  3453. snapshot: {
  3454. pendingCommands: [{ commandId: command.commandId, state: "accepted" }],
  3455. rows: { window: [] },
  3456. },
  3457. });
  3458. gateway.ingest(
  3459. "session-1",
  3460. log.push(
  3461. SessionEventType.TurnStarted,
  3462. { input: "first", inputId: command.commandId, turnNumber: 1 },
  3463. { turnId: "turn-1" },
  3464. ),
  3465. );
  3466. gateway.ingest(
  3467. "session-1",
  3468. log.push(SessionEventType.TurnComplete, { inputId: command.commandId }, { turnId: "turn-1" }),
  3469. );
  3470. const after = await gateway.subscribe(subscribeParams());
  3471. expect(after.initialFrame?.payload).toMatchObject({
  3472. kind: "snapshot",
  3473. snapshot: { pendingCommands: [] },
  3474. });
  3475. gateway.dispose();
  3476. });
  3477. it("仅持久提升不清 pending,启动前失败按精确 inputId 移除", async () => {
  3478. const host = makeHost();
  3479. const gateway = makeGateway(host);
  3480. const log = new EventLog();
  3481. gateway.ingest("session-1", sessionCreated(log));
  3482. const command = commandParams({ commandId: "app-control-pre-start" }) as CommandEnvelope;
  3483. gateway.admitPendingInput("session-1", command, 100);
  3484. gateway.ingest(
  3485. "session-1",
  3486. log.push(SessionEventType.SessionInputPromoted, {
  3487. sourceCommandId: command.commandId,
  3488. pendingInputId: `queue_${command.commandId}`,
  3489. messageId: "message-1",
  3490. }),
  3491. );
  3492. expect((await gateway.subscribe(subscribeParams())).initialFrame?.payload).toMatchObject({
  3493. kind: "snapshot",
  3494. snapshot: { pendingCommands: [{ commandId: command.commandId }] },
  3495. });
  3496. gateway.ingest(
  3497. "session-1",
  3498. log.push(
  3499. SessionEventType.TurnError,
  3500. {
  3501. inputId: command.commandId,
  3502. error: { message: "pre-start rejected" },
  3503. },
  3504. { turnId: "turn-failed" },
  3505. ),
  3506. );
  3507. expect((await gateway.subscribe(subscribeParams())).initialFrame?.payload).toMatchObject({
  3508. kind: "snapshot",
  3509. snapshot: { pendingCommands: [] },
  3510. });
  3511. gateway.dispose();
  3512. });
  3513. it("取消只移除匹配 pending;队列事实替代 pending,冷启动不恢复 pending", async () => {
  3514. const host = makeHost();
  3515. const gateway = makeGateway(host);
  3516. const log = new EventLog();
  3517. gateway.ingest("session-1", sessionCreated(log));
  3518. const first = commandParams({ commandId: "app-control-first" }) as CommandEnvelope;
  3519. const second = commandParams({ commandId: "app-control-second" }) as CommandEnvelope;
  3520. gateway.admitPendingInput("session-1", first, 100);
  3521. gateway.admitPendingInput("session-1", second, 101);
  3522. gateway.cancelPendingInput("session-1", first.commandId);
  3523. expect((await gateway.subscribe(subscribeParams())).initialFrame?.payload).toMatchObject({
  3524. kind: "snapshot",
  3525. snapshot: { pendingCommands: [{ commandId: second.commandId }] },
  3526. });
  3527. gateway.ingest(
  3528. "session-1",
  3529. log.push(SessionEventType.TurnSteerQueued, {
  3530. pendingInputId: "queue_app-control-second",
  3531. inputId: second.commandId,
  3532. input: "queued",
  3533. delivery: "queue",
  3534. queueLength: 1,
  3535. intent: { sourceCommandId: second.commandId, clientId: "client-1", kind: "sendText" },
  3536. }),
  3537. );
  3538. expect((await gateway.subscribe(subscribeParams())).initialFrame?.payload).toMatchObject({
  3539. kind: "snapshot",
  3540. snapshot: {
  3541. pendingCommands: [],
  3542. queue: { items: [expect.objectContaining({ sourceCommandId: second.commandId })] },
  3543. },
  3544. });
  3545. gateway.admitPendingInput("session-1", first, 102);
  3546. gateway.dispose();
  3547. const restarted = makeGateway(host);
  3548. expect((await restarted.subscribe(subscribeParams())).initialFrame?.payload).toMatchObject({
  3549. kind: "snapshot",
  3550. snapshot: { pendingCommands: [] },
  3551. });
  3552. restarted.dispose();
  3553. });
  3554. it.each(["createSession", "createSelectionSideSession"] as const)(
  3555. "%s ACK 采用结果会话 Memory 而非父会话",
  3556. async (type) => {
  3557. const host = makeHost();
  3558. host.memorySettings = new Map([
  3559. ["session-1", false],
  3560. ["child-1", true],
  3561. ]);
  3562. host.executeImpl = async () => ({ type, sessionId: "child-1" });
  3563. const gateway = makeGateway(host);
  3564. gateway.ingest("session-1", sessionCreated(new EventLog()));
  3565. const ack = await gateway.handleCommand(
  3566. commandParams({
  3567. type,
  3568. sessionId: type === "createSession" ? null : "session-1",
  3569. payload: type === "createSession" ? { workspaceId: "/work" } : {},
  3570. }),
  3571. );
  3572. expect(ack).toMatchObject({
  3573. status: "accepted",
  3574. memoryEnabled: true,
  3575. result: { sessionId: "child-1" },
  3576. });
  3577. gateway.dispose();
  3578. },
  3579. );
  3580. it.each([true, false, undefined])(
  3581. "ACK 与 live turn fact 复用会话 Memory %s",
  3582. async (memoryEnabled) => {
  3583. const host = makeHost();
  3584. host.memorySettings = new Map(
  3585. memoryEnabled === undefined ? [] : [["session-1", memoryEnabled]],
  3586. );
  3587. const gateway = makeGateway(host);
  3588. const log = new EventLog();
  3589. gateway.ingest("session-1", sessionCreated(log));
  3590. const ack = await gateway.handleCommand(commandParams());
  3591. expect(ack.status).toBe("accepted");
  3592. expect(ack.memoryEnabled).toBe(memoryEnabled);
  3593. gateway.ingest(
  3594. "session-1",
  3595. log.push(SessionEventType.TurnStarted, { inputId: "cmd-1" }, { turnId: "turn-1" }),
  3596. );
  3597. expect(host.telemetryFacts.find((fact) => fact.kind === "turn.started")).toMatchObject(
  3598. memoryEnabled === undefined ? { kind: "turn.started" } : { memoryEnabled },
  3599. );
  3600. host.memorySettings.set("session-1", !memoryEnabled);
  3601. const duplicate = await gateway.handleCommand(commandParams());
  3602. expect(duplicate.status).toBe("duplicate");
  3603. expect(duplicate.memoryEnabled).toBe(memoryEnabled);
  3604. gateway.dispose();
  3605. },
  3606. );
  3607. it("resident 回收纯预检在 CommandInbox pin 期间拒绝且不消费 pin", async () => {
  3608. const gateway = makeGateway(makeHost());
  3609. const log = new EventLog();
  3610. gateway.ingest("session-1", sessionCreated(log));
  3611. const inbox = (gateway as unknown as { inbox: CommandInbox }).inbox;
  3612. const running = await inbox.handle(commandParams({ commandId: "command-residency-pinned" }));
  3613. expect(running.kind).toBe("execute");
  3614. expect(() => gateway.assertSessionRuntimeDeactivatable("session-1")).toThrow(
  3615. "Session command inbox is still pinned",
  3616. );
  3617. expect(gateway.hasResidencyBlockingCommands("session-1")).toBe(true);
  3618. if (running.kind === "execute") running.settle({ status: "accepted" });
  3619. expect(() => gateway.assertSessionRuntimeDeactivatable("session-1")).not.toThrow();
  3620. gateway.dispose();
  3621. });
  3622. it("stable fork commit 后 registration 异常仍固化 accepted child 并可跨重启重放", async () => {
  3623. const store = await createSqliteSessionStore({ dbPath: ":memory:" });
  3624. const parentSessionId = createSessionId("post-commit-parent");
  3625. const childSessionId = createSessionId("post-commit-child");
  3626. const childMessageId = createMessageId("post-commit-message");
  3627. const commandId = "cmd-post-commit-registration";
  3628. const warnings: Array<{ message: string; fields: Record<string, unknown> }> = [];
  3629. try {
  3630. await store.createSession({
  3631. id: parentSessionId,
  3632. projectID: createProjectId("post-commit-project"),
  3633. slug: "post-commit-parent",
  3634. directory: "/work",
  3635. title: "post commit parent",
  3636. version: "0.1.0",
  3637. });
  3638. const host = makeHost();
  3639. host.sessions = new Set([String(parentSessionId)]);
  3640. const gateway = makeGateway(host);
  3641. const log = new EventLog(String(parentSessionId));
  3642. gateway.ingest(String(parentSessionId), sessionCreated(log));
  3643. gateway.ingest(
  3644. String(parentSessionId),
  3645. log.push(
  3646. SessionEventType.TurnStarted,
  3647. { turnNumber: 1, input: "fork target", messageId: "msg-parent-user" },
  3648. { turnId: "turn-parent" },
  3649. ),
  3650. );
  3651. gateway.ingest(
  3652. String(parentSessionId),
  3653. log.push(
  3654. SessionEventType.ModelStreaming,
  3655. {
  3656. kind: "text_start",
  3657. delta: "",
  3658. done: false,
  3659. assistantMessageId: "msg-parent-assistant",
  3660. },
  3661. { turnId: "turn-parent" },
  3662. ),
  3663. );
  3664. gateway.ingest(
  3665. String(parentSessionId),
  3666. log.push(
  3667. SessionEventType.ModelComplete,
  3668. {
  3669. content: "stable answer",
  3670. stopReason: "stop",
  3671. querySource: "main_turn",
  3672. contextWindow: 200_000,
  3673. usage: {
  3674. inputTokens: 1,
  3675. outputTokens: 1,
  3676. cacheReadTokens: 0,
  3677. cacheWriteTokens: 0,
  3678. },
  3679. },
  3680. { turnId: "turn-parent" },
  3681. ),
  3682. );
  3683. gateway.ingest(
  3684. String(parentSessionId),
  3685. log.push(
  3686. SessionEventType.TurnComplete,
  3687. {
  3688. response: "stable answer",
  3689. tokenCount: 2,
  3690. toolCallCount: 0,
  3691. duration: 1,
  3692. resultType: "success",
  3693. },
  3694. { turnId: "turn-parent" },
  3695. ),
  3696. );
  3697. const initial = await gateway.subscribe(
  3698. subscribeParams({
  3699. topic: `conversation/${String(parentSessionId)}`,
  3700. connectionId: "conn-post-commit",
  3701. }),
  3702. );
  3703. const stableSnapshot =
  3704. initial.initialFrame?.payload.kind === "snapshot"
  3705. ? initial.initialFrame.payload.snapshot
  3706. : undefined;
  3707. const stableAssistant = stableSnapshot?.rows.window.find(
  3708. (row) => row.kind === "assistantText" && row.actions?.canFork === true,
  3709. );
  3710. expect(stableAssistant).toBeDefined();
  3711. const context = {
  3712. deps: { sessionStore: store },
  3713. logger: {
  3714. warn: (message: string, fields: Record<string, unknown>) => {
  3715. warnings.push({ message, fields });
  3716. },
  3717. },
  3718. sessions: new Map(),
  3719. } as never;
  3720. const registration = vi.fn().mockRejectedValue(new Error("catalog exploded"));
  3721. host.executeImpl = async (envelope) => {
  3722. const child = await store.commitForkBundle!({
  3723. child: {
  3724. id: childSessionId,
  3725. parentID: parentSessionId,
  3726. projectID: createProjectId("post-commit-project"),
  3727. slug: "post-commit-child",
  3728. directory: "/work",
  3729. title: "post commit child",
  3730. version: "0.1.0",
  3731. },
  3732. messages: [
  3733. {
  3734. info: {
  3735. id: childMessageId,
  3736. sessionID: childSessionId,
  3737. role: "user",
  3738. agent: "build",
  3739. model: { providerID: "test", modelID: "test" },
  3740. system: [],
  3741. tools: {},
  3742. time: { created: 1 },
  3743. },
  3744. parts: [
  3745. {
  3746. id: createPartId("post-commit-part"),
  3747. sessionID: childSessionId,
  3748. messageID: childMessageId,
  3749. type: "text",
  3750. text: "durable child transcript",
  3751. },
  3752. ],
  3753. },
  3754. ],
  3755. entries: [],
  3756. commandFact: {
  3757. parentSessionId: String(parentSessionId),
  3758. sourceCommandId: commandId,
  3759. ack: {
  3760. commandId,
  3761. status: "accepted",
  3762. revisionAtDecision: stableSnapshot!.revision,
  3763. result: { type: "forkAssistant", sessionId: String(childSessionId) },
  3764. },
  3765. metadata: { parentSessionId: String(parentSessionId) },
  3766. },
  3767. });
  3768. await registerCommittedForkBestEffort(
  3769. context,
  3770. {} as never,
  3771. {
  3772. forkedSessionId: child.id,
  3773. parentSessionId,
  3774. targetMessageId: "msg-parent-target",
  3775. response: "forked",
  3776. } as never,
  3777. {
  3778. commandId: envelope.commandId,
  3779. inheritLatestTarget: false,
  3780. runtimeConfig: { mode: "build", model: "test/test" },
  3781. },
  3782. registration,
  3783. );
  3784. return { type: "forkAssistant", sessionId: String(child.id) };
  3785. };
  3786. const params = commandParams({
  3787. baseLogEpoch: stableSnapshot!.logEpoch,
  3788. baseRevision: stableSnapshot!.revision,
  3789. commandId,
  3790. sessionId: String(parentSessionId),
  3791. type: "forkAssistant",
  3792. payload: {
  3793. target: {
  3794. rowId: stableAssistant!.rowId,
  3795. entityId: stableAssistant!.entityId,
  3796. },
  3797. },
  3798. });
  3799. const first = await gateway.handleCommand(params);
  3800. const duplicate = await gateway.handleCommand(params);
  3801. const query = await gateway.queryCommands({
  3802. commands: [{ sessionId: String(parentSessionId), commandId }],
  3803. });
  3804. expect(first).toMatchObject({
  3805. status: "accepted",
  3806. result: { type: "forkAssistant", sessionId: String(childSessionId) },
  3807. });
  3808. expect(duplicate).toMatchObject({
  3809. status: "duplicate",
  3810. result: { type: "forkAssistant", sessionId: String(childSessionId) },
  3811. });
  3812. expect(query.results[0]?.result).toMatchObject({
  3813. status: "accepted",
  3814. result: { type: "forkAssistant", sessionId: String(childSessionId) },
  3815. });
  3816. expect(host.executed).toHaveLength(1);
  3817. expect(registration).toHaveBeenCalledOnce();
  3818. await expect(store.getSession(childSessionId)).resolves.toMatchObject({
  3819. id: childSessionId,
  3820. parentID: parentSessionId,
  3821. });
  3822. await expect(store.messages({ sessionID: childSessionId })).resolves.toHaveLength(1);
  3823. await expect(
  3824. store.sessionEntries({ sessionID: childSessionId, type: "v4/fork_start_failure" }),
  3825. ).resolves.toEqual([
  3826. expect.objectContaining({
  3827. data: expect.objectContaining({
  3828. commandId,
  3829. forkedSessionId: String(childSessionId),
  3830. registrationRequired: true,
  3831. retryable: true,
  3832. }),
  3833. }),
  3834. ]);
  3835. expect(warnings).toContainEqual({
  3836. message: "fork child registration failed after durable commit",
  3837. fields: expect.objectContaining({
  3838. commandId,
  3839. error: "catalog exploded",
  3840. forkedSessionId: String(childSessionId),
  3841. parentSessionId: String(parentSessionId),
  3842. retryable: true,
  3843. }),
  3844. });
  3845. const durable = await loadPersistentCommandFacts(store, parentSessionId);
  3846. const restartedHost = makeHost();
  3847. restartedHost.sessions = new Set([String(parentSessionId)]);
  3848. for (const ack of durable.child ?? []) {
  3849. restartedHost.persistentCommands.child.set(
  3850. `${String(parentSessionId)}\0${ack.commandId}`,
  3851. ack,
  3852. );
  3853. }
  3854. restartedHost.executeImpl = async () => {
  3855. throw new Error("restart must not execute durable fork again");
  3856. };
  3857. const restartedGateway = makeGateway(restartedHost);
  3858. const restartedDuplicate = await restartedGateway.handleCommand(params);
  3859. const restartedQuery = await restartedGateway.queryCommands({
  3860. commands: [{ sessionId: String(parentSessionId), commandId }],
  3861. });
  3862. expect(restartedDuplicate).toMatchObject({
  3863. status: "duplicate",
  3864. result: { type: "forkAssistant", sessionId: String(childSessionId) },
  3865. });
  3866. expect(restartedQuery.results[0]?.result).toMatchObject({
  3867. status: "accepted",
  3868. result: { type: "forkAssistant", sessionId: String(childSessionId) },
  3869. });
  3870. expect(restartedHost.executed).toHaveLength(0);
  3871. } finally {
  3872. store.close();
  3873. }
  3874. });
  3875. it("TurnStarted 前 runtime 失败返回 failed 并取消 durable input,不留下 ghost admission", async () => {
  3876. const host = makeHost();
  3877. const gateway = makeGateway(host);
  3878. const log = new EventLog();
  3879. gateway.ingest("session-1", sessionCreated(log));
  3880. const record = {
  3881. app: {
  3882. sessionId: "session-1",
  3883. sendInput: vi.fn().mockRejectedValue(new Error("pre-start failed")),
  3884. },
  3885. workspace: { workspacePath: "/work" },
  3886. persistence: "immediate",
  3887. traceContext: { traceId: "trace-1" },
  3888. } as unknown as V4SessionRecordView;
  3889. const executor = new V4CommandExecutor({
  3890. getRecord: (sessionId) => (sessionId === "session-1" ? record : undefined),
  3891. afterLegacyStateMutation: async () => {},
  3892. });
  3893. host.executeImpl = (envelope, admission) => executor.execute(envelope, admission);
  3894. const ack = await gateway.handleCommand(commandParams({ commandId: "cmd-pre-start-fail" }));
  3895. expect(ack).toMatchObject({
  3896. status: "failed",
  3897. reasonCode: "fault.command.executionFailed",
  3898. });
  3899. expect(host.inputCancellations).toEqual([
  3900. {
  3901. commandId: "cmd-pre-start-fail",
  3902. queueItemId: "queue_cmd-pre-start-fail",
  3903. reason: "fault.command.executionFailed",
  3904. },
  3905. ]);
  3906. expect(record.activeAbortController).toBeUndefined();
  3907. });
  3908. it("durable TurnStarted 因 raw gap pending 时,Core admission ACK 不等待 projection commit", async () => {
  3909. const host = makeHost();
  3910. const gateway = makeGateway(host);
  3911. const log = new EventLog();
  3912. gateway.ingest("session-1", sessionCreated(log));
  3913. const missing = log.push(SessionEventType.SessionTitleUpdated, {
  3914. previousTitle: "old",
  3915. title: "new",
  3916. source: "custom",
  3917. });
  3918. const pendingTurnStarted = log.push(
  3919. SessionEventType.TurnStarted,
  3920. {
  3921. turnNumber: 1,
  3922. input: "pending projection",
  3923. inputId: "cmd-pending-projection",
  3924. messageId: "msg-pending-projection",
  3925. },
  3926. { turnId: "turn-pending-projection" },
  3927. );
  3928. let finishTurn!: () => void;
  3929. const completion = new Promise<Record<string, never>>((resolve) => {
  3930. finishTurn = () => resolve({});
  3931. });
  3932. const sendInput = vi.fn().mockImplementation(() => {
  3933. gateway.ingest("session-1", pendingTurnStarted);
  3934. return {
  3935. kind: "started_turn",
  3936. turnId: "turn-pending-projection",
  3937. completion,
  3938. };
  3939. });
  3940. const record = {
  3941. app: { sessionId: "session-1", sendInput },
  3942. workspace: { workspacePath: "/work" },
  3943. persistence: "immediate",
  3944. traceContext: { traceId: "trace-1" },
  3945. } as unknown as V4SessionRecordView;
  3946. const executor = new V4CommandExecutor({
  3947. getRecord: (sessionId) => (sessionId === "session-1" ? record : undefined),
  3948. afterLegacyStateMutation: async () => {},
  3949. });
  3950. host.executeImpl = (envelope, admission) => executor.execute(envelope, admission);
  3951. await expect(
  3952. gateway.handleCommand(
  3953. commandParams({
  3954. commandId: "cmd-pending-projection",
  3955. payload: {
  3956. text: "你好",
  3957. modelSelection: { providerId: "glm", modelId: "glm-4-air" },
  3958. mode: "build",
  3959. },
  3960. }),
  3961. ),
  3962. ).resolves.toMatchObject({ status: "accepted" });
  3963. expect(host.inputCancellations).toEqual([]);
  3964. // 修复原因:raw gap 只延迟 projection;它不能反向撤销 Core 已完成的 prompt admission。
  3965. gateway.ingest("session-1", missing);
  3966. const subscribed = await gateway.subscribe(
  3967. subscribeParams({ connectionId: "post-gap-recovery" }),
  3968. );
  3969. const snapshot =
  3970. subscribed.initialFrame?.payload.kind === "snapshot"
  3971. ? subscribed.initialFrame.payload.snapshot
  3972. : null;
  3973. expect(
  3974. snapshot?.rows.window.some(
  3975. (row) => row.kind === "userInput" && row.sourceCommandId === "cmd-pending-projection",
  3976. ),
  3977. ).toBe(true);
  3978. finishTurn();
  3979. });
  3980. it("Core admission ACK 不等待 TurnStarted projection;旧 revision retry/file rewind 只 stale", async () => {
  3981. const host = makeHost();
  3982. const gateway = makeGateway(host);
  3983. const log = new EventLog();
  3984. gateway.ingest("session-1", sessionCreated(log));
  3985. gateway.ingest(
  3986. "session-1",
  3987. log.push(
  3988. SessionEventType.TurnStarted,
  3989. {
  3990. turnNumber: 1,
  3991. input: "旧问题",
  3992. messageId: "msg-user-old",
  3993. intent: {
  3994. sourceCommandId: "cmd-old",
  3995. queueItemId: "queue-old",
  3996. clientId: "client-old",
  3997. kind: "sendText",
  3998. text: "旧问题",
  3999. requestedDelivery: "startNow",
  4000. admittedDelivery: "startNow",
  4001. },
  4002. },
  4003. { turnId: "turn-old" },
  4004. ),
  4005. );
  4006. gateway.ingest(
  4007. "session-1",
  4008. log.push(
  4009. SessionEventType.ModelStreaming,
  4010. {
  4011. kind: "text_start",
  4012. delta: "",
  4013. done: false,
  4014. assistantMessageId: "msg-assistant-old",
  4015. },
  4016. { turnId: "turn-old" },
  4017. ),
  4018. );
  4019. gateway.ingest(
  4020. "session-1",
  4021. log.push(
  4022. SessionEventType.ModelStreaming,
  4023. { kind: "text_delta", delta: "旧回答", done: false },
  4024. { turnId: "turn-old" },
  4025. ),
  4026. );
  4027. gateway.ingest(
  4028. "session-1",
  4029. log.push(
  4030. SessionEventType.ModelComplete,
  4031. {
  4032. content: "旧回答",
  4033. stopReason: "stop",
  4034. querySource: "main_turn",
  4035. contextWindow: 200_000,
  4036. usage: {
  4037. inputTokens: 1,
  4038. outputTokens: 1,
  4039. cacheReadTokens: 0,
  4040. cacheWriteTokens: 0,
  4041. },
  4042. fileChanges: {
  4043. files: 1,
  4044. additions: 1,
  4045. deletions: 0,
  4046. items: [
  4047. {
  4048. path: "/work/a.ts",
  4049. additions: 1,
  4050. deletions: 0,
  4051. writeCount: 1,
  4052. },
  4053. ],
  4054. },
  4055. },
  4056. { turnId: "turn-old" },
  4057. ),
  4058. );
  4059. gateway.ingest(
  4060. "session-1",
  4061. log.push(
  4062. SessionEventType.TurnComplete,
  4063. {
  4064. response: "旧回答",
  4065. tokenCount: 2,
  4066. toolCallCount: 0,
  4067. duration: 1,
  4068. resultType: "success",
  4069. },
  4070. { turnId: "turn-old" },
  4071. ),
  4072. );
  4073. const initial = (await gateway.subscribe(subscribeParams())).initialFrame;
  4074. const snapshot = initial?.payload.kind === "snapshot" ? initial.payload.snapshot : undefined;
  4075. const assistant = snapshot?.rows.window.find(
  4076. (row) => row.kind === "assistantText" && row.actions?.canRetry === true,
  4077. );
  4078. const header = snapshot?.rows.window.find(
  4079. (row) => row.kind === "turnHeader" && row.actions?.canRewindFiles === true,
  4080. );
  4081. expect(assistant).toBeDefined();
  4082. expect(header).toBeDefined();
  4083. let finishTurn!: () => void;
  4084. const turnGate = new Promise<Record<string, never>>((resolve) => {
  4085. finishTurn = () => resolve({});
  4086. });
  4087. const sendInput = vi.fn().mockReturnValue({
  4088. kind: "started_turn",
  4089. turnId: "turn-new",
  4090. completion: turnGate,
  4091. });
  4092. const submitPrompt = vi.fn().mockResolvedValue({});
  4093. const applyWorkspaceFileRewind = vi.fn().mockResolvedValue({
  4094. applied: true,
  4095. preview: { canApply: true, safeFiles: [], unsafeFiles: [], ignoredFiles: [] },
  4096. response: "applied",
  4097. });
  4098. const record = {
  4099. app: {
  4100. sessionId: "session-1",
  4101. sendInput,
  4102. submitPrompt,
  4103. runtime: { applyWorkspaceFileRewind },
  4104. },
  4105. workspace: { workspacePath: "/work" },
  4106. persistence: "immediate",
  4107. traceContext: { traceId: "trace-1" },
  4108. } as unknown as V4SessionRecordView;
  4109. const executor = new V4CommandExecutor({
  4110. getRecord: (sessionId) => (sessionId === "session-1" ? record : undefined),
  4111. resolveRowActionTarget: (sessionId, target, action) =>
  4112. gateway.resolveRowActionTarget(sessionId, target, action),
  4113. afterLegacyStateMutation: async () => {},
  4114. });
  4115. host.executeImpl = (envelope, admission) => executor.execute(envelope, admission);
  4116. const sending = gateway.handleCommand(
  4117. commandParams({
  4118. commandId: "cmd-new",
  4119. baseRevision: snapshot!.revision,
  4120. payload: {
  4121. text: "你好",
  4122. modelSelection: { providerId: "glm", modelId: "glm-4-air" },
  4123. mode: "build",
  4124. },
  4125. }),
  4126. );
  4127. await vi.waitFor(() => expect(sendInput).toHaveBeenCalledTimes(1));
  4128. await expect(sending).resolves.toMatchObject({ status: "accepted" });
  4129. // ACK 只确认输入已准入;投影 revision 必须由实际事件推进,不能由 ACK 自行制造。
  4130. gateway.ingest(
  4131. "session-1",
  4132. log.push(
  4133. SessionEventType.TurnStarted,
  4134. { turnNumber: 2, input: "你好", messageId: "msg-user-new" },
  4135. { turnId: "turn-new" },
  4136. ),
  4137. );
  4138. const staleRetry = gateway.handleCommand(
  4139. commandParams({
  4140. commandId: "cmd-stale-retry",
  4141. type: "retryTurn",
  4142. payload: { target: { rowId: assistant!.rowId, entityId: assistant!.entityId! } },
  4143. baseRevision: snapshot!.revision,
  4144. baseLogEpoch: snapshot!.logEpoch,
  4145. }),
  4146. );
  4147. const staleFileRewind = gateway.handleCommand(
  4148. commandParams({
  4149. commandId: "cmd-stale-file",
  4150. type: "applyFileRewind",
  4151. payload: { target: { rowId: header!.rowId, entityId: header!.entityId! } },
  4152. baseRevision: snapshot!.revision,
  4153. baseLogEpoch: snapshot!.logEpoch,
  4154. }),
  4155. );
  4156. await expect(staleRetry).resolves.toMatchObject({
  4157. status: "stale",
  4158. reasonCode: "proto.staleRevision",
  4159. });
  4160. await expect(staleFileRewind).resolves.toMatchObject({
  4161. status: "stale",
  4162. reasonCode: "proto.staleRevision",
  4163. });
  4164. expect(host.executed.map((envelope) => envelope.commandId)).toEqual(["cmd-new"]);
  4165. expect(submitPrompt).not.toHaveBeenCalled();
  4166. expect(applyWorkspaceFileRewind).not.toHaveBeenCalled();
  4167. finishTurn();
  4168. });
  4169. it("logical TopicFrame 恰好 16MiB 接纳,UTF-8 后再多 1 byte 明确失败且不落 admission", async () => {
  4170. const envelope = commandParams({
  4171. commandId: "cmd-limit",
  4172. payload: { text: "" },
  4173. }) as CommandEnvelope;
  4174. const admission = {
  4175. admissionSeq: 1,
  4176. admittedAt: 1_700_000_999_000,
  4177. queueItemId: "queue_cmd-limit",
  4178. };
  4179. const probe = new ConversationTopicPublisher("session-1", "epoch-1", {
  4180. now: () => 1_700_000_999_000,
  4181. });
  4182. const emptyBytes = probe.measureInputAdmissionProjectionBytes(envelope, admission);
  4183. expect(emptyBytes).not.toBeNull();
  4184. // emoji 验证按 UTF-8 字节而非 JS string.length 计数;其余 ASCII 精确补齐到 16MiB。
  4185. const emoji = "🙂";
  4186. const emojiBytes = Buffer.byteLength(JSON.stringify(emoji), "utf8") - 2;
  4187. const text = `${"a".repeat(
  4188. PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxBytes - (emptyBytes as number) - emojiBytes,
  4189. )}${emoji}`;
  4190. const exactEnvelope = { ...envelope, payload: { text } };
  4191. expect(probe.measureInputAdmissionProjectionBytes(exactEnvelope, admission)).toBe(
  4192. PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxBytes,
  4193. );
  4194. const acceptedHost = makeHost();
  4195. const accepted = await makeGateway(acceptedHost).handleCommand(exactEnvelope);
  4196. expect(accepted.status).toBe("accepted");
  4197. expect(acceptedHost.inputAdmissions).toHaveLength(1);
  4198. expect(acceptedHost.executed).toHaveLength(1);
  4199. const rejectedHost = makeHost();
  4200. const rejected = await makeGateway(rejectedHost).handleCommand({
  4201. ...exactEnvelope,
  4202. payload: { text: `${text}a` },
  4203. });
  4204. expect(rejected).toMatchObject({ status: "failed", reasonCode: "proto.payloadTooLarge" });
  4205. expect(rejectedHost.inputAdmissions).toEqual([]);
  4206. expect(rejectedHost.executed).toEqual([]);
  4207. });
  4208. it.each([
  4209. [
  4210. "sendGoalCommand",
  4211. {
  4212. text: "目标",
  4213. displayText: "x".repeat(PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxBytes),
  4214. },
  4215. ],
  4216. [
  4217. "createSession",
  4218. {
  4219. workspaceId: "/tmp/ws",
  4220. firstInput: { text: "x".repeat(PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxBytes) },
  4221. },
  4222. ],
  4223. [
  4224. "sendText",
  4225. {
  4226. text: "attachment",
  4227. attachments: [
  4228. {
  4229. ref: "artifact://large",
  4230. fileName: "x".repeat(PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxBytes),
  4231. mime: "application/octet-stream",
  4232. bytes: 1,
  4233. },
  4234. ],
  4235. },
  4236. ],
  4237. ] as const)("%s 的 firstInput/text/附件引用越界时不执行", async (type, payload) => {
  4238. const host = makeHost();
  4239. const ack = await makeGateway(host).handleCommand(
  4240. commandParams({
  4241. commandId: `cmd-${type}-large`,
  4242. sessionId: type === "createSession" ? null : "session-1",
  4243. type,
  4244. payload,
  4245. }),
  4246. );
  4247. expect(ack).toMatchObject({ status: "failed", reasonCode: "proto.payloadTooLarge" });
  4248. expect(host.inputAdmissions).toEqual([]);
  4249. expect(host.executed).toEqual([]);
  4250. });
  4251. // 2026-07-05 语义修正:handleCommand 等待副作用完成后随响应返回终态 ACK
  4252. //(spec §6.2/§6.4「accepted 即时带 result」),settle 仍固化结果供 duplicate 重放。
  4253. it("同 commandId 并发与 ACK 丢失重试等待同一 final result,只执行一次", async () => {
  4254. const host = makeHost();
  4255. const gateway = makeGateway(host);
  4256. const log = new EventLog();
  4257. gateway.ingest("session-1", sessionCreated(log));
  4258. // 用手动 deferred 卡住副作用,验证在途重试语义(§6.3)。
  4259. let releaseExecute!: () => void;
  4260. host.executeImpl = async () => {
  4261. await new Promise<void>((resolveExecute) => {
  4262. releaseExecute = resolveExecute;
  4263. });
  4264. return { type: "forkAssistant" as const, sessionId: "child-same" };
  4265. };
  4266. const first = gateway.handleCommand(commandParams());
  4267. await vi.waitFor(() => expect(host.executed).toHaveLength(1));
  4268. let retrySettled = false;
  4269. const inflightRetryPromise = gateway.handleCommand(commandParams()).then((ack) => {
  4270. retrySettled = true;
  4271. return ack;
  4272. });
  4273. await new Promise<void>((resolve) => setTimeout(resolve, 0));
  4274. expect(retrySettled).toBe(false);
  4275. expect(host.executed).toHaveLength(1);
  4276. expect(host.executed[0]!.type).toBe("sendText");
  4277. expect(host.inputAdmissions).toEqual([{ commandId: "cmd-1", queueItemId: "queue_cmd-1" }]);
  4278. releaseExecute();
  4279. const [ack, inflightRetry] = await Promise.all([first, inflightRetryPromise]);
  4280. expect(ack).toMatchObject({
  4281. status: "accepted",
  4282. result: { type: "forkAssistant", sessionId: "child-same" },
  4283. });
  4284. expect(inflightRetry).toMatchObject({
  4285. status: "duplicate",
  4286. result: { type: "forkAssistant", sessionId: "child-same" },
  4287. });
  4288. // settle 固化后重试回 duplicate,副作用仍只执行一次。
  4289. const replay = await gateway.handleCommand(commandParams());
  4290. expect(replay.status).toBe("duplicate");
  4291. expect(replay.result).toEqual({ type: "forkAssistant", sessionId: "child-same" });
  4292. expect(host.executed).toHaveLength(1);
  4293. });
  4294. it("admission projection measure 异常 settle 同一 failed final 并释放 session FIFO", async () => {
  4295. const host = makeHost();
  4296. const gateway = makeGateway(host);
  4297. const log = new EventLog();
  4298. gateway.ingest("session-1", sessionCreated(log));
  4299. const measure = vi
  4300. .spyOn(ConversationTopicPublisher.prototype, "measureInputAdmissionProjectionBytes")
  4301. .mockImplementationOnce(() => {
  4302. throw new Error("measure exploded");
  4303. });
  4304. try {
  4305. const first = gateway
  4306. .handleCommand(commandParams({ commandId: "cmd-measure-fault" }))
  4307. .catch((error) => ({ thrown: String(error) }));
  4308. const duplicate = gateway
  4309. .handleCommand(commandParams({ commandId: "cmd-measure-fault" }))
  4310. .catch((error) => ({ thrown: String(error) }));
  4311. const pair = await Promise.race([
  4312. Promise.all([first, duplicate]),
  4313. new Promise<"timeout">((resolve) => setTimeout(() => resolve("timeout"), 100)),
  4314. ]);
  4315. expect(pair).toEqual([
  4316. expect.objectContaining({
  4317. commandId: "cmd-measure-fault",
  4318. status: "failed",
  4319. reasonCode: "fault.command.executionFailed",
  4320. message: "measure exploded",
  4321. }),
  4322. expect.objectContaining({
  4323. commandId: "cmd-measure-fault",
  4324. status: "failed",
  4325. reasonCode: "fault.command.executionFailed",
  4326. message: "measure exploded",
  4327. }),
  4328. ]);
  4329. expect(host.executed).toHaveLength(0);
  4330. const next = await gateway.handleCommand(
  4331. commandParams({ commandId: "cmd-after-measure-fault" }),
  4332. );
  4333. expect(next.status).toBe("accepted");
  4334. expect(host.executed).toHaveLength(1);
  4335. } finally {
  4336. measure.mockRestore();
  4337. }
  4338. });
  4339. it("输入执行失败:durable admission 收口 cancelled,不遗留 restart discarded 假象", async () => {
  4340. const host = makeHost();
  4341. const gateway = makeGateway(host);
  4342. const log = new EventLog();
  4343. gateway.ingest("session-1", sessionCreated(log));
  4344. host.executeImpl = async () => {
  4345. throw Object.assign(new Error("runtime rejected input"), {
  4346. reasonCode: "fault.command.inputRejected",
  4347. });
  4348. };
  4349. const ack = await gateway.handleCommand(commandParams({ commandId: "command-rejected" }));
  4350. expect(ack).toMatchObject({
  4351. commandId: "command-rejected",
  4352. status: "failed",
  4353. reasonCode: "fault.command.inputRejected",
  4354. });
  4355. expect(host.inputCancellations).toEqual([
  4356. {
  4357. commandId: "command-rejected",
  4358. queueItemId: "queue_command-rejected",
  4359. reason: "fault.command.inputRejected",
  4360. },
  4361. ]);
  4362. });
  4363. it("createSession:sessionId=null 放行,ACK 即时携带 result.sessionId", async () => {
  4364. const host = makeHost();
  4365. const gateway = makeGateway(host);
  4366. host.executeImpl = async () => ({
  4367. type: "createSession",
  4368. sessionId: "session-new",
  4369. });
  4370. const ack = await gateway.handleCommand(
  4371. commandParams({
  4372. commandId: "cmd-create",
  4373. sessionId: null,
  4374. type: "createSession",
  4375. payload: { workspaceId: "/tmp/ws" },
  4376. }),
  4377. );
  4378. expect(ack.status).toBe("accepted");
  4379. // spec §6.4:createSession 的 accepted ACK 必带 result.sessionId
  4380. //(曾经只回初始 ACK,客户端拿不到 sessionId —— M3 全链路验收抓出的 bug)。
  4381. expect(ack.result).toEqual({
  4382. type: "createSession",
  4383. sessionId: "session-new",
  4384. });
  4385. expect(host.executed).toHaveLength(1);
  4386. // settle 固化后 duplicate 回放携带执行结果。
  4387. const replay = await gateway.handleCommand(
  4388. commandParams({
  4389. commandId: "cmd-create",
  4390. sessionId: null,
  4391. type: "createSession",
  4392. payload: { workspaceId: "/tmp/ws" },
  4393. }),
  4394. );
  4395. expect(replay.status).toBe("duplicate");
  4396. expect(replay.result).toEqual({
  4397. type: "createSession",
  4398. sessionId: "session-new",
  4399. });
  4400. });
  4401. it("未知会话 → rejected proto.sessionNotFound,不触发执行", async () => {
  4402. const host = makeHost();
  4403. const gateway = makeGateway(host);
  4404. const ack = await gateway.handleCommand(commandParams({ sessionId: "ghost" }));
  4405. expect(ack.status).toBe("rejected");
  4406. expect(ack.reasonCode).toBe("proto.sessionNotFound");
  4407. expect(host.executed).toHaveLength(0);
  4408. });
  4409. it("未接线命令 → ACK failed fault.command.notImplemented(failed 重试保真)", async () => {
  4410. const host = makeHost();
  4411. const gateway = makeGateway(host);
  4412. const log = new EventLog();
  4413. gateway.ingest("session-1", sessionCreated(log));
  4414. host.executeImpl = async (envelope) => {
  4415. throw new V4CommandNotImplementedError(envelope.type);
  4416. };
  4417. // compact 是可排队输入命令,不做 CAS;否则 renderer 在 running snapshot 上提交后
  4418. // 会因并发 stream revision 变化而无意义 stale。
  4419. const ack = await gateway.handleCommand(
  4420. commandParams({
  4421. commandId: "cmd-compact",
  4422. type: "compact",
  4423. payload: {},
  4424. }),
  4425. );
  4426. expect(ack.status).toBe("failed");
  4427. expect(ack.reasonCode).toBe("fault.command.notImplemented");
  4428. expect(host.errors).toHaveLength(1);
  4429. expect(host.errors[0]!.scope).toBe("v4.command.execute");
  4430. const replay = await gateway.handleCommand(
  4431. commandParams({
  4432. commandId: "cmd-compact",
  4433. type: "compact",
  4434. payload: {},
  4435. }),
  4436. );
  4437. expect(replay.status).toBe("failed");
  4438. expect(replay.reasonCode).toBe("fault.command.notImplemented");
  4439. });
  4440. it("commands/query 保持输入顺序,并与 command in-flight 共用 gate", async () => {
  4441. const host = makeHost();
  4442. const gateway = makeGateway(host);
  4443. const log = new EventLog();
  4444. gateway.ingest("session-1", sessionCreated(log));
  4445. let releaseExecute!: () => void;
  4446. host.executeImpl = async () =>
  4447. new Promise<void>((resolve) => {
  4448. releaseExecute = resolve;
  4449. });
  4450. const executing = gateway.handleCommand(commandParams({ commandId: "command-running" }));
  4451. await vi.waitFor(() => expect(host.executed).toHaveLength(1));
  4452. host.persistentCommands.discarded.set("session-1\0command-discarded", {
  4453. commandId: "command-discarded",
  4454. status: "failed",
  4455. reasonCode: "fault.command.inputDiscardedOnRestart",
  4456. revisionAtDecision: 0,
  4457. });
  4458. let querySettled = false;
  4459. const resultPromise = gateway
  4460. .queryCommands({
  4461. commands: [
  4462. { sessionId: "session-1", commandId: "command-running" },
  4463. { sessionId: "session-1", commandId: "command-missing" },
  4464. { sessionId: "session-1", commandId: "command-discarded" },
  4465. ],
  4466. })
  4467. .then((result) => {
  4468. querySettled = true;
  4469. return result;
  4470. });
  4471. await new Promise<void>((resolve) => setTimeout(resolve, 0));
  4472. expect(querySettled).toBe(false);
  4473. releaseExecute();
  4474. await executing;
  4475. const result = await resultPromise;
  4476. expect(result.results.map((item) => item.result)).toEqual([
  4477. {
  4478. commandId: "command-running",
  4479. status: "accepted",
  4480. revisionAtDecision: 0,
  4481. },
  4482. "unknown",
  4483. {
  4484. commandId: "command-discarded",
  4485. status: "failed",
  4486. reasonCode: "fault.command.inputDiscardedOnRestart",
  4487. revisionAtDecision: 0,
  4488. },
  4489. ]);
  4490. });
  4491. it("busy input event pin 完整 intent;settle/LRU 不会把 live queue 变 unknown", async () => {
  4492. const host = makeHost();
  4493. const gateway = makeGateway(host);
  4494. const log = new EventLog();
  4495. gateway.ingest("session-1", sessionCreated(log));
  4496. host.executeImpl = async (envelope, admission) => {
  4497. const queueItemId = admission?.queueItemId ?? "missing-queue-id";
  4498. gateway.ingest(
  4499. "session-1",
  4500. log.push(
  4501. SessionEventType.TurnSteerQueued,
  4502. {
  4503. pendingInputId: queueItemId,
  4504. inputId: envelope.commandId,
  4505. input: "queued text",
  4506. inputPreview: "queued text",
  4507. inputSize: 11,
  4508. delivery: "queue",
  4509. targetTurnId: "turn-1",
  4510. queueLength: 1,
  4511. intent: {
  4512. sourceCommandId: envelope.commandId,
  4513. queueItemId,
  4514. clientId: envelope.clientId,
  4515. kind: "sendText",
  4516. admissionSeq: admission?.admissionSeq ?? -1,
  4517. admittedAt: admission?.admittedAt ?? -1,
  4518. requestedDelivery: "queue",
  4519. admittedDelivery: "queue",
  4520. },
  4521. },
  4522. { turnId: "turn-1" },
  4523. ),
  4524. );
  4525. return undefined;
  4526. };
  4527. const ack = await gateway.handleCommand(
  4528. commandParams({ commandId: "command-live", clientId: "mobile-client" }),
  4529. );
  4530. expect(ack.status).toBe("accepted");
  4531. const queried = await gateway.queryCommands({
  4532. commands: [{ sessionId: "session-1", commandId: "command-live" }],
  4533. });
  4534. expect(queried.results[0]?.result).toMatchObject({
  4535. commandId: "command-live",
  4536. status: "accepted",
  4537. });
  4538. const subscribed = await gateway.subscribe(subscribeParams());
  4539. expect(
  4540. subscribed.initialFrame?.payload.kind === "snapshot"
  4541. ? subscribed.initialFrame.payload.snapshot.queue.items[0]
  4542. : null,
  4543. ).toMatchObject({
  4544. sourceCommandId: "command-live",
  4545. queueItemId: "queue_command-live",
  4546. clientId: "mobile-client",
  4547. order: { admissionSeq: 1 },
  4548. dispatch: { state: "queued" },
  4549. });
  4550. });
  4551. it("send-now remove 不提前解 pin;只在 session_input 原子 promotion 后释放", async () => {
  4552. const host = makeHost();
  4553. const gateway = makeGateway(host);
  4554. const log = new EventLog();
  4555. gateway.ingest("session-1", sessionCreated(log));
  4556. host.executeImpl = async (envelope, admission) => {
  4557. gateway.ingest(
  4558. "session-1",
  4559. log.push(
  4560. SessionEventType.TurnSteerQueued,
  4561. {
  4562. pendingInputId: admission!.queueItemId,
  4563. inputId: envelope.commandId,
  4564. input: "queued text",
  4565. inputPreview: "queued text",
  4566. inputSize: 11,
  4567. delivery: "queue",
  4568. targetTurnId: "turn-1",
  4569. queueLength: 1,
  4570. intent: {
  4571. sourceCommandId: envelope.commandId,
  4572. queueItemId: admission!.queueItemId,
  4573. clientId: envelope.clientId,
  4574. kind: "sendText",
  4575. admissionSeq: admission!.admissionSeq,
  4576. admittedAt: admission!.admittedAt,
  4577. requestedDelivery: "queue",
  4578. admittedDelivery: "queue",
  4579. },
  4580. },
  4581. { turnId: "turn-1" },
  4582. ),
  4583. );
  4584. return undefined;
  4585. };
  4586. await gateway.handleCommand(commandParams({ commandId: "command-promoting" }));
  4587. gateway.ingest(
  4588. "session-1",
  4589. log.push(
  4590. SessionEventType.TurnSteerDiscarded,
  4591. {
  4592. pendingInputIds: ["queue_command-promoting"],
  4593. reason: "promoted",
  4594. targetTurnId: "turn-1",
  4595. },
  4596. { turnId: "turn-1" },
  4597. ),
  4598. );
  4599. host.executeImpl = async () => undefined;
  4600. for (let index = 0; index <= PROTOCOL_V4_LIMITS.idempotencyTablePerSession; index += 1) {
  4601. await gateway.handleCommand(
  4602. commandParams({
  4603. commandId: `pre-promotion-churn-${index}`,
  4604. payload: {},
  4605. type: "stop",
  4606. }),
  4607. );
  4608. }
  4609. const beforePromotion = await gateway.queryCommands({
  4610. commands: [{ sessionId: "session-1", commandId: "command-promoting" }],
  4611. });
  4612. expect(beforePromotion.results[0]?.result).toMatchObject({ status: "accepted" });
  4613. gateway.ingest(
  4614. "session-1",
  4615. log.push(SessionEventType.SessionInputPromoted, {
  4616. pendingInputId: "queue_command-promoting",
  4617. sourceCommandId: "command-promoting",
  4618. messageId: "message-promoting",
  4619. }),
  4620. );
  4621. for (let index = 0; index <= PROTOCOL_V4_LIMITS.idempotencyTablePerSession; index += 1) {
  4622. await gateway.handleCommand(
  4623. commandParams({
  4624. commandId: `post-promotion-churn-${index}`,
  4625. payload: {},
  4626. type: "stop",
  4627. }),
  4628. );
  4629. }
  4630. const afterPromotion = await gateway.queryCommands({
  4631. commands: [{ sessionId: "session-1", commandId: "command-promoting" }],
  4632. });
  4633. expect(afterPromotion.results[0]?.result).toBe("unknown");
  4634. });
  4635. });
  4636. // 会话工具设计 0.7:长回合的 turnHeader 滚出快照尾窗后,Host 的 wait 依赖 owner 在
  4637. // commands/query 中给出的回合状态;global bucket 不带该字段。
  4638. describe("commands/query 回合状态(header 在尾窗之外)", () => {
  4639. function turnComplete(log: EventLog, turnId: string): SessionEvent {
  4640. return log.push(
  4641. SessionEventType.TurnComplete,
  4642. { duration: 1, response: "done", resultType: "success", tokenCount: 1, toolCallCount: 0 },
  4643. { turnId },
  4644. );
  4645. }
  4646. it("按 sourceCommandId 返回全量投影中的回合状态", async () => {
  4647. const host = makeHost();
  4648. const gateway = makeGateway(host);
  4649. const log = new EventLog();
  4650. gateway.ingest("session-1", sessionCreated(log));
  4651. gateway.ingest(
  4652. "session-1",
  4653. log.push(
  4654. SessionEventType.TurnStarted,
  4655. { turnNumber: 1, input: "long", inputId: "command-long" },
  4656. { turnId: "turn-long" },
  4657. ),
  4658. );
  4659. gateway.ingest("session-1", turnComplete(log, "turn-long"));
  4660. for (let index = 0; index < PROTOCOL_V4_LIMITS.snapshotTailWindowRows; index += 1) {
  4661. const turnId = `turn-after-${index}`;
  4662. gateway.ingest(
  4663. "session-1",
  4664. log.push(
  4665. SessionEventType.TurnStarted,
  4666. { turnNumber: index + 2, input: "next", inputId: `command-after-${index}` },
  4667. { turnId },
  4668. ),
  4669. );
  4670. gateway.ingest("session-1", turnComplete(log, turnId));
  4671. }
  4672. const subscribed = await gateway.subscribe(subscribeParams());
  4673. const wire =
  4674. subscribed.initialFrame?.payload.kind === "snapshot"
  4675. ? subscribed.initialFrame.payload.snapshot
  4676. : undefined;
  4677. expect(wire?.rows.window.length).toBe(PROTOCOL_V4_LIMITS.snapshotTailWindowRows);
  4678. expect(
  4679. wire?.rows.window.some(
  4680. (row) => row.kind === "turnHeader" && row.sourceCommandId === "command-long",
  4681. ),
  4682. ).toBe(false);
  4683. const query = await gateway.queryCommands({
  4684. commands: [
  4685. { sessionId: "session-1", commandId: "command-long" },
  4686. { sessionId: null, commandId: "command-long" },
  4687. { sessionId: "session-1", commandId: "command-missing" },
  4688. ],
  4689. });
  4690. expect(query.results[0]?.turn).toEqual({
  4691. turnId: expect.any(String),
  4692. state: "completedSuccess",
  4693. });
  4694. expect(query.results[1]?.turn).toBeUndefined();
  4695. expect(query.results[2]?.turn).toBeUndefined();
  4696. });
  4697. });
  4698. // R-19(10 §4.2.3):config 种子接线——ensurePublisher 创建即注入、hydration 收尾补注,
  4699. // 种子不产 delta / 不 bump revision,日志事件值优先。
  4700. describe("config 种子(R-19 gateway 接线)", () => {
  4701. const SEED: SessionConfigSeed = {
  4702. provider: "prov-a",
  4703. model: "model-1",
  4704. thought: "high",
  4705. mode: "yolo",
  4706. };
  4707. it("live 路径:ingest 建 publisher 时种入,snapshot.config = runtime 真值且 revision 不动", async () => {
  4708. const host = makeHost();
  4709. host.configSeeds.set("session-1", SEED);
  4710. const gateway = makeGateway(host);
  4711. const log = new EventLog();
  4712. gateway.ingest("session-1", sessionCreated(log));
  4713. const result = await gateway.subscribe(subscribeParams());
  4714. expect(result.initialFrame!.payload.kind).toBe("snapshot");
  4715. if (result.initialFrame!.payload.kind !== "snapshot") return;
  4716. const snapshot = result.initialFrame!.payload.snapshot;
  4717. expect(snapshot.config).toMatchObject({
  4718. provider: "prov-a",
  4719. model: "model-1",
  4720. thought: "high",
  4721. mode: "yolo",
  4722. });
  4723. // 种子是初值不是变化:不产 delta、revision 保持 0(CAS 不变量不受种子影响)。
  4724. expect(snapshot.revision).toBe(0);
  4725. });
  4726. it("冷恢复路径:hydration 重放后补种——日志 ModelSelected 优先,未触碰的 mode 吃种子", async () => {
  4727. const host = makeHost();
  4728. host.configSeeds.set("session-1", SEED);
  4729. const log = new EventLog();
  4730. sessionCreated(log);
  4731. log.push(SessionEventType.ModelSelected, {
  4732. modelSelection: {
  4733. providerId: "prov-b",
  4734. modelId: "model-2",
  4735. options: { reasoningLevel: "low" },
  4736. },
  4737. });
  4738. host.persistedEvents.set("session-1", log.events);
  4739. const gateway = makeGateway(host);
  4740. const result = await gateway.subscribe(subscribeParams());
  4741. if (result.initialFrame!.payload.kind !== "snapshot") {
  4742. throw new Error("expected snapshot frame");
  4743. }
  4744. const snapshot = result.initialFrame!.payload.snapshot;
  4745. // 模型区:日志有 ModelSelected → 日志值权威(种子不覆盖)。
  4746. expect(snapshot.config).toMatchObject({
  4747. provider: "prov-b",
  4748. model: "model-2",
  4749. thought: "low",
  4750. });
  4751. // mode:日志无 SessionModeChanged → 吃种子(历史会话 resume 恢复的持久化偏好)。
  4752. expect(snapshot.config.mode).toBe("yolo");
  4753. });
  4754. it("种子钩子抛错:防御式吞掉进 onError,conversation 主路径不受影响", async () => {
  4755. const host = makeHost();
  4756. const gateway = new ConversationV4Gateway(
  4757. {
  4758. sessionExists: (sessionId) => host.sessions.has(sessionId),
  4759. emitWireFrame: (wire) => collectCompleteConversationFrame(host.frames, wire),
  4760. executeCommand: async () => undefined,
  4761. getSessionConfigSeed: () => {
  4762. throw new Error("seed boom");
  4763. },
  4764. onError: (scope, error) => host.errors.push({ scope, error }),
  4765. },
  4766. { now: () => 1_700_000_999_000, createLogEpoch: () => "epoch-1" },
  4767. );
  4768. const log = new EventLog();
  4769. gateway.ingest("session-1", sessionCreated(log));
  4770. const result = await gateway.subscribe(subscribeParams());
  4771. expect(result.initialFrame!.payload.kind).toBe("snapshot");
  4772. expect(host.errors.some((entry) => entry.scope === "v4.configSeed")).toBe(true);
  4773. });
  4774. });
  4775. describe("ConversationV4Gateway.collectMemoryDiagnostics", () => {
  4776. it("返回 publisher / detached 子 session / raw seq 状态表的只读大小", () => {
  4777. const gateway = makeGateway(makeHost());
  4778. expect(gateway.collectMemoryDiagnostics()).toEqual({
  4779. publishers: 0,
  4780. detachedLive: 0,
  4781. detachedTerminal: 0,
  4782. rawSeqStates: 0,
  4783. });
  4784. });
  4785. });
  4786. describe("detached subagent child publisher 生命周期(session-idle-deactivation.md)", () => {
  4787. function childTurnComplete(log: EventLog): SessionEvent {
  4788. return log.push(
  4789. SessionEventType.TurnComplete,
  4790. { duration: 1, response: "done", resultType: "success", tokenCount: 1, toolCallCount: 0 },
  4791. { turnId: "turn-1" },
  4792. );
  4793. }
  4794. it("父 record 释放时连带释放没有 record 的 detached child publisher", () => {
  4795. const host = makeHost();
  4796. const gateway = makeGateway(host);
  4797. gateway.ingest("session-1", sessionCreated(new EventLog("session-1")));
  4798. const childLog = new EventLog("child-1");
  4799. gateway.ingestDetachedLiveSession("child-1", sessionCreated(childLog), "session-1");
  4800. gateway.ingestDetachedLiveSession("child-1", textDelta(childLog, "x"), "session-1");
  4801. expect(gateway.collectMemoryDiagnostics()).toMatchObject({ publishers: 2, detachedLive: 1 });
  4802. gateway.disposeSession("session-1");
  4803. expect(gateway.collectMemoryDiagnostics()).toMatchObject({
  4804. publishers: 0,
  4805. detachedLive: 0,
  4806. detachedTerminal: 0,
  4807. });
  4808. });
  4809. it("child 已有自己的 record 时,父释放不碰它,交给 child 自己的生命周期", () => {
  4810. const host = makeHost();
  4811. const gateway = makeGateway(host);
  4812. gateway.ingest("session-1", sessionCreated(new EventLog("session-1")));
  4813. const childLog = new EventLog("child-2");
  4814. gateway.ingestDetachedLiveSession("child-2", sessionCreated(childLog), "session-1");
  4815. host.sessions.add("child-2");
  4816. gateway.disposeSession("session-1");
  4817. expect(gateway.collectMemoryDiagnostics()).toMatchObject({ publishers: 1, detachedLive: 1 });
  4818. gateway.disposeSession("child-2");
  4819. expect(gateway.collectMemoryDiagnostics()).toMatchObject({ publishers: 0, detachedLive: 0 });
  4820. });
  4821. it("时间兜底:child 终态后无订阅者且超过 grace 才释放;有订阅者不释放", async () => {
  4822. const host = makeHost();
  4823. const gateway = makeGateway(host);
  4824. gateway.ingest("session-1", sessionCreated(new EventLog("session-1")));
  4825. const childLog = new EventLog("child-3");
  4826. gateway.ingestDetachedLiveSession("child-3", sessionCreated(childLog), "session-1");
  4827. gateway.ingestDetachedLiveSession("child-3", textDelta(childLog, "x"), "session-1");
  4828. gateway.ingestDetachedLiveSession("child-3", childTurnComplete(childLog), "session-1");
  4829. const terminalAt = Date.now();
  4830. expect(gateway.collectMemoryDiagnostics()).toMatchObject({ detachedTerminal: 1 });
  4831. // grace 内不释放。
  4832. expect(gateway.pruneDetachedChildPublishers(terminalAt + 60_000)).toBe(0);
  4833. // 有订阅者时即使超过 grace 也不释放。
  4834. const { ack } = await gateway.subscribe(subscribeParams({ topic: "conversation/child-3" }));
  4835. expect(gateway.pruneDetachedChildPublishers(terminalAt + 3 * 60_000)).toBe(0);
  4836. expect(gateway.collectMemoryDiagnostics()).toMatchObject({ publishers: 2 });
  4837. gateway.unsubscribe({
  4838. topic: "conversation/child-3",
  4839. subscriptionId: ack.subscriptionId,
  4840. connectionId: "conn-1",
  4841. });
  4842. expect(gateway.pruneDetachedChildPublishers(terminalAt + 3 * 60_000)).toBe(1);
  4843. expect(gateway.collectMemoryDiagnostics()).toMatchObject({
  4844. publishers: 1,
  4845. detachedLive: 0,
  4846. detachedTerminal: 0,
  4847. });
  4848. // 父 record 后续释放不受影响(child 映射已摘除)。
  4849. gateway.disposeSession("session-1");
  4850. expect(gateway.collectMemoryDiagnostics()).toMatchObject({ publishers: 0 });
  4851. });
  4852. it("child 再次 turn_started 撤销终态记录,时间兜底不再释放它", () => {
  4853. const host = makeHost();
  4854. const gateway = makeGateway(host);
  4855. const childLog = new EventLog("child-4");
  4856. gateway.ingestDetachedLiveSession("child-4", sessionCreated(childLog), "session-1");
  4857. gateway.ingestDetachedLiveSession("child-4", childTurnComplete(childLog), "session-1");
  4858. gateway.ingestDetachedLiveSession(
  4859. "child-4",
  4860. childLog.push(
  4861. SessionEventType.TurnStarted,
  4862. { turnNumber: 2, input: "again" },
  4863. { turnId: "turn-2" },
  4864. ),
  4865. "session-1",
  4866. );
  4867. expect(gateway.collectMemoryDiagnostics()).toMatchObject({ detachedTerminal: 0 });
  4868. expect(gateway.pruneDetachedChildPublishers(Date.now() + 10 * 60_000)).toBe(0);
  4869. expect(gateway.collectMemoryDiagnostics()).toMatchObject({ publishers: 1, detachedLive: 1 });
  4870. });
  4871. });