v4-gateway.test.ts 163 KB

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