zcodeProtocolV4Coalesce.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. applyConversationDeltas,
  4. applyConversationDeltasMutable,
  5. assistantTextRowSchema,
  6. coalesceConversationDeltas,
  7. conflateByKey,
  8. conversationSnapshotSchema,
  9. createMutableConversationSnapshotAccumulator,
  10. type AssistantTextRow,
  11. type ConversationDelta,
  12. type ConversationSnapshot,
  13. type ToolCallRow,
  14. type TurnHeaderRow,
  15. reasoningRowSchema,
  16. toolCallRowSchema,
  17. } from "../src/zcode-protocol-v4/index.js";
  18. describe("assistant response correlation", () => {
  19. it("accepts the same optional assistantResponseId on reasoning, text and tool rows", () => {
  20. expect(
  21. reasoningRowSchema.parse({
  22. ...makeAssistantRow(0, "先检查权限"),
  23. kind: "reasoning",
  24. assistantResponseId: "assistant-response-1",
  25. }).assistantResponseId,
  26. ).toBe("assistant-response-1");
  27. expect(
  28. assistantTextRowSchema.parse({
  29. ...makeAssistantRow(1, "正在检查权限"),
  30. assistantResponseId: "assistant-response-1",
  31. }).assistantResponseId,
  32. ).toBe("assistant-response-1");
  33. expect(
  34. toolCallRowSchema.parse({
  35. ...makeToolRow(2),
  36. assistantResponseId: "assistant-response-1",
  37. }).assistantResponseId,
  38. ).toBe("assistant-response-1");
  39. });
  40. it("keeps legacy rows without assistantResponseId valid", () => {
  41. expect(
  42. reasoningRowSchema.parse({ ...makeAssistantRow(0), kind: "reasoning" }).assistantResponseId,
  43. ).toBeUndefined();
  44. expect(assistantTextRowSchema.parse(makeAssistantRow(1)).assistantResponseId).toBeUndefined();
  45. expect(toolCallRowSchema.parse(makeToolRow(2)).assistantResponseId).toBeUndefined();
  46. });
  47. });
  48. function makeAssistantRow(rowId: number, text = ""): AssistantTextRow {
  49. return {
  50. rowId,
  51. turnId: "turn-1",
  52. createdAt: 1000,
  53. createdAtSeq: rowId,
  54. kind: "assistantText",
  55. text,
  56. state: "streaming",
  57. };
  58. }
  59. function makeToolRow(rowId: number): ToolCallRow {
  60. return {
  61. rowId,
  62. turnId: "turn-1",
  63. createdAt: 1000,
  64. createdAtSeq: rowId,
  65. kind: "toolCall",
  66. toolCallId: `tc-${rowId}`,
  67. toolName: "Read",
  68. status: "inputStreaming",
  69. inputText: "",
  70. };
  71. }
  72. function makeSnapshot(): ConversationSnapshot {
  73. return {
  74. protocolVersion: 1,
  75. sessionId: "s-1",
  76. logEpoch: "epoch-1",
  77. seq: 0,
  78. revision: 0,
  79. control: {
  80. phase: "running",
  81. sessionEnded: false,
  82. canStop: true,
  83. stopState: "stoppable",
  84. stopTargetKind: "assistant",
  85. activeWorks: [{ kind: "primaryTurn", startedAt: 1000 }],
  86. lastError: null,
  87. apiRetry: null,
  88. },
  89. availability: {
  90. fork: { allowed: true },
  91. compact: { allowed: false, reasonCode: "guard.manualCompact" },
  92. switchModelConfig: { allowed: true },
  93. setFollowupMode: { allowed: true },
  94. queueEdit: { allowed: true },
  95. sendQueuedNow: { allowed: false, reasonCode: "guard.sendQueuedNowStopsBeforeDrain" },
  96. pauseGoal: { allowed: false, reasonCode: "guard.noGoal" },
  97. resumeGoal: { allowed: false, reasonCode: "guard.stopPausesActiveGoalTarget" },
  98. },
  99. inputRouting: { mode: "enqueue" },
  100. // meta 是 freeze-m2 后 additive 新增(带 schema default);夹具写归一化形态,
  101. // round-trip 断言 parse 前后 deep-equal 才成立。
  102. meta: { title: "", titleSource: "default" },
  103. config: {
  104. provider: "glm",
  105. model: "glm-5",
  106. thought: "medium",
  107. thoughtLevels: ["medium", "high", "max"],
  108. followupMode: "queue",
  109. mode: "build",
  110. },
  111. modelTransition: null,
  112. usage: {
  113. contextWindow: { usedTokens: 100, maxTokens: 200000, autoCompactThresholdTokens: null },
  114. cumulative: { inputTokens: 1, outputTokens: 2, cacheReadTokens: 0, cacheWriteTokens: 0 },
  115. },
  116. queue: { items: [], autoDrain: true },
  117. pendingInteractions: [],
  118. pendingCommands: [],
  119. backgroundWorks: [],
  120. // 软门禁 additive 字段:带 default(null),round-trip 归一化形态
  121. workspaceHookAdmission: null,
  122. goal: null,
  123. plan: null,
  124. rows: { window: [], totalCount: 0, firstRowId: null },
  125. };
  126. }
  127. /** 语义保持裁判:coalesce 后 apply 的终态必须与逐条 apply 逐字节一致。 */
  128. function expectSemanticsPreserved(deltas: ConversationDelta[]) {
  129. const base = makeSnapshot();
  130. const direct = applyConversationDeltas(base, deltas);
  131. const coalesced = applyConversationDeltas(base, coalesceConversationDeltas(deltas));
  132. expect(coalesced).toEqual(direct);
  133. // 规则 6 允许把靠后的 op 合并到靠前的位置上,键序因此不再是"两条路径天然相同"——
  134. // 这条定律要的是**逐字节**一致,而不只是深相等。
  135. expect(JSON.stringify(coalesced.workflowRuns)).toBe(JSON.stringify(direct.workflowRuns));
  136. }
  137. /** run 出生增量:一条完整 header,客户端据它才建得起表。 */
  138. function makeRunBirth(runId: string, revision: number): ConversationDelta {
  139. return {
  140. op: "workflowRun.updated",
  141. runId,
  142. revision,
  143. run: {
  144. runId,
  145. status: "running",
  146. usage: { spentTokens: 0, nodesUsed: 0 },
  147. lastEventSequence: 0,
  148. },
  149. };
  150. }
  151. /** 一条节点相位推进的增量(引擎事件在线上的常态形状)。 */
  152. function makeNodePhase(
  153. runId: string,
  154. revision: number,
  155. ordinal: number,
  156. phase: "queued" | "dispatched" | "executing" | "settled",
  157. ): ConversationDelta {
  158. return {
  159. op: "workflowRun.updated",
  160. runId,
  161. revision,
  162. run: { lastEventSequence: revision },
  163. nodes: [{ siteId: "ask#1", ordinal, phase }],
  164. };
  165. }
  166. describe("zcode-protocol-v4 coalesce", () => {
  167. it("旧 snapshot 缺少 thoughtLevels 时按空能力集合兼容解析", () => {
  168. const legacySnapshot = structuredClone(makeSnapshot()) as unknown as {
  169. config: Record<string, unknown>;
  170. };
  171. delete legacySnapshot.config.thoughtLevels;
  172. expect(conversationSnapshotSchema.parse(legacySnapshot).config.thoughtLevels).toEqual([]);
  173. });
  174. it("accepts context window cache and breakdown metadata in snapshots", () => {
  175. const snapshot: ConversationSnapshot = {
  176. ...makeSnapshot(),
  177. usage: {
  178. contextWindow: {
  179. usedTokens: 120,
  180. maxTokens: 200000,
  181. autoCompactThresholdTokens: null,
  182. cache: {
  183. inputTokens: 100,
  184. cacheReadTokens: 80,
  185. cacheWriteTokens: 10,
  186. latestHitRate: 0.8,
  187. hitRate: 0.8,
  188. hitRateRequestCount: 1,
  189. totalInputTokens: 100,
  190. totalCacheReadTokens: 80,
  191. totalCacheWriteTokens: 10,
  192. },
  193. breakdown: [
  194. { source: "messages", chars: 900 },
  195. { source: "system_tool_schemas", chars: 100 },
  196. ],
  197. },
  198. cumulative: {
  199. inputTokens: 100,
  200. outputTokens: 20,
  201. cacheReadTokens: 80,
  202. cacheWriteTokens: 10,
  203. },
  204. },
  205. };
  206. const contextWindow = conversationSnapshotSchema.parse(snapshot).usage.contextWindow;
  207. expect(contextWindow?.cache).toMatchObject({ hitRate: 0.8 });
  208. expect(contextWindow?.breakdown).toEqual([
  209. { source: "messages", chars: 900 },
  210. { source: "system_tool_schemas", chars: 100 },
  211. ]);
  212. });
  213. it("merges adjacent row.delta with same (rowId, path)", () => {
  214. const deltas: ConversationDelta[] = [
  215. { op: "row.appended", row: makeAssistantRow(1) },
  216. { op: "row.delta", rowId: 1, path: "text", append: "你好" },
  217. { op: "row.delta", rowId: 1, path: "text", append: ",世界" },
  218. { op: "row.delta", rowId: 1, path: "text", append: "!" },
  219. ];
  220. const result = coalesceConversationDeltas(deltas);
  221. expect(result).toHaveLength(2);
  222. expect(result[1]).toEqual({
  223. op: "row.delta",
  224. rowId: 1,
  225. path: "text",
  226. append: "你好,世界!",
  227. });
  228. expectSemanticsPreserved(deltas);
  229. });
  230. it("does not merge row.delta across different rows or paths", () => {
  231. const deltas: ConversationDelta[] = [
  232. { op: "row.appended", row: makeAssistantRow(1) },
  233. { op: "row.appended", row: makeToolRow(2) },
  234. { op: "row.delta", rowId: 1, path: "text", append: "a" },
  235. { op: "row.delta", rowId: 2, path: "inputText", append: "{" },
  236. { op: "row.delta", rowId: 1, path: "text", append: "b" },
  237. ];
  238. const result = coalesceConversationDeltas(deltas);
  239. // 不相邻不合并(保序优先于压缩率)
  240. expect(result.filter((d) => d.op === "row.delta")).toHaveLength(3);
  241. expectSemanticsPreserved(deltas);
  242. });
  243. it("shallow-merges adjacent state.updated patches (later key wins)", () => {
  244. const deltas: ConversationDelta[] = [
  245. {
  246. op: "state.updated",
  247. patch: { revision: 1, inputRouting: { mode: "enqueue" } },
  248. },
  249. {
  250. op: "state.updated",
  251. patch: { revision: 2, queue: { items: [], autoDrain: false } },
  252. },
  253. ];
  254. const result = coalesceConversationDeltas(deltas);
  255. expect(result).toHaveLength(1);
  256. expect(result[0]).toEqual({
  257. op: "state.updated",
  258. patch: {
  259. revision: 2,
  260. inputRouting: { mode: "enqueue" },
  261. queue: { items: [], autoDrain: false },
  262. },
  263. });
  264. expectSemanticsPreserved(deltas);
  265. });
  266. it("row.upserted swallows preceding row.delta of the same row", () => {
  267. const finalRow: AssistantTextRow = {
  268. ...makeAssistantRow(1, "完整文本"),
  269. state: "complete",
  270. };
  271. const deltas: ConversationDelta[] = [
  272. { op: "row.appended", row: makeAssistantRow(1) },
  273. { op: "row.delta", rowId: 1, path: "text", append: "完整" },
  274. { op: "row.delta", rowId: 1, path: "text", append: "文本" },
  275. { op: "row.upserted", row: finalRow },
  276. ];
  277. const result = coalesceConversationDeltas(deltas);
  278. expect(result).toEqual([
  279. { op: "row.appended", row: makeAssistantRow(1) },
  280. { op: "row.upserted", row: finalRow },
  281. ]);
  282. expectSemanticsPreserved(deltas);
  283. });
  284. it("row.upserted does not swallow deltas beyond the row's own appended (previous generation)", () => {
  285. // row 1 流了一段 → row 1 被整行替换 → 又流一段 → 再替换:
  286. // 第二次 upserted 只能吞第二段 delta,不能越过第一次 upserted。
  287. const gen1: AssistantTextRow = { ...makeAssistantRow(1, "第一代"), state: "streaming" };
  288. const gen2: AssistantTextRow = { ...makeAssistantRow(1, "第二代"), state: "complete" };
  289. const deltas: ConversationDelta[] = [
  290. { op: "row.appended", row: makeAssistantRow(1) },
  291. { op: "row.delta", rowId: 1, path: "text", append: "x" },
  292. { op: "row.upserted", row: gen1 },
  293. { op: "row.delta", rowId: 1, path: "text", append: "y" },
  294. { op: "row.upserted", row: gen2 },
  295. ];
  296. expectSemanticsPreserved(deltas);
  297. });
  298. it("row.removed is a barrier: no rule crosses it", () => {
  299. const deltas: ConversationDelta[] = [
  300. { op: "row.appended", row: makeAssistantRow(1) },
  301. { op: "row.delta", rowId: 1, path: "text", append: "旧" },
  302. { op: "row.removed", fromRowId: 1 },
  303. { op: "row.appended", row: makeAssistantRow(2) },
  304. { op: "row.delta", rowId: 2, path: "text", append: "新" },
  305. { op: "row.upserted", row: { ...makeAssistantRow(2, "新"), state: "complete" } },
  306. ];
  307. const result = coalesceConversationDeltas(deltas);
  308. // 屏障保留;屏障前的 delta 不被屏障后的 upserted 吞掉
  309. expect(result.some((d) => d.op === "row.removed")).toBe(true);
  310. expect(result.findIndex((d) => d.op === "row.delta" && d.rowId === 1)).toBeGreaterThanOrEqual(
  311. 0,
  312. );
  313. expectSemanticsPreserved(deltas);
  314. });
  315. it("keeps only the last of adjacent row.upserted for the same row", () => {
  316. const a: AssistantTextRow = { ...makeAssistantRow(1, "a"), state: "streaming" };
  317. const b: AssistantTextRow = { ...makeAssistantRow(1, "ab"), state: "complete" };
  318. const deltas: ConversationDelta[] = [
  319. { op: "row.appended", row: makeAssistantRow(1) },
  320. { op: "row.upserted", row: a },
  321. { op: "row.upserted", row: b },
  322. ];
  323. const result = coalesceConversationDeltas(deltas);
  324. expect(result).toEqual([
  325. { op: "row.appended", row: makeAssistantRow(1) },
  326. { op: "row.upserted", row: b },
  327. ]);
  328. expectSemanticsPreserved(deltas);
  329. });
  330. // ── 规则 6:workflowRun.updated 向窗口内最早的同 runId 增量合并 ──────────────
  331. // 宽 fan-out 的 run 每条引擎事件产一条增量,窗口里它们被别的 run 与行操作隔开;只合并相邻的
  332. // 等于一条都合不掉,而 500 条/订阅者的帧界正是被这些增量顶满的。
  333. it("规则 6:同 runId 的增量合并到最早那条,op 数从 N 塌成 1", () => {
  334. const deltas: ConversationDelta[] = [
  335. makeRunBirth("dwfrun-1", 1),
  336. ...Array.from({ length: 30 }, (_, index) =>
  337. makeNodePhase("dwfrun-1", index + 2, 1, index % 2 === 0 ? "executing" : "queued"),
  338. ),
  339. ];
  340. const result = coalesceConversationDeltas(deltas);
  341. expect(result).toHaveLength(1);
  342. expect(result[0]).toMatchObject({ op: "workflowRun.updated", revision: 31 });
  343. expectSemanticsPreserved(deltas);
  344. });
  345. it("规则 6:两条 run 的增量与行操作、无关 state.updated 交错也能各自塌缩", () => {
  346. const deltas: ConversationDelta[] = [
  347. makeRunBirth("dwfrun-1", 1),
  348. { op: "row.appended", row: makeAssistantRow(1) },
  349. makeRunBirth("dwfrun-2", 2),
  350. makeNodePhase("dwfrun-1", 3, 1, "queued"),
  351. { op: "row.delta", rowId: 1, path: "text", append: "分析中" },
  352. makeNodePhase("dwfrun-2", 4, 1, "queued"),
  353. { op: "state.updated", patch: { revision: 7 } },
  354. makeNodePhase("dwfrun-1", 5, 2, "queued"),
  355. makeNodePhase("dwfrun-2", 6, 1, "dispatched"),
  356. makeNodePhase("dwfrun-1", 7, 1, "dispatched"),
  357. ];
  358. const result = coalesceConversationDeltas(deltas);
  359. const perRun = result.filter((delta) => delta.op === "workflowRun.updated");
  360. expect(perRun).toHaveLength(2);
  361. // 出生序保住了:合并落在**最早**那条上,所以 runs[] 的顺序与逐条投递一致。
  362. expect(perRun.map((delta) => (delta.op === "workflowRun.updated" ? delta.runId : ""))).toEqual([
  363. "dwfrun-1",
  364. "dwfrun-2",
  365. ]);
  366. expectSemanticsPreserved(deltas);
  367. });
  368. it("规则 6:header 键与 cleared 互为反面,后者一律对消前者", () => {
  369. const deltas: ConversationDelta[] = [
  370. makeRunBirth("dwfrun-1", 1),
  371. {
  372. op: "workflowRun.updated",
  373. runId: "dwfrun-1",
  374. revision: 2,
  375. run: { pendingQuestions: [{ qid: "q-1", question: "门坏了吗?" }], resultPreview: "草稿" },
  376. },
  377. // 后一条把 pendingQuestions 清成缺席、又给 resultPreview 一个新值。
  378. {
  379. op: "workflowRun.updated",
  380. runId: "dwfrun-1",
  381. revision: 3,
  382. run: { resultPreview: "定稿" },
  383. cleared: ["pendingQuestions"],
  384. },
  385. ];
  386. const result = coalesceConversationDeltas(deltas);
  387. expect(result).toHaveLength(1);
  388. const merged = result[0]!;
  389. if (merged.op !== "workflowRun.updated") throw new Error("应合并成一条 workflowRun.updated");
  390. expect(merged.run).not.toHaveProperty("pendingQuestions");
  391. expect(merged.run?.resultPreview).toBe("定稿");
  392. expect(merged.cleared).toEqual(["pendingQuestions"]);
  393. expectSemanticsPreserved(deltas);
  394. // 反向:先清后设,键回到 run 里、不再留在 cleared。
  395. const reversed: ConversationDelta[] = [
  396. makeRunBirth("dwfrun-1", 1),
  397. { op: "workflowRun.updated", runId: "dwfrun-1", revision: 2, cleared: ["pendingQuestions"] },
  398. {
  399. op: "workflowRun.updated",
  400. runId: "dwfrun-1",
  401. revision: 3,
  402. run: { pendingQuestions: [{ qid: "q-2", question: "换一版?" }] },
  403. },
  404. ];
  405. const mergedReversed = coalesceConversationDeltas(reversed)[0]!;
  406. if (mergedReversed.op !== "workflowRun.updated") throw new Error("应合并成一条增量");
  407. expect(mergedReversed.cleared).toBeUndefined();
  408. expect(mergedReversed.run?.pendingQuestions).toHaveLength(1);
  409. expectSemanticsPreserved(reversed);
  410. });
  411. it("规则 6 的屏障:整键重发的 state.updated 不可跨越", () => {
  412. const deltas: ConversationDelta[] = [
  413. makeRunBirth("dwfrun-1", 1),
  414. makeNodePhase("dwfrun-1", 2, 1, "queued"),
  415. // 整键重发(diff 的退路):它之后的增量作用在一张全新的表上。
  416. {
  417. op: "state.updated",
  418. patch: {
  419. workflowRuns: {
  420. revision: 3,
  421. runs: [
  422. {
  423. runId: "dwfrun-1",
  424. status: "running",
  425. usage: { spentTokens: 0, nodesUsed: 0 },
  426. actors: [],
  427. nodes: [],
  428. lastEventSequence: 3,
  429. },
  430. ],
  431. },
  432. },
  433. },
  434. makeNodePhase("dwfrun-1", 4, 9, "queued"),
  435. makeNodePhase("dwfrun-1", 5, 9, "dispatched"),
  436. ];
  437. const result = coalesceConversationDeltas(deltas);
  438. // 屏障两侧各自塌缩成一条,屏障本身留在中间。
  439. expect(result.map((delta) => delta.op)).toEqual([
  440. "workflowRun.updated",
  441. "state.updated",
  442. "workflowRun.updated",
  443. ]);
  444. expectSemanticsPreserved(deltas);
  445. });
  446. it("规则 6 的屏障:workflowRun.removed 吞掉同 run 此前的增量(出生+淘汰=没见过)", () => {
  447. const deltas: ConversationDelta[] = [
  448. makeRunBirth("dwfrun-1", 1),
  449. makeRunBirth("dwfrun-2", 2),
  450. makeNodePhase("dwfrun-1", 3, 1, "queued"),
  451. makeNodePhase("dwfrun-2", 4, 1, "queued"),
  452. { op: "workflowRun.removed", runId: "dwfrun-1", revision: 5 },
  453. makeNodePhase("dwfrun-2", 6, 1, "dispatched"),
  454. ];
  455. const result = coalesceConversationDeltas(deltas);
  456. expect(result.map((delta) => delta.op)).toEqual(["workflowRun.updated", "workflowRun.removed"]);
  457. expect(result[0]).toMatchObject({ runId: "dwfrun-2", revision: 6 });
  458. expectSemanticsPreserved(deltas);
  459. // 淘汰后这条 run 又回来(迟到事件):新增量不被吞、也不与屏障前的合并。
  460. const revived: ConversationDelta[] = [...deltas, makeRunBirth("dwfrun-1", 7)];
  461. expect(coalesceConversationDeltas(revived).map((delta) => delta.op)).toEqual([
  462. "workflowRun.updated",
  463. "workflowRun.removed",
  464. "workflowRun.updated",
  465. ]);
  466. expectSemanticsPreserved(revived);
  467. });
  468. it("规则 6:合并后的 op 坐在靠前的位置,容器 revision 仍收在最高水位", () => {
  469. const deltas: ConversationDelta[] = [
  470. makeRunBirth("dwfrun-1", 1),
  471. makeRunBirth("dwfrun-2", 2),
  472. // 最后一条属于 dwfrun-1,合并后会被搬到第一条的位置上——靠 apply 的 max 收口。
  473. makeNodePhase("dwfrun-1", 9, 1, "settled"),
  474. ];
  475. const coalesced = applyConversationDeltas(makeSnapshot(), coalesceConversationDeltas(deltas));
  476. expect(coalesced.workflowRuns?.revision).toBe(9);
  477. expectSemanticsPreserved(deltas);
  478. });
  479. it("preserves semantics on a mixed long sequence", () => {
  480. const deltas: ConversationDelta[] = [
  481. { op: "row.appended", row: makeAssistantRow(1) },
  482. { op: "row.delta", rowId: 1, path: "text", append: "分析中" },
  483. { op: "state.updated", patch: { revision: 1 } },
  484. { op: "row.appended", row: makeToolRow(2) },
  485. { op: "row.delta", rowId: 2, path: "inputText", append: '{"path":' },
  486. { op: "row.delta", rowId: 2, path: "inputText", append: '"a.ts"}' },
  487. {
  488. op: "row.upserted",
  489. row: {
  490. ...makeToolRow(2),
  491. status: "success",
  492. inputText: '{"path":"a.ts"}',
  493. output: { text: "ok" },
  494. },
  495. },
  496. { op: "state.updated", patch: { revision: 2 } },
  497. { op: "row.delta", rowId: 1, path: "text", append: "……完成" },
  498. { op: "row.upserted", row: { ...makeAssistantRow(1, "分析中……完成"), state: "complete" } },
  499. { op: "state.updated", patch: { revision: 3 } },
  500. ];
  501. expectSemanticsPreserved(deltas);
  502. });
  503. });
  504. describe("zcode-protocol-v4 apply", () => {
  505. it("隔离态 mutable accumulator 与规范不可变 apply 五种操作逐字节等价", () => {
  506. const base = makeSnapshot();
  507. const deltas: ConversationDelta[] = [
  508. { op: "row.appended", row: makeAssistantRow(1, "a") },
  509. { op: "row.appended", row: makeToolRow(2) },
  510. { op: "row.delta", rowId: 1, path: "text", append: "bc" },
  511. { op: "row.delta", rowId: 2, path: "inputText", append: '{"path":"a.ts"}' },
  512. {
  513. op: "row.upserted",
  514. row: { ...makeToolRow(2), status: "success", inputText: "done" },
  515. },
  516. { op: "state.updated", patch: { revision: 3, inputRouting: { mode: "startNow" } } },
  517. { op: "row.removed", fromRowId: 2 },
  518. { op: "row.appended", row: makeAssistantRow(5, "rerun") },
  519. // 缺失 row 与不适用 path 都必须保持 no-op。
  520. { op: "row.upserted", row: makeAssistantRow(99, "ghost") },
  521. { op: "row.delta", rowId: 5, path: "inputText", append: "ghost" },
  522. ];
  523. const expected = applyConversationDeltas(base, deltas);
  524. const accumulator = createMutableConversationSnapshotAccumulator(base);
  525. applyConversationDeltasMutable(accumulator, deltas);
  526. expect(accumulator.snapshot).toEqual(expected);
  527. expect([...accumulator.rowIndexById]).toEqual([
  528. [1, 0],
  529. [5, 1],
  530. ]);
  531. expect(base.rows.window).toEqual([]);
  532. });
  533. it("row.removed truncates from fromRowId and row.upserted on missing row is a no-op", () => {
  534. const base = makeSnapshot();
  535. const afterAppend = applyConversationDeltas(base, [
  536. { op: "row.appended", row: makeAssistantRow(1, "a") },
  537. { op: "row.appended", row: makeAssistantRow(2, "b") },
  538. { op: "row.appended", row: makeAssistantRow(3, "c") },
  539. ]);
  540. const truncated = applyConversationDeltas(afterAppend, [{ op: "row.removed", fromRowId: 2 }]);
  541. expect(truncated.rows.window.map((r) => r.rowId)).toEqual([1]);
  542. expect(truncated.rows.totalCount).toBe(1);
  543. expect(truncated.rows.firstRowId).toBe(1);
  544. // Bugfix 回归:从 active branch 首行裁剪后 rowId 分配仍继续递增,分页锚点必须
  545. // 先清空再由新分支首行建立,不能把 1..4 的空洞当成未加载历史。
  546. const removedFromHead = applyConversationDeltas(afterAppend, [
  547. { op: "row.removed", fromRowId: 1 },
  548. ]);
  549. expect(removedFromHead.rows).toEqual({ window: [], totalCount: 0, firstRowId: null });
  550. const rerun = applyConversationDeltas(removedFromHead, [
  551. { op: "row.appended", row: makeAssistantRow(5, "edited") },
  552. ]);
  553. expect(rerun.rows).toMatchObject({ totalCount: 1, firstRowId: 5 });
  554. expect(rerun.rows.window.map((row) => row.rowId)).toEqual([5]);
  555. // §4.3:patch 命中未加载 rowId = no-op
  556. const noop = applyConversationDeltas(truncated, [
  557. { op: "row.upserted", row: makeAssistantRow(99, "ghost") },
  558. { op: "row.delta", rowId: 42, path: "text", append: "ghost" },
  559. ]);
  560. expect(noop).toEqual(truncated);
  561. });
  562. it("state.updated replaces keys wholesale without deep merge", () => {
  563. const base = makeSnapshot();
  564. const next = applyConversationDeltas(base, [
  565. {
  566. op: "state.updated",
  567. patch: {
  568. control: {
  569. ...base.control,
  570. phase: "completedInterrupted",
  571. sessionEnded: true,
  572. canStop: false,
  573. stopState: "idle",
  574. },
  575. },
  576. },
  577. ]);
  578. expect(next.control.phase).toBe("completedInterrupted");
  579. // 其他 A 区键不受影响
  580. expect(next.config).toEqual(base.config);
  581. });
  582. });
  583. describe("zcode-protocol-v4 schema", () => {
  584. it("validates a full snapshot round-trip", () => {
  585. const snapshot = applyConversationDeltas(makeSnapshot(), [
  586. { op: "row.appended", row: makeAssistantRow(1, "hello") },
  587. ]);
  588. const parsed = conversationSnapshotSchema.parse(JSON.parse(JSON.stringify(snapshot)));
  589. expect(parsed).toEqual(snapshot);
  590. });
  591. it("BG27/BG28:snapshot round-trip 保留后台结果标题元数据", () => {
  592. const header: TurnHeaderRow = {
  593. rowId: 1,
  594. turnId: "background-turn",
  595. createdAt: 1000,
  596. createdAtSeq: 1,
  597. kind: "turnHeader",
  598. origin: "backgroundResult",
  599. originMeta: {
  600. backgroundSource: "subagent",
  601. title: "Review background result rendering",
  602. workId: "agent-review",
  603. },
  604. state: "completedSuccess",
  605. startedAt: 1000,
  606. endedAt: 2000,
  607. };
  608. const snapshot = applyConversationDeltas(makeSnapshot(), [{ op: "row.appended", row: header }]);
  609. const parsed = conversationSnapshotSchema.parse(JSON.parse(JSON.stringify(snapshot)));
  610. expect(parsed.rows.window[0]).toEqual(header);
  611. });
  612. it("keeps structured userInput questions in snapshot round-trip", () => {
  613. const snapshot: ConversationSnapshot = {
  614. ...makeSnapshot(),
  615. pendingInteractions: [
  616. {
  617. interactionId: "ask-1",
  618. kind: "userInput",
  619. anchorRowId: 2,
  620. createdAt: 1000,
  621. payload: {
  622. kind: "userInput",
  623. prompt: "请选择实现形式",
  624. freeText: true,
  625. toolName: "AskUserQuestion",
  626. toolCallId: "tool-ask",
  627. traceId: "trace-ask",
  628. input: { questions: [] },
  629. schema: { toolName: "AskUserQuestion" },
  630. currentQuestionIndex: 1,
  631. answerDrafts: { answer_0: ["独立页面"] },
  632. questions: [
  633. {
  634. question: "你想把番茄钟做成什么形式?",
  635. header: "形式",
  636. options: [
  637. {
  638. value: "page",
  639. label: "独立页面",
  640. description: "通过导航访问",
  641. preview: "新增 v4 页面入口",
  642. },
  643. ],
  644. },
  645. {
  646. question: "默认时长是多少?",
  647. header: "时长",
  648. options: [{ value: "25", label: "25 分钟" }],
  649. },
  650. ],
  651. },
  652. },
  653. ],
  654. };
  655. const parsed = conversationSnapshotSchema.parse(JSON.parse(JSON.stringify(snapshot)));
  656. expect(parsed.pendingInteractions[0]).toMatchObject({
  657. kind: "userInput",
  658. payload: {
  659. toolName: "AskUserQuestion",
  660. currentQuestionIndex: 1,
  661. answerDrafts: { answer_0: ["独立页面"] },
  662. },
  663. });
  664. const payload = parsed.pendingInteractions[0]?.payload;
  665. expect(payload?.kind).toBe("userInput");
  666. if (payload?.kind === "userInput") {
  667. expect(payload.questions).toHaveLength(2);
  668. expect(payload.questions?.[0]).toMatchObject({
  669. question: "你想把番茄钟做成什么形式?",
  670. options: [
  671. {
  672. value: "page",
  673. label: "独立页面",
  674. description: "通过导航访问",
  675. preview: "新增 v4 页面入口",
  676. },
  677. ],
  678. });
  679. }
  680. });
  681. });
  682. describe("zcode-protocol-v4 conflation", () => {
  683. it("keeps only the latest item per key, ordered by last occurrence", () => {
  684. const items = [
  685. { id: "a", v: 1 },
  686. { id: "b", v: 1 },
  687. { id: "a", v: 2 },
  688. { id: "c", v: 1 },
  689. { id: "b", v: 2 },
  690. ];
  691. expect(conflateByKey(items, (i) => i.id)).toEqual([
  692. { id: "a", v: 2 },
  693. { id: "c", v: 1 },
  694. { id: "b", v: 2 },
  695. ]);
  696. });
  697. });