v4-gateway.test.ts 171 KB

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