conversation-topic-publisher.test.ts 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740
  1. // ConversationTopicPublisher 黄金测试(M2 传输外壳,10 §3 / 04 恢复 / 05 flush 管线)。
  2. // 核心断言面:
  3. // 1. subscribe(base) 裁决矩阵:epoch 不匹配 / seq 出保留窗 / seq 超前 → snapshot;窗内 → resume
  4. // 2. 帧区间记账 (fromSeq, toSeq] 无缝衔接(含「整帧被 profile 过滤」时区间照样覆盖)
  5. // 3. snapshot 帧 + 后续续流帧 apply 的终态 ≡ 全量直投(恢复协议黄金路径)
  6. // 4. 重订阅替换语义(R-01):旧 subId 作废、旧 buffer 清空
  7. // 5. resync 溢出降级:snapshot 重对齐后续流不断
  8. import { describe, expect, it } from "vitest";
  9. import type {
  10. EventId,
  11. SessionEvent,
  12. SessionEventType as SessionEventTypeUnion,
  13. SessionId,
  14. TraceId,
  15. TurnId,
  16. } from "@zcode/contracts";
  17. import { SessionEventType } from "@zcode/contracts";
  18. import type {
  19. ConversationDelta,
  20. ConversationSnapshot,
  21. ConversationTopicFrame,
  22. } from "@zcode/shared/zcode-protocol-v4";
  23. import {
  24. PROTOCOL_V4_LIMITS,
  25. applyConversationDeltas,
  26. conversationTopicFrameSchema,
  27. utf8JsonByteLength,
  28. } from "@zcode/shared/zcode-protocol-v4";
  29. import {
  30. appendConversationSubscriberBuffer,
  31. ConversationTopicPublisher,
  32. conversationSubscriberBufferByteLimit,
  33. PROJECTION_TERMINAL_RESERVE_BYTES,
  34. ProductProjection,
  35. } from "../src/zcode-protocol-v4/index.js";
  36. // ── 事件构造 ──
  37. class EventLog {
  38. private seq = 0;
  39. readonly events: SessionEvent[] = [];
  40. constructor(private readonly sessionId = "session-1") {}
  41. push(
  42. type: SessionEventTypeUnion,
  43. payload: unknown,
  44. opts: { turnId?: string } = {},
  45. ): SessionEvent {
  46. this.seq += 1;
  47. const event: SessionEvent = {
  48. id: `event-${this.seq}` as EventId,
  49. sessionId: this.sessionId as SessionId,
  50. turnId: opts.turnId as TurnId | undefined,
  51. type,
  52. timestamp: new Date(1_700_000_000_000 + this.seq * 1000),
  53. traceId: "trace-1" as TraceId,
  54. sequenceNumber: this.seq,
  55. payload,
  56. };
  57. this.events.push(event);
  58. return event;
  59. }
  60. }
  61. function turnEvents(log: EventLog, turnNumber: number): SessionEvent[] {
  62. const turnId = `turn-${turnNumber}`;
  63. const start = log.events.length;
  64. log.push(SessionEventType.TurnStarted, { turnNumber, input: `任务 ${turnNumber}` }, { turnId });
  65. log.push(
  66. SessionEventType.ModelStreaming,
  67. { kind: "text_start", delta: "", done: false },
  68. { turnId },
  69. );
  70. log.push(
  71. SessionEventType.ModelStreaming,
  72. { kind: "text_delta", delta: `回答 ${turnNumber} 上半`, done: false },
  73. { turnId },
  74. );
  75. log.push(
  76. SessionEventType.ModelStreaming,
  77. { kind: "text_delta", delta: ` 下半`, done: false },
  78. { turnId },
  79. );
  80. log.push(
  81. SessionEventType.TurnComplete,
  82. {
  83. response: `回答 ${turnNumber}`,
  84. tokenCount: 10,
  85. toolCallCount: 0,
  86. duration: 100,
  87. resultType: "success",
  88. },
  89. { turnId },
  90. );
  91. return log.events.slice(start);
  92. }
  93. function makeLog(turns: number): EventLog {
  94. const log = new EventLog();
  95. log.push(SessionEventType.SessionCreated, {
  96. mode: "default",
  97. contextWindow: 200_000,
  98. });
  99. for (let i = 1; i <= turns; i++) turnEvents(log, i);
  100. return log;
  101. }
  102. /** 权威终态:直接跑 reducer 全量重放。 */
  103. function authoritativeSnapshot(events: readonly SessionEvent[]): ConversationSnapshot {
  104. const projection = new ProductProjection("session-1", "epoch-1");
  105. for (const event of events) projection.applyEvent(event);
  106. return projection.getSnapshot();
  107. }
  108. /** 客户端 apply 规则(10 §3.2):snapshot 整体替换;deltas 帧要求 fromSeq === store.seq。 */
  109. function clientApply(
  110. store: { seq: number; snapshot: ConversationSnapshot | null },
  111. frame: ConversationTopicFrame,
  112. ): void {
  113. expect(() => conversationTopicFrameSchema.parse(frame)).not.toThrow();
  114. if (frame.payload.kind === "snapshot") {
  115. store.snapshot = frame.payload.snapshot;
  116. store.seq = frame.toSeq;
  117. return;
  118. }
  119. if (frame.toSeq <= store.seq) return; // 迟到/重复帧
  120. expect(frame.fromSeq).toBe(store.seq); // 断档即测试失败(本套件不该出现断档)
  121. expect(store.snapshot).not.toBeNull();
  122. // seq 语义 = 「所在帧 toSeq」(10 §4.2 R-03),不经 delta 传播,客户端 apply 后自行对齐。
  123. store.snapshot = {
  124. ...applyConversationDeltas(store.snapshot as ConversationSnapshot, frame.payload.deltas),
  125. seq: frame.toSeq,
  126. };
  127. store.seq = frame.toSeq;
  128. }
  129. describe("分享导入来源种子", () => {
  130. it("在 publisher 快照中保留来源提示且不产生 conversation delta", () => {
  131. const publisher = new ConversationTopicPublisher("session-1", "epoch-1");
  132. const before = publisher.getSnapshot();
  133. publisher.seedSharedContextImport({ title: "导入的分享" });
  134. const snapshot = publisher.getSnapshot();
  135. expect(snapshot.sharedContextImport).toEqual({ title: "导入的分享" });
  136. expect(snapshot.revision).toBe(before.revision);
  137. expect(snapshot.seq).toBe(before.seq);
  138. expect(snapshot.rows.window).toEqual([]);
  139. });
  140. });
  141. describe("subscribe(base) 裁决矩阵", () => {
  142. function publisherWith(events: readonly SessionEvent[], retention?: number) {
  143. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  144. now: () => 1_700_000_999_000,
  145. retention,
  146. });
  147. for (const event of events) publisher.ingest(event);
  148. return publisher;
  149. }
  150. it("无 base → snapshot(fromSeq=0,snapshot.seq=toSeq)", () => {
  151. const publisher = publisherWith(makeLog(1).events);
  152. const { ack, frame } = publisher.subscribe({ connectionId: "conn-1" });
  153. expect(ack.mode).toBe("snapshot");
  154. expect(ack.logEpoch).toBe("epoch-1");
  155. expect(frame).not.toBeNull();
  156. expect(frame!.fromSeq).toBe(0);
  157. expect(frame!.payload.kind).toBe("snapshot");
  158. if (frame!.payload.kind === "snapshot") {
  159. expect(frame!.payload.snapshot.seq).toBe(frame!.toSeq);
  160. }
  161. });
  162. it("epoch 不匹配 → snapshot(CLI 重启后 base 必然失效)", () => {
  163. const publisher = publisherWith(makeLog(1).events);
  164. const { ack } = publisher.subscribe({
  165. connectionId: "conn-1",
  166. base: { logEpoch: "epoch-0", seq: 3 },
  167. });
  168. expect(ack.mode).toBe("snapshot");
  169. });
  170. it("base.seq 超前当前水位 → snapshot(水位不变量防御)", () => {
  171. const publisher = publisherWith(makeLog(1).events);
  172. const { ack } = publisher.subscribe({
  173. connectionId: "conn-1",
  174. base: { logEpoch: "epoch-1", seq: 999 },
  175. });
  176. expect(ack.mode).toBe("snapshot");
  177. });
  178. it("base.seq 掉出保留窗 → snapshot;窗内 → resume", () => {
  179. // 3 turn(1 + 3×5 = 16 事件),保留窗压到 5:floor = seq 11。
  180. const publisher = publisherWith(makeLog(3).events, 5);
  181. expect(
  182. publisher.subscribe({
  183. connectionId: "conn-out",
  184. base: { logEpoch: "epoch-1", seq: 10 },
  185. }).ack.mode,
  186. ).toBe("snapshot");
  187. expect(
  188. publisher.subscribe({
  189. connectionId: "conn-in",
  190. base: { logEpoch: "epoch-1", seq: 11 },
  191. }).ack.mode,
  192. ).toBe("resume");
  193. });
  194. it("base.seq === 当前水位 → resume 且无初始帧", () => {
  195. const log = makeLog(1);
  196. const publisher = publisherWith(log.events);
  197. const { ack, frame } = publisher.subscribe({
  198. connectionId: "conn-1",
  199. base: { logEpoch: "epoch-1", seq: log.events.length },
  200. });
  201. expect(ack.mode).toBe("resume");
  202. expect(frame).toBeNull();
  203. });
  204. });
  205. describe("恢复协议黄金路径:snapshot/resume + 续流 ≡ 全量重放", () => {
  206. it("中途订阅(snapshot)+ 续流帧终态一致", () => {
  207. const log = makeLog(2);
  208. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  209. now: () => 0,
  210. });
  211. const store = { seq: 0, snapshot: null as ConversationSnapshot | null };
  212. // 第 1 个 turn 结束后才订阅。
  213. const firstHalf = log.events.slice(0, 6);
  214. const secondHalf = log.events.slice(6);
  215. for (const event of firstHalf) publisher.ingest(event);
  216. const { frame } = publisher.subscribe({
  217. connectionId: "conn-1",
  218. deliveryProfile: "continuous",
  219. });
  220. clientApply(store, frame!);
  221. const subId = publisher.subscribe({
  222. connectionId: "conn-1",
  223. base: { logEpoch: "epoch-1", seq: store.seq },
  224. deliveryProfile: "continuous",
  225. }); // 重订阅走 resume(水位对齐 → 无初始帧),拿到活跃 subId
  226. expect(subId.ack.mode).toBe("resume");
  227. // 续流:每个事件后 flush(最细粒度帧)。
  228. for (const event of secondHalf) {
  229. publisher.ingest(event);
  230. const next = publisher.flush(subId.ack.subscriptionId);
  231. if (next) clientApply(store, next);
  232. }
  233. expect(store.snapshot).toEqual(authoritativeSnapshot(log.events));
  234. });
  235. it("断线重连(resume):base 窗内续传帧 + 后续流帧终态一致", () => {
  236. const log = makeLog(3);
  237. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  238. now: () => 0,
  239. });
  240. const store = { seq: 0, snapshot: null as ConversationSnapshot | null };
  241. // 先在线跟到第 8 个事件。
  242. const online = log.events.slice(0, 8);
  243. const offline = log.events.slice(8, 12);
  244. const afterReconnect = log.events.slice(12);
  245. for (const event of online.slice(0, 1)) publisher.ingest(event);
  246. const first = publisher.subscribe({ connectionId: "conn-1" });
  247. clientApply(store, first.frame!);
  248. for (const event of online.slice(1)) {
  249. publisher.ingest(event);
  250. const frame = publisher.flush(first.ack.subscriptionId);
  251. if (frame) clientApply(store, frame);
  252. }
  253. // 掉线期间事件继续产生(订阅还挂着,但客户端收不到 → 直接作废旧订阅模拟断连)。
  254. publisher.unsubscribe(first.ack.subscriptionId);
  255. for (const event of offline) publisher.ingest(event);
  256. // 重连带 base:应 resume 并一帧补齐缺口。
  257. const second = publisher.subscribe({
  258. connectionId: "conn-1",
  259. base: { logEpoch: "epoch-1", seq: store.seq },
  260. });
  261. expect(second.ack.mode).toBe("resume");
  262. clientApply(store, second.frame!);
  263. expect(store.seq).toBe(12);
  264. for (const event of afterReconnect) {
  265. publisher.ingest(event);
  266. const frame = publisher.flush(second.ack.subscriptionId);
  267. if (frame) clientApply(store, frame);
  268. }
  269. expect(store.snapshot).toEqual(authoritativeSnapshot(log.events));
  270. });
  271. it("replayable 订阅者:resume 重放过 profile 过滤,终态仍与全量重放一致", () => {
  272. // tool 输入流式在掉线窗口内发生:inputText row.delta 被 replayable 过滤,
  273. // 靠 ToolCallScheduled 的 row.upserted 收口(profiles.ts 收口不变量)。
  274. const log = new EventLog();
  275. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  276. const turnId = "turn-1";
  277. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId });
  278. const preDropCount = log.events.length;
  279. log.push(
  280. SessionEventType.ModelStreaming,
  281. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-1", toolName: "bash" },
  282. { turnId },
  283. );
  284. log.push(
  285. SessionEventType.ModelStreaming,
  286. { kind: "tool_input_delta", delta: '{"command":"ls"}', done: false, toolCallId: "tc-1" },
  287. { turnId },
  288. );
  289. log.push(
  290. SessionEventType.ToolCallScheduled,
  291. {
  292. toolCallId: "tc-1",
  293. toolName: "bash",
  294. input: { command: "ls" },
  295. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  296. },
  297. { turnId },
  298. );
  299. log.push(
  300. SessionEventType.TurnComplete,
  301. { response: "", tokenCount: 0, toolCallCount: 1, duration: 10, resultType: "success" },
  302. { turnId },
  303. );
  304. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  305. now: () => 0,
  306. });
  307. const store = { seq: 0, snapshot: null as ConversationSnapshot | null };
  308. for (const event of log.events.slice(0, preDropCount)) publisher.ingest(event);
  309. const first = publisher.subscribe({ connectionId: "conn-1" });
  310. clientApply(store, first.frame!);
  311. publisher.unsubscribe(first.ack.subscriptionId);
  312. for (const event of log.events.slice(preDropCount)) publisher.ingest(event);
  313. const second = publisher.subscribe({
  314. connectionId: "conn-1",
  315. base: { logEpoch: "epoch-1", seq: store.seq },
  316. });
  317. expect(second.ack.mode).toBe("resume");
  318. clientApply(store, second.frame!);
  319. expect(store.snapshot).toEqual(authoritativeSnapshot(log.events));
  320. });
  321. });
  322. describe("帧区间记账与替换语义", () => {
  323. it("批量 cold rehydrate 与逐事件 reducer 终态一致,中间 base 经 snapshot boundary 恢复", () => {
  324. const log = new EventLog();
  325. log.push(SessionEventType.SessionCreated, {
  326. mode: "default",
  327. contextWindow: 200_000,
  328. });
  329. for (let turnNumber = 1; turnNumber <= 40; turnNumber += 1) {
  330. const turnId = `turn-${turnNumber}`;
  331. log.push(
  332. SessionEventType.TurnStarted,
  333. {
  334. turnNumber,
  335. input: `任务 ${turnNumber}`,
  336. messageId: `message-user-${turnNumber}`,
  337. },
  338. { turnId },
  339. );
  340. log.push(
  341. SessionEventType.ModelStreaming,
  342. {
  343. kind: "text_start",
  344. delta: "",
  345. done: false,
  346. assistantMessageId: `message-assistant-${turnNumber}`,
  347. },
  348. { turnId },
  349. );
  350. log.push(
  351. SessionEventType.ModelStreaming,
  352. { kind: "text_delta", delta: `回答 ${turnNumber}`, done: false },
  353. { turnId },
  354. );
  355. const toolCallId = `tool-${turnNumber}`;
  356. log.push(
  357. SessionEventType.ModelStreaming,
  358. {
  359. kind: "tool_input_start",
  360. delta: "",
  361. done: false,
  362. toolCallId,
  363. toolName: "bash",
  364. },
  365. { turnId },
  366. );
  367. log.push(
  368. SessionEventType.ModelStreaming,
  369. {
  370. kind: "tool_input_delta",
  371. delta: `{"command":"printf ${turnNumber}"}`,
  372. done: false,
  373. toolCallId,
  374. },
  375. { turnId },
  376. );
  377. log.push(
  378. SessionEventType.ToolCallScheduled,
  379. {
  380. toolCallId,
  381. toolName: "bash",
  382. input: { command: `printf ${turnNumber}` },
  383. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  384. },
  385. { turnId },
  386. );
  387. log.push(
  388. SessionEventType.ToolCallResult,
  389. {
  390. toolCallId,
  391. result: { success: true, content: `tool output ${turnNumber}` },
  392. duration: 10,
  393. },
  394. { turnId },
  395. );
  396. log.push(
  397. SessionEventType.TurnComplete,
  398. {
  399. response: `回答 ${turnNumber}`,
  400. tokenCount: 10,
  401. toolCallCount: 1,
  402. duration: 100,
  403. resultType: "success",
  404. },
  405. { turnId },
  406. );
  407. }
  408. const strict = new ConversationTopicPublisher("session-1", "epoch-1", { now: () => 0 });
  409. for (const event of log.events) strict.ingest(event);
  410. const cold = new ConversationTopicPublisher("session-1", "epoch-1", { now: () => 0 });
  411. cold.rehydrate(log.events);
  412. expect(cold.getSnapshot()).toEqual(strict.getSnapshot());
  413. const baseEventCount = 73;
  414. const base = new ConversationTopicPublisher("session-1", "epoch-1", { now: () => 0 });
  415. for (const event of log.events.slice(0, baseEventCount)) base.ingest(event);
  416. const store = { seq: 0, snapshot: null as ConversationSnapshot | null };
  417. clientApply(store, base.subscribe({ connectionId: "base" }).frame!);
  418. const resumed = cold.subscribe({
  419. connectionId: "mobile-replay",
  420. deliveryProfile: "replayable",
  421. base: { logEpoch: "epoch-1", seq: store.seq },
  422. });
  423. expect(resumed.ack.mode).toBe("snapshot");
  424. clientApply(store, resumed.frame!);
  425. const expectedFrame = cold.subscribe({ connectionId: "fresh-snapshot" }).frame!;
  426. expect(expectedFrame.payload.kind).toBe("snapshot");
  427. expect(store.snapshot).toEqual(
  428. expectedFrame.payload.kind === "snapshot" ? expectedFrame.payload.snapshot : null,
  429. );
  430. });
  431. it("rehydrate replay 非 size 异常时保留旧 projection/log/subscription reservation", () => {
  432. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", { now: () => 0 });
  433. const live = new EventLog();
  434. publisher.ingest(
  435. live.push(SessionEventType.SessionCreated, {
  436. mode: "default",
  437. contextWindow: 200_000,
  438. }),
  439. );
  440. const subscribed = publisher.subscribe({ connectionId: "desktop" });
  441. publisher.ingest(
  442. live.push(SessionEventType.SessionTitleUpdated, {
  443. previousTitle: "old",
  444. title: "live title",
  445. source: "custom",
  446. }),
  447. );
  448. const reservation = publisher.reserveFlush(subscribed.ack.subscriptionId);
  449. const before = publisher.getSnapshot();
  450. const persisted = new EventLog();
  451. persisted.push(SessionEventType.SessionCreated, {
  452. mode: "default",
  453. contextWindow: 200_000,
  454. });
  455. persisted.push(SessionEventType.TurnError, { turnPhase: "model" });
  456. expect(() => publisher.rehydrate(persisted.events)).toThrow(TypeError);
  457. expect(publisher.getSnapshot()).toEqual(before);
  458. expect(publisher.hasSubscription(subscribed.ack.subscriptionId, "desktop")).toBe(true);
  459. expect(publisher.reserveFlush(subscribed.ack.subscriptionId)).toBe(reservation);
  460. expect(reservation?.commit()).toBe(true);
  461. });
  462. it("continuous 订阅者:tool_input_delta 透传 inputText 供桌面实时预览", () => {
  463. const log = new EventLog();
  464. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  465. const turnId = "turn-1";
  466. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "write" }, { turnId });
  467. log.push(
  468. SessionEventType.ModelStreaming,
  469. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-1", toolName: "Write" },
  470. { turnId },
  471. );
  472. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  473. now: () => 0,
  474. });
  475. for (const event of log.events) publisher.ingest(event);
  476. const { ack } = publisher.subscribe({
  477. connectionId: "conn-1",
  478. deliveryProfile: "continuous",
  479. });
  480. const streamDelta = log.push(
  481. SessionEventType.ModelStreaming,
  482. {
  483. kind: "tool_input_delta",
  484. delta: '{"file_path":"src/app.ts","content":"line 1\\n',
  485. done: false,
  486. toolCallId: "tc-1",
  487. },
  488. { turnId },
  489. );
  490. publisher.ingest(streamDelta);
  491. const frame = publisher.flush(ack.subscriptionId);
  492. expect(frame?.payload.kind).toBe("deltas");
  493. const deltas = frame?.payload.kind === "deltas" ? frame.payload.deltas : [];
  494. expect(deltas).toContainEqual({
  495. op: "row.delta",
  496. rowId: expect.any(Number),
  497. path: "inputText",
  498. append: '{"file_path":"src/app.ts","content":"line 1\\n',
  499. });
  500. });
  501. it("flush 帧 (fromSeq, toSeq] 无缝衔接;无新内容返回 null", () => {
  502. const log = makeLog(1);
  503. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  504. now: () => 0,
  505. });
  506. publisher.ingest(log.events[0]!);
  507. const { ack } = publisher.subscribe({
  508. connectionId: "conn-1",
  509. deliveryProfile: "continuous",
  510. });
  511. let watermark = 1;
  512. for (const event of log.events.slice(1)) {
  513. publisher.ingest(event);
  514. const frame = publisher.flush(ack.subscriptionId);
  515. expect(frame).not.toBeNull();
  516. expect(frame!.fromSeq).toBe(watermark);
  517. expect(frame!.toSeq).toBe(event.sequenceNumber);
  518. watermark = frame!.toSeq;
  519. }
  520. expect(publisher.flush(ack.subscriptionId)).toBeNull();
  521. });
  522. it("整帧被 profile 过滤时区间照样推进(连续性判定不受过滤影响)", () => {
  523. // replayable 下 tool_input_delta 只产 row.delta(inputText) → 被过滤为空,
  524. // 但帧区间必须覆盖该 seq,否则客户端会误判断档。
  525. const log = new EventLog();
  526. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  527. const turnId = "turn-1";
  528. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId });
  529. log.push(
  530. SessionEventType.ModelStreaming,
  531. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-1", toolName: "bash" },
  532. { turnId },
  533. );
  534. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  535. now: () => 0,
  536. });
  537. for (const event of log.events) publisher.ingest(event);
  538. const { ack } = publisher.subscribe({ connectionId: "conn-1" }); // replayable
  539. // 纯 inputText 流事件:deltas 全被过滤。
  540. const pureStream = log.push(
  541. SessionEventType.ModelStreaming,
  542. { kind: "tool_input_delta", delta: '{"a":1}', done: false, toolCallId: "tc-1" },
  543. { turnId },
  544. );
  545. publisher.ingest(pureStream);
  546. const frame = publisher.flush(ack.subscriptionId);
  547. expect(frame).not.toBeNull();
  548. expect(frame!.payload).toEqual({ kind: "deltas", deltas: [] });
  549. expect(frame!.toSeq).toBe(pureStream.sequenceNumber);
  550. // 随后的结构性事件从新水位续接。
  551. const scheduled = log.push(
  552. SessionEventType.ToolCallScheduled,
  553. {
  554. toolCallId: "tc-1",
  555. toolName: "bash",
  556. input: { a: 1 },
  557. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  558. },
  559. { turnId },
  560. );
  561. publisher.ingest(scheduled);
  562. const next = publisher.flush(ack.subscriptionId);
  563. expect(next!.fromSeq).toBe(pureStream.sequenceNumber);
  564. expect(next!.toSeq).toBe(scheduled.sequenceNumber);
  565. });
  566. it("replayable 订阅者:scheduled 定稿必须在 upsert 中携带完整 inputText", () => {
  567. const log = new EventLog();
  568. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  569. const turnId = "turn-1";
  570. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "write" }, { turnId });
  571. log.push(
  572. SessionEventType.ModelStreaming,
  573. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-1", toolName: "Write" },
  574. { turnId },
  575. );
  576. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  577. now: () => 0,
  578. });
  579. for (const event of log.events) publisher.ingest(event);
  580. const { ack } = publisher.subscribe({ connectionId: "conn-1" }); // replayable
  581. const input = { file_path: "src/app.ts", content: "line 1\nline 2" };
  582. const scheduled = log.push(
  583. SessionEventType.ToolCallScheduled,
  584. {
  585. toolCallId: "tc-1",
  586. toolName: "Write",
  587. input,
  588. schedule: { parallelGroups: [["tc-1"]], executionOrder: ["tc-1"] },
  589. },
  590. { turnId },
  591. );
  592. publisher.ingest(scheduled);
  593. const frame = publisher.flush(ack.subscriptionId);
  594. expect(frame?.payload.kind).toBe("deltas");
  595. const deltas = frame?.payload.kind === "deltas" ? frame.payload.deltas : [];
  596. const upsert = deltas.find(
  597. (delta) => delta.op === "row.upserted" && delta.row.kind === "toolCall",
  598. );
  599. expect(upsert).toBeDefined();
  600. if (upsert?.op === "row.upserted" && upsert.row.kind === "toolCall") {
  601. expect(upsert.row.input).toEqual(input);
  602. expect(upsert.row.inputText).toBe(JSON.stringify(input));
  603. }
  604. });
  605. it("continuous 订阅者:model.streaming tool_call 用完整输入收口已有工具行", () => {
  606. const log = new EventLog();
  607. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1000 });
  608. const turnId = "turn-1";
  609. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "write" }, { turnId });
  610. log.push(
  611. SessionEventType.ModelStreaming,
  612. { kind: "tool_input_start", delta: "", done: false, toolCallId: "tc-1", toolName: "Write" },
  613. { turnId },
  614. );
  615. log.push(
  616. SessionEventType.ModelStreaming,
  617. {
  618. kind: "tool_input_delta",
  619. delta: '{"file_path":"src/app.ts"',
  620. done: false,
  621. toolCallId: "tc-1",
  622. },
  623. { turnId },
  624. );
  625. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  626. now: () => 0,
  627. });
  628. for (const event of log.events) publisher.ingest(event);
  629. const { ack } = publisher.subscribe({
  630. connectionId: "conn-1",
  631. deliveryProfile: "continuous",
  632. });
  633. const input = { file_path: "src/app.ts", content: "done" };
  634. const finalToolCall = log.push(
  635. SessionEventType.ModelStreaming,
  636. {
  637. kind: "tool_call",
  638. delta: "",
  639. done: true,
  640. toolCallId: "tc-1",
  641. toolName: "Write",
  642. input,
  643. },
  644. { turnId },
  645. );
  646. publisher.ingest(finalToolCall);
  647. const frame = publisher.flush(ack.subscriptionId);
  648. expect(frame?.payload.kind).toBe("deltas");
  649. const deltas = frame?.payload.kind === "deltas" ? frame.payload.deltas : [];
  650. const upsert = deltas.find(
  651. (delta) => delta.op === "row.upserted" && delta.row.kind === "toolCall",
  652. );
  653. expect(upsert).toBeDefined();
  654. if (upsert?.op === "row.upserted" && upsert.row.kind === "toolCall") {
  655. expect(upsert.row.input).toEqual(input);
  656. expect(upsert.row.inputText).toBe(JSON.stringify(input));
  657. }
  658. });
  659. it("重订阅替换(R-01):旧 subId 作废,不再产帧", () => {
  660. const log = makeLog(1);
  661. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  662. now: () => 0,
  663. });
  664. publisher.ingest(log.events[0]!);
  665. const first = publisher.subscribe({ connectionId: "conn-1" });
  666. const second = publisher.subscribe({ connectionId: "conn-1" });
  667. expect(second.ack.subscriptionId).not.toBe(first.ack.subscriptionId);
  668. expect(publisher.hasSubscription(first.ack.subscriptionId)).toBe(false);
  669. publisher.ingest(log.events[1]!);
  670. expect(publisher.flush(first.ack.subscriptionId)).toBeNull();
  671. expect(publisher.flush(second.ack.subscriptionId)).not.toBeNull();
  672. });
  673. it("resync 溢出降级:snapshot 重对齐后续流不断", () => {
  674. const log = makeLog(2);
  675. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  676. now: () => 0,
  677. });
  678. const store = { seq: 0, snapshot: null as ConversationSnapshot | null };
  679. publisher.ingest(log.events[0]!);
  680. const { ack, frame } = publisher.subscribe({
  681. connectionId: "conn-1",
  682. deliveryProfile: "continuous",
  683. });
  684. clientApply(store, frame!);
  685. // 事件推进但不 flush(模拟缓冲堆积),然后触发 resync。
  686. for (const event of log.events.slice(1, 8)) publisher.ingest(event);
  687. const resyncFrame = publisher.resync(ack.subscriptionId);
  688. clientApply(store, resyncFrame!);
  689. expect(store.seq).toBe(8);
  690. // resync 后 buffer 清空:无新事件时 flush 为 null。
  691. expect(publisher.flush(ack.subscriptionId)).toBeNull();
  692. for (const event of log.events.slice(8)) {
  693. publisher.ingest(event);
  694. const next = publisher.flush(ack.subscriptionId);
  695. if (next) clientApply(store, next);
  696. }
  697. expect(store.snapshot).toEqual(authoritativeSnapshot(log.events));
  698. });
  699. it("same-sub resync 从客户端 base 重建 resume,并作废旧 reservation", () => {
  700. const log = makeLog(2);
  701. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", { now: () => 0 });
  702. for (const event of log.events.slice(0, 4)) publisher.ingest(event);
  703. const initial = publisher.subscribe({
  704. connectionId: "mobile",
  705. deliveryProfile: "replayable",
  706. });
  707. for (const event of log.events.slice(4, 8)) publisher.ingest(event);
  708. const oldReservation = publisher.reserveFlush(initial.ack.subscriptionId);
  709. expect(oldReservation?.frame.fromSeq).toBe(4);
  710. const recovered = publisher.resyncReserved(initial.ack.subscriptionId, {
  711. base: { logEpoch: "epoch-1", seq: 6 },
  712. });
  713. expect(recovered?.ack).toEqual({
  714. subscriptionId: initial.ack.subscriptionId,
  715. mode: "resume",
  716. logEpoch: "epoch-1",
  717. });
  718. expect(recovered?.reservation?.frame).toMatchObject({
  719. subscriptionId: initial.ack.subscriptionId,
  720. fromSeq: 6,
  721. toSeq: 8,
  722. payload: { kind: "deltas" },
  723. });
  724. expect(oldReservation?.commit()).toBe(false);
  725. publisher.ingest(log.events[8]!);
  726. expect(recovered?.reservation?.commit()).toBe(true);
  727. expect(publisher.flush(initial.ack.subscriptionId)).toMatchObject({
  728. fromSeq: 8,
  729. toSeq: 9,
  730. });
  731. });
  732. it("same-sub recovery admission 失败可 rollback 原 reservation 与未发 buffer", () => {
  733. const log = makeLog(1);
  734. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", { now: () => 0 });
  735. publisher.ingest(log.events[0]!);
  736. const initial = publisher.subscribe({ connectionId: "mobile" });
  737. publisher.ingest(log.events[1]!);
  738. const oldReservation = publisher.reserveFlush(initial.ack.subscriptionId)!;
  739. const recovered = publisher.resyncReserved(initial.ack.subscriptionId, {
  740. base: null,
  741. forceSnapshot: true,
  742. })!;
  743. expect(oldReservation.commit()).toBe(false);
  744. // encode/admission 窗口内的新事件进入 recovery 后 buffer;rollback 不能覆盖丢失。
  745. publisher.ingest(log.events[2]!);
  746. expect(recovered.rollback()).toBe(true);
  747. expect(recovered.reservation?.commit()).toBe(false);
  748. expect(publisher.reserveFlush(initial.ack.subscriptionId)).toBe(oldReservation);
  749. expect(oldReservation.commit()).toBe(true);
  750. const afterRollback = publisher.flush(initial.ack.subscriptionId);
  751. expect(afterRollback).toMatchObject({
  752. fromSeq: 2,
  753. toSeq: 3,
  754. });
  755. expect(afterRollback?.payload.kind).toBe("deltas");
  756. if (afterRollback?.payload.kind === "deltas") {
  757. expect(afterRollback.payload.deltas.length).toBeGreaterThan(0);
  758. }
  759. });
  760. it.each([
  761. ["null base", { base: null }],
  762. ["old epoch", { base: { logEpoch: "old", seq: 6 } }],
  763. ["force snapshot", { base: { logEpoch: "epoch-1", seq: 6 }, forceSnapshot: true }],
  764. ])("same-sub resync %s 回最新 snapshot", (_case, request) => {
  765. const log = makeLog(1);
  766. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", { now: () => 0 });
  767. for (const event of log.events) publisher.ingest(event);
  768. const initial = publisher.subscribe({ connectionId: "mobile" });
  769. const recovered = publisher.resyncReserved(initial.ack.subscriptionId, request);
  770. expect(recovered?.ack.mode).toBe("snapshot");
  771. expect(recovered?.ack.subscriptionId).toBe(initial.ack.subscriptionId);
  772. expect(recovered?.reservation?.frame).toMatchObject({
  773. subscriptionId: initial.ack.subscriptionId,
  774. fromSeq: 0,
  775. toSeq: log.events.length,
  776. payload: { kind: "snapshot" },
  777. });
  778. });
  779. it("same-sub aligned resume 仍发送空 recovery logical frame 以收口 flight", () => {
  780. const log = makeLog(1);
  781. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", { now: () => 0 });
  782. for (const event of log.events) publisher.ingest(event);
  783. const initial = publisher.subscribe({ connectionId: "mobile" });
  784. const recovered = publisher.resyncReserved(initial.ack.subscriptionId, {
  785. base: { logEpoch: "epoch-1", seq: log.events.length },
  786. });
  787. expect(recovered?.ack.mode).toBe("resume");
  788. expect(recovered?.reservation?.frame).toMatchObject({
  789. subscriptionId: initial.ack.subscriptionId,
  790. fromSeq: log.events.length,
  791. toSeq: log.events.length,
  792. payload: { kind: "deltas", deltas: [] },
  793. });
  794. });
  795. it("mobile same-sub resync 不作废 desktop sibling reservation", () => {
  796. const log = makeLog(1);
  797. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", { now: () => 0 });
  798. publisher.ingest(log.events[0]!);
  799. const desktop = publisher.subscribe({ connectionId: "desktop", deliveryProfile: "continuous" });
  800. const mobile = publisher.subscribe({ connectionId: "mobile", deliveryProfile: "replayable" });
  801. publisher.ingest(log.events[1]!);
  802. const desktopReservation = publisher.reserveFlush(desktop.ack.subscriptionId);
  803. const mobileReservation = publisher.reserveFlush(mobile.ack.subscriptionId);
  804. const recovered = publisher.resyncReserved(mobile.ack.subscriptionId, {
  805. base: { logEpoch: "epoch-1", seq: 1 },
  806. });
  807. expect(mobileReservation?.commit()).toBe(false);
  808. expect(desktopReservation?.commit()).toBe(true);
  809. expect(recovered?.reservation?.commit()).toBe(true);
  810. });
  811. it("SAT24:desktop continuous 与 mobile replayable 消费同一份完整 subagent 投影", () => {
  812. const log = new EventLog();
  813. log.push(SessionEventType.SessionCreated, {
  814. mode: "default",
  815. contextWindow: 200_000,
  816. });
  817. log.push(
  818. SessionEventType.TurnStarted,
  819. { turnNumber: 1, input: "并行派生" },
  820. { turnId: "turn-1" },
  821. );
  822. for (let index = 1; index <= 7; index += 1) {
  823. log.push(
  824. SessionEventType.SubagentSpawned,
  825. {
  826. agentId: `agent-${index}`,
  827. agentType: "Explore",
  828. childSessionId: `sess-child-${index}`,
  829. description: `child ${index}`,
  830. parentToolCallId: `call-${index}`,
  831. status: "running",
  832. },
  833. { turnId: "turn-1" },
  834. );
  835. }
  836. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  837. now: () => 0,
  838. });
  839. for (const event of log.events) publisher.ingest(event);
  840. const desktop = publisher.subscribe({
  841. connectionId: "desktop",
  842. deliveryProfile: "continuous",
  843. });
  844. const mobile = publisher.subscribe({
  845. connectionId: "mobile",
  846. deliveryProfile: "replayable",
  847. });
  848. for (const subscription of [desktop, mobile]) {
  849. expect(subscription.frame?.payload.kind).toBe("snapshot");
  850. if (subscription.frame?.payload.kind === "snapshot") {
  851. expect(subscription.frame.payload.snapshot.subagents?.running).toHaveLength(7);
  852. }
  853. expect(subscription.reservation?.commit()).toBe(true);
  854. }
  855. const eighth = log.push(
  856. SessionEventType.SubagentSpawned,
  857. {
  858. agentId: "agent-8",
  859. agentType: "Explore",
  860. childSessionId: "sess-child-8",
  861. description: "child 8",
  862. parentToolCallId: "call-8",
  863. status: "running",
  864. },
  865. { turnId: "turn-1" },
  866. );
  867. publisher.ingest(eighth);
  868. for (const subscription of [desktop, mobile]) {
  869. const frame = publisher.reserveFlush(subscription.ack.subscriptionId)?.frame;
  870. expect(frame?.payload.kind).toBe("deltas");
  871. if (frame?.payload.kind === "deltas") {
  872. const patch = frame.payload.deltas.find(
  873. (delta) => delta.op === "state.updated" && delta.patch.subagents,
  874. );
  875. expect(patch).toMatchObject({
  876. op: "state.updated",
  877. patch: { subagents: { endedTotal: 0 } },
  878. });
  879. if (patch?.op === "state.updated") {
  880. expect(patch.patch.subagents?.running).toHaveLength(8);
  881. }
  882. }
  883. }
  884. });
  885. });
  886. describe("subscriber 有界缓冲与自动 resync", () => {
  887. function uniqueDeltas(count: number): ConversationDelta[] {
  888. return Array.from({ length: count }, (_, index) => ({
  889. op: "row.delta" as const,
  890. rowId: index + 1,
  891. path: "text" as const,
  892. append: "x",
  893. }));
  894. }
  895. function singleDeltaPayloadAtBytes(targetBytes: number): ConversationDelta {
  896. const empty: ConversationDelta = {
  897. op: "row.delta",
  898. rowId: 1,
  899. path: "text",
  900. append: "",
  901. };
  902. const overhead = utf8JsonByteLength({
  903. kind: "deltas",
  904. deltas: [empty],
  905. });
  906. expect(overhead).toBeLessThan(targetBytes);
  907. const delta: ConversationDelta = {
  908. ...empty,
  909. append: "x".repeat(targetBytes - overhead),
  910. };
  911. expect(utf8JsonByteLength({ kind: "deltas", deltas: [delta] })).toBe(targetBytes);
  912. return delta;
  913. }
  914. it("coalesce 后 500 ops 可缓冲,501 ops 触发 overflow", () => {
  915. expect(appendConversationSubscriberBuffer([], uniqueDeltas(500))).toMatchObject({
  916. kind: "buffered",
  917. deltas: { length: 500 },
  918. });
  919. expect(appendConversationSubscriberBuffer([], uniqueDeltas(501))).toEqual({ kind: "overflow" });
  920. expect(appendConversationSubscriberBuffer([], uniqueDeltas(501), { maxOps: 501 })).toEqual({
  921. kind: "overflow",
  922. });
  923. expect(() => appendConversationSubscriberBuffer([], uniqueDeltas(1), { maxOps: NaN })).toThrow(
  924. /non-negative finite/u,
  925. );
  926. });
  927. it("encoded logical payload 正好 1MiB 可缓冲,超一字节 overflow", () => {
  928. const max = PROTOCOL_V4_LIMITS.subscriberBufferMaxBytes;
  929. expect(appendConversationSubscriberBuffer([], [singleDeltaPayloadAtBytes(max)])).toMatchObject({
  930. kind: "buffered",
  931. encodedBytes: max,
  932. });
  933. expect(appendConversationSubscriberBuffer([], [singleDeltaPayloadAtBytes(max + 1)])).toEqual({
  934. kind: "overflow",
  935. });
  936. expect(
  937. appendConversationSubscriberBuffer([], [singleDeltaPayloadAtBytes(max + 1)], {
  938. maxBytes: max + 1,
  939. }),
  940. ).toEqual({ kind: "overflow" });
  941. });
  942. /**
  943. * 积压超出尾部窗口:40 个 turn(约 120 行)的 upsert 都在 buffer 里,而 wire snapshot 只带
  944. * 尾部 60 行——buffer 真正大于 snapshot 上界,降级为 snapshot 才有收益(05 §3)。
  945. */
  946. function pushBacklogBeyondTailWindow(log: EventLog, publisher: ConversationTopicPublisher): void {
  947. const firstTurn = log.events.filter(
  948. (event) => event.type === SessionEventType.TurnStarted,
  949. ).length;
  950. for (let index = 1; index <= 40; index += 1) {
  951. const turnNumber = firstTurn + index;
  952. const turnId = `backlog-${turnNumber}`;
  953. publisher.ingest(
  954. log.push(SessionEventType.TurnStarted, { turnNumber, input: `q${turnNumber}` }, { turnId }),
  955. );
  956. publisher.ingest(
  957. log.push(
  958. SessionEventType.ModelStreaming,
  959. { kind: "text_start", delta: "", done: false },
  960. { turnId },
  961. ),
  962. );
  963. publisher.ingest(
  964. log.push(
  965. SessionEventType.ModelStreaming,
  966. { kind: "text_delta", delta: "y".repeat(200), done: false },
  967. { turnId },
  968. ),
  969. );
  970. publisher.ingest(
  971. log.push(
  972. SessionEventType.TurnComplete,
  973. { response: "r", tokenCount: 1, toolCallCount: 0, duration: 1, resultType: "success" },
  974. { turnId },
  975. ),
  976. );
  977. }
  978. }
  979. it("overflow 后首次 flush 自动发最新 snapshot,随后从新水位续流", () => {
  980. const log = new EventLog();
  981. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  982. now: () => 0,
  983. subscriberBufferMaxBytes: 500,
  984. });
  985. publisher.ingest(
  986. log.push(SessionEventType.SessionCreated, {
  987. mode: "default",
  988. contextWindow: 1000,
  989. }),
  990. );
  991. const { ack } = publisher.subscribe({
  992. connectionId: "conn-1",
  993. deliveryProfile: "continuous",
  994. });
  995. publisher.flush(ack.subscriptionId);
  996. pushBacklogBeyondTailWindow(log, publisher);
  997. const started = log.push(
  998. SessionEventType.TurnStarted,
  999. { turnNumber: 99, input: "run" },
  1000. { turnId: "turn-1" },
  1001. );
  1002. publisher.ingest(started);
  1003. publisher.ingest(
  1004. log.push(
  1005. SessionEventType.ModelStreaming,
  1006. { kind: "text_start", delta: "", done: false },
  1007. { turnId: "turn-1" },
  1008. ),
  1009. );
  1010. const afterOverflow = log.push(
  1011. SessionEventType.ModelStreaming,
  1012. { kind: "text_delta", delta: "after-overflow", done: false },
  1013. { turnId: "turn-1" },
  1014. );
  1015. publisher.ingest(afterOverflow);
  1016. const recovery = publisher.flush(ack.subscriptionId);
  1017. expect(recovery?.payload.kind).toBe("snapshot");
  1018. expect(recovery?.toSeq).toBe(afterOverflow.sequenceNumber);
  1019. if (recovery?.payload.kind === "snapshot") {
  1020. const rows = recovery.payload.snapshot.rows.window;
  1021. expect(rows.length).toBe(PROTOCOL_V4_LIMITS.snapshotTailWindowRows);
  1022. expect(rows.at(-1)).toMatchObject({ kind: "assistantText", text: "after-overflow" });
  1023. }
  1024. const tail = log.push(
  1025. SessionEventType.ModelStreaming,
  1026. { kind: "text_delta", delta: "tail", done: false },
  1027. { turnId: "turn-1" },
  1028. );
  1029. publisher.ingest(tail);
  1030. const resumed = publisher.flush(ack.subscriptionId);
  1031. expect(resumed?.payload.kind).toBe("deltas");
  1032. expect(resumed?.fromSeq).toBe(afterOverflow.sequenceNumber);
  1033. expect(resumed?.toSeq).toBe(tail.sequenceNumber);
  1034. });
  1035. it("慢 subscriber overflow 只让自己 snapshot,快 subscriber 保持 delta", () => {
  1036. const log = new EventLog();
  1037. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  1038. now: () => 0,
  1039. subscriberBufferMaxBytes: 500,
  1040. });
  1041. log.push(SessionEventType.SessionCreated, {
  1042. mode: "default",
  1043. contextWindow: 1000,
  1044. });
  1045. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  1046. log.push(
  1047. SessionEventType.ModelStreaming,
  1048. { kind: "text_start", delta: "", done: false },
  1049. { turnId: "turn-1" },
  1050. );
  1051. for (const event of log.events) publisher.ingest(event);
  1052. const fast = publisher.subscribe({
  1053. connectionId: "fast",
  1054. deliveryProfile: "continuous",
  1055. });
  1056. const slow = publisher.subscribe({
  1057. connectionId: "slow",
  1058. deliveryProfile: "continuous",
  1059. });
  1060. publisher.flush(fast.ack.subscriptionId);
  1061. publisher.flush(slow.ack.subscriptionId);
  1062. publisher.ingest(
  1063. log.push(
  1064. SessionEventType.TurnComplete,
  1065. { response: "r", tokenCount: 1, toolCallCount: 0, duration: 1, resultType: "success" },
  1066. { turnId: "turn-1" },
  1067. ),
  1068. );
  1069. const fastKinds: string[] = [];
  1070. const ingest = publisher.ingest.bind(publisher);
  1071. // fast 每条事件都 flush;slow 从不 flush,积压超出尾部窗口。
  1072. publisher.ingest = (event) => {
  1073. ingest(event);
  1074. const frame = publisher.flush(fast.ack.subscriptionId);
  1075. if (frame) fastKinds.push(frame.payload.kind);
  1076. };
  1077. pushBacklogBeyondTailWindow(log, publisher);
  1078. expect(fastKinds.length).toBeGreaterThan(0);
  1079. expect(fastKinds.every((kind) => kind === "deltas")).toBe(true);
  1080. expect(publisher.flush(slow.ack.subscriptionId)?.payload.kind).toBe("snapshot");
  1081. });
  1082. it("字节上限 = min(max(下限, snapshot 上界), 16MiB - 64KiB)", () => {
  1083. const floor = PROTOCOL_V4_LIMITS.subscriberBufferMaxBytes;
  1084. const cap = PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxBytes - PROJECTION_TERMINAL_RESERVE_BYTES;
  1085. expect(conversationSubscriberBufferByteLimit(floor, 0)).toBe(floor);
  1086. expect(conversationSubscriberBufferByteLimit(floor, floor - 1)).toBe(floor);
  1087. expect(conversationSubscriberBufferByteLimit(floor, 3 * floor)).toBe(3 * floor);
  1088. expect(conversationSubscriberBufferByteLimit(floor, cap + 1)).toBe(cap);
  1089. expect(conversationSubscriberBufferByteLimit(500, 2_000)).toBe(2_000);
  1090. const big = singleDeltaPayloadAtBytes(3 * floor);
  1091. expect(appendConversationSubscriberBuffer([], [big])).toEqual({ kind: "overflow" });
  1092. expect(
  1093. appendConversationSubscriberBuffer([], [big], { snapshotBytesUpperBound: 3 * floor }),
  1094. ).toMatchObject({ kind: "buffered", encodedBytes: 3 * floor });
  1095. expect(
  1096. appendConversationSubscriberBuffer([], [big], { snapshotBytesUpperBound: 3 * floor - 1 }),
  1097. ).toEqual({ kind: "overflow" });
  1098. });
  1099. /**
  1100. * 长 session 回归(2026-09-30 实测):3MiB bash 输出这类单条大 delta 超过 1MiB 下限,
  1101. * 旧规则降级为 snapshot → 客户端整份替换丢历史 → turn navigator 每轮全量重新分页。
  1102. * snapshot 只会更大(同一行还在尾部窗口),所以必须继续发 deltas。
  1103. */
  1104. it("单条大 delta 超过 1MiB 但不超过 snapshot 上界:继续发 deltas,终态 ≡ 全量重放", () => {
  1105. const log = makeLog(2);
  1106. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", { now: () => 0 });
  1107. const store = { seq: 0, snapshot: null as ConversationSnapshot | null };
  1108. for (const event of log.events) publisher.ingest(event);
  1109. const { ack, frame } = publisher.subscribe({
  1110. connectionId: "conn-1",
  1111. deliveryProfile: "continuous",
  1112. });
  1113. clientApply(store, frame!);
  1114. const turnId = "turn-big";
  1115. for (const event of [
  1116. log.push(SessionEventType.TurnStarted, { turnNumber: 3, input: "big" }, { turnId }),
  1117. log.push(
  1118. SessionEventType.ModelStreaming,
  1119. { kind: "text_start", delta: "", done: false },
  1120. { turnId },
  1121. ),
  1122. log.push(
  1123. SessionEventType.ModelStreaming,
  1124. {
  1125. kind: "text_delta",
  1126. delta: "x".repeat(PROTOCOL_V4_LIMITS.subscriberBufferMaxBytes + 512 * 1024),
  1127. done: false,
  1128. },
  1129. { turnId },
  1130. ),
  1131. ]) {
  1132. publisher.ingest(event);
  1133. }
  1134. const bigFrame = publisher.flush(ack.subscriptionId)!;
  1135. expect(bigFrame.payload.kind).toBe("deltas");
  1136. expect(utf8JsonByteLength(bigFrame.payload)).toBeGreaterThan(
  1137. PROTOCOL_V4_LIMITS.subscriberBufferMaxBytes,
  1138. );
  1139. clientApply(store, bigFrame);
  1140. const complete = log.push(
  1141. SessionEventType.TurnComplete,
  1142. { response: "r", tokenCount: 1, toolCallCount: 0, duration: 1, resultType: "success" },
  1143. { turnId },
  1144. );
  1145. publisher.ingest(complete);
  1146. const next = publisher.flush(ack.subscriptionId)!;
  1147. expect(next.payload.kind).toBe("deltas");
  1148. clientApply(store, next);
  1149. expect(store.seq).toBe(complete.sequenceNumber);
  1150. expect(store.snapshot).toEqual(authoritativeSnapshot(log.events));
  1151. });
  1152. it("profile filter 在计数前执行,被过滤 delta 不占 op 但 seq 继续推进", () => {
  1153. const log = new EventLog();
  1154. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  1155. now: () => 0,
  1156. subscriberBufferMaxOps: 0,
  1157. });
  1158. log.push(SessionEventType.SessionCreated, {
  1159. mode: "default",
  1160. contextWindow: 1000,
  1161. });
  1162. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "write" }, { turnId: "turn-1" });
  1163. log.push(
  1164. SessionEventType.ModelStreaming,
  1165. {
  1166. kind: "tool_input_start",
  1167. delta: "",
  1168. done: false,
  1169. toolCallId: "tc-1",
  1170. toolName: "Write",
  1171. },
  1172. { turnId: "turn-1" },
  1173. );
  1174. for (const event of log.events) publisher.ingest(event);
  1175. const { ack } = publisher.subscribe({ connectionId: "replayable" });
  1176. const filtered = log.push(
  1177. SessionEventType.ModelStreaming,
  1178. {
  1179. kind: "tool_input_delta",
  1180. delta: '{"file_path":"a.ts"}',
  1181. done: false,
  1182. toolCallId: "tc-1",
  1183. },
  1184. { turnId: "turn-1" },
  1185. );
  1186. publisher.ingest(filtered);
  1187. const frame = publisher.flush(ack.subscriptionId);
  1188. expect(frame?.payload).toEqual({ kind: "deltas", deltas: [] });
  1189. expect(frame?.toSeq).toBe(filtered.sequenceNumber);
  1190. });
  1191. });
  1192. // ── M5④ R-06:snapshot 尾部窗口 + rows/range 游标分页 ──
  1193. // 黄金不变量:截断 snapshot 的 window 前面补齐 rows/range 各页后,与全量重放
  1194. // 的 rows.window 逐字节一致(数据源同一投影,构造保证;此处独立重放交叉验证)。
  1195. describe("rows/range 游标分页(R-06)", () => {
  1196. // 每 turn 3 行(turnHeader+userInput+assistantText);30 turn = 90 行 > 60。
  1197. const TURNS = 30;
  1198. function longPublisher(): {
  1199. publisher: ConversationTopicPublisher;
  1200. log: EventLog;
  1201. } {
  1202. const log = makeLog(TURNS);
  1203. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  1204. now: () => 0,
  1205. });
  1206. for (const event of log.events) publisher.ingest(event);
  1207. return { publisher, log };
  1208. }
  1209. it("超窗会话 snapshot 只带尾部 60 行;totalCount/firstRowId 保留全序口径", () => {
  1210. const { publisher, log } = longPublisher();
  1211. const full = authoritativeSnapshot(log.events);
  1212. expect(full.rows.window.length).toBeGreaterThan(60);
  1213. const { frame } = publisher.subscribe({ connectionId: "conn-1" });
  1214. expect(frame!.payload.kind).toBe("snapshot");
  1215. const wire = frame!.payload.kind === "snapshot" ? frame!.payload.snapshot : null;
  1216. expect(wire!.rows.window.length).toBe(60);
  1217. expect(wire!.rows.totalCount).toBe(full.rows.totalCount);
  1218. expect(wire!.rows.firstRowId).toBe(full.rows.firstRowId);
  1219. // 尾部窗口 = 全量重放的最后 60 行(逐字节一致)。
  1220. expect(wire!.rows.window).toEqual(full.rows.window.slice(-60));
  1221. // A 区不受截断影响。
  1222. expect({ ...wire!, rows: full.rows }).toEqual(full);
  1223. });
  1224. it("loadOlder 黄金路径:rows/range 各页 + 尾部窗口 ≡ 全量重放(逐字节)", () => {
  1225. const { publisher, log } = longPublisher();
  1226. const full = authoritativeSnapshot(log.events);
  1227. const { frame } = publisher.subscribe({ connectionId: "conn-1" });
  1228. const wire = frame!.payload.kind === "snapshot" ? frame!.payload.snapshot : null;
  1229. // 模拟客户端 loadOlder:以窗口首行为游标逐页向上,直到 hasMore=false。
  1230. let window = [...wire!.rows.window];
  1231. let guard = 0;
  1232. for (;;) {
  1233. expect(guard++).toBeLessThan(20);
  1234. const first = window[0]!;
  1235. if (first.rowId === wire!.rows.firstRowId) break;
  1236. const page = publisher.getRowsRange({
  1237. beforeRowId: first.rowId,
  1238. limit: 10,
  1239. });
  1240. expect(page.atLogEpoch).toBe("epoch-1");
  1241. expect(page.atSeq).toBe(full.seq);
  1242. expect(page.atRevision).toBe(full.revision);
  1243. // 页内 rowId 升序且都 < 游标。
  1244. for (let i = 0; i < page.rows.length; i++) {
  1245. expect(page.rows[i]!.rowId).toBeLessThan(first.rowId);
  1246. if (i > 0) {
  1247. expect(page.rows[i]!.rowId).toBeGreaterThan(page.rows[i - 1]!.rowId);
  1248. }
  1249. }
  1250. window = [...page.rows, ...window];
  1251. if (!page.hasMore) {
  1252. expect(window[0]!.rowId).toBe(wire!.rows.firstRowId);
  1253. }
  1254. }
  1255. // 黄金断言:补齐后的 window 与全量重放逐字节一致。
  1256. expect(JSON.stringify(window)).toBe(JSON.stringify(full.rows.window));
  1257. });
  1258. it("beforeRowId 缺省 = 从尾部向前;limit 截到 rowsRangeMaxLimit", () => {
  1259. const { publisher, log } = longPublisher();
  1260. const full = authoritativeSnapshot(log.events);
  1261. const tail = publisher.getRowsRange({ limit: 5 });
  1262. expect(tail.rows).toEqual(full.rows.window.slice(-5));
  1263. expect(tail.hasMore).toBe(true);
  1264. const all = publisher.getRowsRange({ limit: 10_000 });
  1265. expect(all.rows.length).toBeLessThanOrEqual(200);
  1266. expect(all.hasMore).toBe(full.rows.window.length > all.rows.length);
  1267. });
  1268. it("已到顶:beforeRowId = 全序首行 → 空页 hasMore=false", () => {
  1269. const { publisher } = longPublisher();
  1270. const snapshot = publisher.getSnapshot();
  1271. const page = publisher.getRowsRange({
  1272. beforeRowId: snapshot.rows.firstRowId!,
  1273. limit: 10,
  1274. });
  1275. expect(page.rows).toEqual([]);
  1276. expect(page.hasMore).toBe(false);
  1277. });
  1278. it("短会话(≤60 行)snapshot 不截断,行为与既往一致", () => {
  1279. const log = makeLog(2);
  1280. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  1281. now: () => 0,
  1282. });
  1283. for (const event of log.events) publisher.ingest(event);
  1284. const { frame } = publisher.subscribe({ connectionId: "conn-1" });
  1285. const wire = frame!.payload.kind === "snapshot" ? frame!.payload.snapshot : null;
  1286. expect(wire).toEqual(authoritativeSnapshot(log.events));
  1287. });
  1288. });
  1289. describe("HK08 Hook lifecycle product delivery boundary", () => {
  1290. const descriptor = {
  1291. clientVisible: true as const,
  1292. sourceKind: "user" as const,
  1293. sourcePath: "/Users/example/.zcode/cli/config.json",
  1294. executionType: "command" as const,
  1295. executionMode: "foreground" as const,
  1296. commandDisplay: "./hooks/check.sh",
  1297. timeoutMs: 5_000,
  1298. };
  1299. function hookLifecycleLog(): EventLog {
  1300. const log = new EventLog();
  1301. log.push(SessionEventType.SessionCreated, { mode: "default", contextWindow: 1_000 });
  1302. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "run" }, { turnId: "turn-1" });
  1303. log.push(
  1304. SessionEventType.HookRunStarted,
  1305. {
  1306. descriptor,
  1307. hookEventName: "UserPromptSubmit",
  1308. hookIndex: 0,
  1309. hookCount: 1,
  1310. hookInvocationId: "hook-invocation-1",
  1311. hookRunId: "hook-run-1",
  1312. startedAt: 1_700_000_003_000,
  1313. },
  1314. { turnId: "turn-1" },
  1315. );
  1316. log.push(
  1317. SessionEventType.HookRunCompleted,
  1318. {
  1319. descriptor,
  1320. durationMs: 25,
  1321. hookEventName: "UserPromptSubmit",
  1322. hookIndex: 0,
  1323. hookCount: 1,
  1324. hookInvocationId: "hook-invocation-1",
  1325. hookRunId: "hook-run-1",
  1326. outcome: "success",
  1327. startedAt: 1_700_000_003_000,
  1328. },
  1329. { turnId: "turn-1" },
  1330. );
  1331. return log;
  1332. }
  1333. it.each(["continuous", "replayable"] as const)(
  1334. "%s snapshot(W) + resume(W,current] matches the full safe Hook projection",
  1335. (deliveryProfile) => {
  1336. const log = hookLifecycleLog();
  1337. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  1338. now: () => 1_700_000_999_000,
  1339. });
  1340. const store = { seq: 0, snapshot: null as ConversationSnapshot | null };
  1341. for (const event of log.events.slice(0, 3)) publisher.ingest(event);
  1342. const initial = publisher.subscribe({
  1343. connectionId: `${deliveryProfile}-initial`,
  1344. deliveryProfile,
  1345. });
  1346. expect(initial.ack.mode).toBe("snapshot");
  1347. clientApply(store, initial.frame!);
  1348. publisher.unsubscribe(initial.ack.subscriptionId);
  1349. publisher.ingest(log.events[3]!);
  1350. const resumed = publisher.subscribe({
  1351. connectionId: `${deliveryProfile}-resume`,
  1352. deliveryProfile,
  1353. base: { logEpoch: "epoch-1", seq: store.seq },
  1354. });
  1355. expect(resumed.ack.mode).toBe("resume");
  1356. clientApply(store, resumed.frame!);
  1357. const fullFrame = publisher.subscribe({
  1358. connectionId: `${deliveryProfile}-full`,
  1359. deliveryProfile,
  1360. }).frame!;
  1361. expect(fullFrame.payload.kind).toBe("snapshot");
  1362. if (fullFrame.payload.kind !== "snapshot") throw new Error("expected snapshot");
  1363. expect(store.snapshot).toEqual(fullFrame.payload.snapshot);
  1364. expect(store.snapshot?.rows.window.some((row) => row.kind === "hookInvocation")).toBe(true);
  1365. expect(JSON.stringify(store.snapshot)).not.toMatch(/commandDisplay|sourcePath/u);
  1366. },
  1367. );
  1368. it("delivers the same safe summary through live, resume, snapshot, and rows/range", () => {
  1369. const log = hookLifecycleLog();
  1370. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  1371. now: () => 1_700_000_999_000,
  1372. });
  1373. for (const event of log.events.slice(0, 2)) publisher.ingest(event);
  1374. const desktop = publisher.subscribe({
  1375. connectionId: "desktop",
  1376. deliveryProfile: "continuous",
  1377. });
  1378. const replayable = publisher.subscribe({
  1379. connectionId: "web",
  1380. deliveryProfile: "replayable",
  1381. });
  1382. publisher.ingest(log.events[2]!);
  1383. const desktopLive = publisher.flush(desktop.ack.subscriptionId);
  1384. const replayableLive = publisher.flush(replayable.ack.subscriptionId);
  1385. expect(desktopLive?.payload.kind).toBe("deltas");
  1386. expect(
  1387. desktopLive?.payload.kind === "deltas"
  1388. ? desktopLive.payload.deltas.some(
  1389. (delta) => delta.op === "row.appended" && delta.row.kind === "hookInvocation",
  1390. )
  1391. : false,
  1392. ).toBe(true);
  1393. expect(
  1394. replayableLive?.payload.kind === "deltas"
  1395. ? replayableLive.payload.deltas.some(
  1396. (delta) =>
  1397. (delta.op === "row.appended" || delta.op === "row.upserted") &&
  1398. delta.row.kind === "hookInvocation",
  1399. )
  1400. : true,
  1401. ).toBe(true);
  1402. expect(replayableLive?.toSeq).toBe(log.events[2]!.sequenceNumber);
  1403. publisher.ingest(log.events[3]!);
  1404. publisher.unsubscribe(desktop.ack.subscriptionId);
  1405. publisher.unsubscribe(replayable.ack.subscriptionId);
  1406. const desktopResume = publisher.subscribe({
  1407. connectionId: "desktop-resume",
  1408. deliveryProfile: "continuous",
  1409. base: { logEpoch: "epoch-1", seq: 2 },
  1410. });
  1411. const replayableResume = publisher.subscribe({
  1412. connectionId: "web-resume",
  1413. deliveryProfile: "replayable",
  1414. base: { logEpoch: "epoch-1", seq: 2 },
  1415. });
  1416. expect(desktopResume.frame?.payload.kind).toBe("deltas");
  1417. expect(
  1418. desktopResume.frame?.payload.kind === "deltas"
  1419. ? desktopResume.frame.payload.deltas.some(
  1420. (delta) =>
  1421. (delta.op === "row.appended" || delta.op === "row.upserted") &&
  1422. delta.row.kind === "hookInvocation",
  1423. )
  1424. : false,
  1425. ).toBe(true);
  1426. expect(
  1427. replayableResume.frame?.payload.kind === "deltas"
  1428. ? replayableResume.frame.payload.deltas.some(
  1429. (delta) =>
  1430. (delta.op === "row.appended" || delta.op === "row.upserted") &&
  1431. delta.row.kind === "hookInvocation",
  1432. )
  1433. : true,
  1434. ).toBe(true);
  1435. expect(replayableResume.frame?.toSeq).toBe(log.events[3]!.sequenceNumber);
  1436. const desktopSnapshot = publisher.subscribe({
  1437. connectionId: "desktop-snapshot",
  1438. deliveryProfile: "continuous",
  1439. }).frame;
  1440. const webSnapshot = publisher.subscribe({
  1441. connectionId: "web-snapshot",
  1442. deliveryProfile: "replayable",
  1443. }).frame;
  1444. expect(
  1445. desktopSnapshot?.payload.kind === "snapshot"
  1446. ? desktopSnapshot.payload.snapshot.rows.window.some((row) => row.kind === "hookInvocation")
  1447. : false,
  1448. ).toBe(true);
  1449. expect(
  1450. webSnapshot?.payload.kind === "snapshot"
  1451. ? webSnapshot.payload.snapshot.rows.window.some((row) => row.kind === "hookInvocation")
  1452. : true,
  1453. ).toBe(true);
  1454. if (desktopSnapshot?.payload.kind === "snapshot" && webSnapshot?.payload.kind === "snapshot") {
  1455. expect(desktopSnapshot.payload.snapshot.rows.totalCount).toBe(
  1456. webSnapshot.payload.snapshot.rows.totalCount,
  1457. );
  1458. }
  1459. expect(
  1460. publisher
  1461. .getRowsRange({ limit: 100 }, "continuous")
  1462. .rows.some((row) => row.kind === "hookInvocation"),
  1463. ).toBe(true);
  1464. expect(
  1465. publisher
  1466. .getRowsRange({ limit: 100 }, "replayable")
  1467. .rows.some((row) => row.kind === "hookInvocation"),
  1468. ).toBe(true);
  1469. expect(
  1470. publisher.getRowsRange({ limit: 100 }).rows.some((row) => row.kind === "hookInvocation"),
  1471. ).toBe(true);
  1472. });
  1473. });
  1474. describe("会话计划目录(S13-S15)", () => {
  1475. it("只返回当前分支已结束且包含正文的 ExitPlanMode,最新优先", () => {
  1476. const log = new EventLog();
  1477. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  1478. now: () => 0,
  1479. });
  1480. const turnId = "turn-plan-directory";
  1481. const ingest = (event: SessionEvent) => publisher.ingest(event);
  1482. ingest(log.push(SessionEventType.SessionCreated, { mode: "default" }));
  1483. ingest(log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "写计划" }, { turnId }));
  1484. const schedulePlan = (toolCallId: string, plan: string) => {
  1485. ingest(
  1486. log.push(
  1487. SessionEventType.ModelStreaming,
  1488. {
  1489. kind: "tool_input_start",
  1490. delta: "",
  1491. done: false,
  1492. toolCallId,
  1493. toolName: "ExitPlanMode",
  1494. },
  1495. { turnId },
  1496. ),
  1497. );
  1498. ingest(
  1499. log.push(
  1500. SessionEventType.ToolCallScheduled,
  1501. {
  1502. toolCallId,
  1503. toolName: "ExitPlanMode",
  1504. input: { plan },
  1505. schedule: { parallelGroups: [[toolCallId]], executionOrder: [toolCallId] },
  1506. },
  1507. { turnId },
  1508. ),
  1509. );
  1510. };
  1511. schedulePlan("plan-success", "# 成功计划");
  1512. ingest(
  1513. log.push(
  1514. SessionEventType.ToolCallResult,
  1515. {
  1516. toolCallId: "plan-success",
  1517. result: { success: true, content: "done" },
  1518. duration: 10,
  1519. },
  1520. { turnId },
  1521. ),
  1522. );
  1523. schedulePlan("plan-error", "# 失败计划");
  1524. ingest(
  1525. log.push(
  1526. SessionEventType.ToolCallError,
  1527. {
  1528. toolCallId: "plan-error",
  1529. error: { type: "fault.test", message: "failed" },
  1530. },
  1531. { turnId },
  1532. ),
  1533. );
  1534. schedulePlan("plan-cancelled", "# 取消计划");
  1535. expect(publisher.getPlans().plans.map((row) => row.toolCallId)).toEqual([
  1536. "plan-error",
  1537. "plan-success",
  1538. ]);
  1539. ingest(
  1540. log.push(
  1541. SessionEventType.TurnComplete,
  1542. {
  1543. response: "",
  1544. tokenCount: 0,
  1545. toolCallCount: 3,
  1546. duration: 20,
  1547. resultType: "cancelled",
  1548. },
  1549. { turnId },
  1550. ),
  1551. );
  1552. const result = publisher.getPlans();
  1553. expect(result.plans.map((row) => [row.toolCallId, row.status])).toEqual([
  1554. ["plan-cancelled", "cancelled"],
  1555. ["plan-error", "error"],
  1556. ["plan-success", "success"],
  1557. ]);
  1558. expect(result.atSeq).toBe(log.events.at(-1)?.sequenceNumber);
  1559. expect(result.atLogEpoch).toBe("epoch-1");
  1560. });
  1561. it("计划早于 wire snapshot tail 时仍从完整 projection 返回", () => {
  1562. const log = new EventLog();
  1563. const turnId = "turn-early-plan";
  1564. log.push(SessionEventType.SessionCreated, { mode: "default" });
  1565. log.push(SessionEventType.TurnStarted, { turnNumber: 1, input: "早期计划" }, { turnId });
  1566. log.push(
  1567. SessionEventType.ModelStreaming,
  1568. {
  1569. kind: "tool_input_start",
  1570. delta: "",
  1571. done: false,
  1572. toolCallId: "early-plan",
  1573. toolName: "ExitPlanMode",
  1574. },
  1575. { turnId },
  1576. );
  1577. log.push(
  1578. SessionEventType.ToolCallScheduled,
  1579. {
  1580. toolCallId: "early-plan",
  1581. toolName: "ExitPlanMode",
  1582. input: { plan: "# 早于尾窗的计划" },
  1583. schedule: { parallelGroups: [["early-plan"]], executionOrder: ["early-plan"] },
  1584. },
  1585. { turnId },
  1586. );
  1587. log.push(
  1588. SessionEventType.ToolCallResult,
  1589. {
  1590. toolCallId: "early-plan",
  1591. result: { success: true, content: "done" },
  1592. duration: 10,
  1593. },
  1594. { turnId },
  1595. );
  1596. log.push(
  1597. SessionEventType.TurnComplete,
  1598. {
  1599. response: "",
  1600. tokenCount: 0,
  1601. toolCallCount: 1,
  1602. duration: 20,
  1603. resultType: "success",
  1604. },
  1605. { turnId },
  1606. );
  1607. for (let turn = 2; turn <= 32; turn += 1) turnEvents(log, turn);
  1608. const publisher = new ConversationTopicPublisher("session-1", "epoch-1", {
  1609. now: () => 0,
  1610. });
  1611. for (const event of log.events) publisher.ingest(event);
  1612. const initial = publisher.subscribe({ connectionId: "wire-tail" }).frame;
  1613. const wireRows =
  1614. initial?.payload.kind === "snapshot" ? initial.payload.snapshot.rows.window : [];
  1615. expect(wireRows).toHaveLength(PROTOCOL_V4_LIMITS.snapshotTailWindowRows);
  1616. expect(wireRows.some((row) => row.kind === "toolCall" && row.toolCallId === "early-plan")).toBe(
  1617. false,
  1618. );
  1619. expect(publisher.getPlans().plans.map((row) => row.toolCallId)).toEqual(["early-plan"]);
  1620. });
  1621. });