conversation-topic-publisher.test.ts 64 KB

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