v4-gateway.test.ts 161 KB

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