v4-gateway.test.ts 173 KB

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