zcodeProtocolV4Wire.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. PROTOCOL_V4_LIMITS,
  4. V4_NOTIFICATIONS,
  5. V4_WIRE_PROTOCOL_VERSION,
  6. clientHelloSchema,
  7. conversationTopicFrameSchema,
  8. conversationTopicWireFrameSchema,
  9. encodeTopicWireFrames,
  10. helloMessageSchema,
  11. reassembleTopicWireFrames,
  12. toolCallRowSchema,
  13. toolOutputSchema,
  14. utf8JsonByteLength,
  15. type ConversationSnapshot,
  16. type ConversationTopicFrame,
  17. type ConversationTopicWireFrame,
  18. } from "../src/zcode-protocol-v4/index.js";
  19. import {
  20. ZCODE_PROTOCOL_V4_WIRE_VERSION,
  21. ZCODE_PROTOCOL_VERSION,
  22. } from "../src/zcode-protocol/index.js";
  23. const TOPIC = "conversation/session-wire";
  24. const SUBSCRIPTION_ID = "sub-wire";
  25. const LOGICAL_FRAME_ID = "logical-wire";
  26. const DELIVERY_KIND = "online" as const;
  27. function makeFrame(append: string): ConversationTopicFrame {
  28. return {
  29. topic: TOPIC,
  30. subscriptionId: SUBSCRIPTION_ID,
  31. fromSeq: 10,
  32. toSeq: 11,
  33. sentAt: 1_700_000_000_000,
  34. payload: {
  35. kind: "deltas",
  36. deltas: [
  37. {
  38. op: "row.delta",
  39. rowId: 1,
  40. path: "text",
  41. append,
  42. },
  43. ],
  44. },
  45. };
  46. }
  47. function makeSnapshotFrame(title: string): ConversationTopicFrame {
  48. const snapshot: ConversationSnapshot = {
  49. protocolVersion: 1,
  50. sessionId: "session-wire",
  51. logEpoch: "epoch-wire",
  52. seq: 11,
  53. revision: 1,
  54. control: {
  55. phase: "running",
  56. sessionEnded: false,
  57. canStop: true,
  58. stopState: "stoppable",
  59. stopTargetKind: "assistant",
  60. activeWorks: [{ kind: "primaryTurn", startedAt: 1_000 }],
  61. lastError: null,
  62. apiRetry: null,
  63. },
  64. availability: {
  65. fork: { allowed: true },
  66. compact: { allowed: true },
  67. switchModelConfig: { allowed: true },
  68. setFollowupMode: { allowed: true },
  69. queueEdit: { allowed: true },
  70. sendQueuedNow: { allowed: true },
  71. pauseGoal: { allowed: false, reasonCode: "guard.noGoal" },
  72. resumeGoal: { allowed: false, reasonCode: "guard.noGoal" },
  73. },
  74. inputRouting: { mode: "enqueue" },
  75. meta: { title, titleSource: "custom" },
  76. config: {
  77. provider: "glm",
  78. model: "glm-5",
  79. thought: "medium",
  80. thoughtLevels: [],
  81. followupMode: "queue",
  82. mode: "build",
  83. },
  84. modelTransition: null,
  85. usage: {
  86. contextWindow: {
  87. usedTokens: 0,
  88. maxTokens: 200_000,
  89. autoCompactThresholdTokens: null,
  90. },
  91. cumulative: {
  92. inputTokens: 0,
  93. outputTokens: 0,
  94. cacheReadTokens: 0,
  95. cacheWriteTokens: 0,
  96. },
  97. },
  98. queue: { items: [], autoDrain: true },
  99. pendingInteractions: [],
  100. pendingCommands: [],
  101. backgroundWorks: [],
  102. // 软门禁 additive 字段:归一化形态(带 default(null))
  103. workspaceHookAdmission: null,
  104. goal: null,
  105. plan: null,
  106. rows: { window: [], totalCount: 0, firstRowId: null },
  107. };
  108. return {
  109. topic: TOPIC,
  110. subscriptionId: SUBSCRIPTION_ID,
  111. fromSeq: 0,
  112. toSeq: snapshot.seq,
  113. sentAt: 1_700_000_000_000,
  114. payload: { kind: "snapshot", snapshot },
  115. };
  116. }
  117. function notificationBytes(wire: ConversationTopicWireFrame): number {
  118. return new TextEncoder().encode(
  119. `${JSON.stringify({
  120. method: V4_NOTIFICATIONS.conversationFrame,
  121. params: wire,
  122. })}\n`,
  123. ).byteLength;
  124. }
  125. function encode(frame: ConversationTopicFrame, maxPhysicalFrameBytes?: number) {
  126. return encodeTopicWireFrames(frame, {
  127. topic: TOPIC,
  128. subscriptionId: SUBSCRIPTION_ID,
  129. logicalFrameId: LOGICAL_FRAME_ID,
  130. logicalFrameOrdinal: 1,
  131. deliveryKind: DELIVERY_KIND,
  132. ...(maxPhysicalFrameBytes === undefined ? {} : { maxPhysicalFrameBytes }),
  133. measurePhysicalFrameBytes: notificationBytes,
  134. });
  135. }
  136. function frameAtLogicalBytes(targetBytes: number): ConversationTopicFrame {
  137. const empty = makeFrame("");
  138. const overhead = utf8JsonByteLength(empty);
  139. expect(overhead).toBeLessThan(targetBytes);
  140. const frame = makeFrame("x".repeat(targetBytes - overhead));
  141. expect(utf8JsonByteLength(frame)).toBe(targetBytes);
  142. return frame;
  143. }
  144. function frameAtCompletePhysicalBytes(targetBytes: number): ConversationTopicFrame {
  145. const empty = makeFrame("");
  146. const emptyWire: ConversationTopicWireFrame = {
  147. wireVersion: V4_WIRE_PROTOCOL_VERSION,
  148. kind: "complete",
  149. deliveryKind: DELIVERY_KIND,
  150. logicalFrameId: LOGICAL_FRAME_ID,
  151. logicalFrameOrdinal: 1,
  152. topic: TOPIC,
  153. subscriptionId: SUBSCRIPTION_ID,
  154. frame: empty,
  155. };
  156. const overhead = notificationBytes(emptyWire);
  157. expect(overhead).toBeLessThan(targetBytes);
  158. const frame = makeFrame("x".repeat(targetBytes - overhead));
  159. const wire: ConversationTopicWireFrame = { ...emptyWire, frame };
  160. expect(notificationBytes(wire)).toBe(targetBytes);
  161. return frame;
  162. }
  163. describe("ZCode Protocol V4 wire v3", () => {
  164. it("硬切 V4 wire/hello 到 v3,但不改变 legacy 主协议版本", () => {
  165. expect(V4_WIRE_PROTOCOL_VERSION).toBe(3);
  166. expect(ZCODE_PROTOCOL_V4_WIRE_VERSION).toBe(3);
  167. expect(ZCODE_PROTOCOL_VERSION).toBe(1);
  168. expect(
  169. helloMessageSchema.safeParse({
  170. kind: "hello",
  171. protocolVersion: 3,
  172. connectionId: "connection-1",
  173. clientMode: "desktop-continuous",
  174. deliveryProfile: "continuous",
  175. serverTime: 1,
  176. capabilities: {
  177. nativeDialogs: true,
  178. localTerminal: true,
  179. binaryFrames: false,
  180. compression: "none",
  181. },
  182. auth: {},
  183. }).success,
  184. ).toBe(true);
  185. expect(
  186. helloMessageSchema.safeParse({
  187. kind: "hello",
  188. protocolVersion: 1,
  189. connectionId: "connection-1",
  190. clientMode: "desktop-continuous",
  191. deliveryProfile: "continuous",
  192. serverTime: 1,
  193. capabilities: {
  194. nativeDialogs: true,
  195. localTerminal: true,
  196. binaryFrames: false,
  197. compression: "none",
  198. },
  199. auth: {},
  200. }).success,
  201. ).toBe(false);
  202. expect(
  203. clientHelloSchema.safeParse({
  204. kind: "clientHello",
  205. protocolVersion: 3,
  206. clientId: "client-1",
  207. clientKind: "desktop",
  208. appVersion: "4.0.0",
  209. }).success,
  210. ).toBe(true);
  211. expect(
  212. clientHelloSchema.safeParse({
  213. kind: "clientHello",
  214. protocolVersion: 3,
  215. clientId: "client-1",
  216. clientMode: "mobileRemote",
  217. appVersion: "4.0.0",
  218. }).success,
  219. ).toBe(false);
  220. expect(
  221. helloMessageSchema.safeParse({
  222. kind: "hello",
  223. protocolVersion: 3,
  224. connectionId: "connection-1",
  225. clientMode: "desktop-continuous",
  226. deliveryProfile: "replayable",
  227. serverTime: 1,
  228. capabilities: {
  229. nativeDialogs: true,
  230. localTerminal: true,
  231. binaryFrames: false,
  232. compression: "none",
  233. },
  234. auth: {},
  235. }).success,
  236. ).toBe(false);
  237. });
  238. it.each([
  239. {
  240. kind: "task_output",
  241. retrievalStatus: "success",
  242. taskStatus: "completed",
  243. output: "done",
  244. },
  245. {
  246. kind: "respond_to_coordinator",
  247. status: "success",
  248. },
  249. ] as const)("ToolCallRow wire 接受 $kind display", (display) => {
  250. expect(
  251. toolCallRowSchema.safeParse({
  252. rowId: 1,
  253. turnId: "turn-1",
  254. createdAt: 1,
  255. createdAtSeq: 1,
  256. kind: "toolCall",
  257. toolCallId: "call-1",
  258. toolName: "TaskOutput",
  259. status: "success",
  260. inputText: "{}",
  261. display,
  262. }).success,
  263. ).toBe(true);
  264. });
  265. it("ToolCallRow wire 接受 CUA App 身份并拒绝非法 PID", () => {
  266. const row = {
  267. rowId: 1,
  268. turnId: "turn-1",
  269. createdAt: 1,
  270. createdAtSeq: 1,
  271. kind: "toolCall",
  272. toolCallId: "call-1",
  273. toolName: "mcp__computer-use__key",
  274. status: "running",
  275. inputText: "{}",
  276. cuaApp: { pid: 42, name: "Zed", bundleId: "dev.zed.Zed" },
  277. };
  278. expect(toolCallRowSchema.safeParse(row).success).toBe(true);
  279. expect(toolCallRowSchema.safeParse({ ...row, cuaApp: { pid: 0, name: "Zed" } }).success).toBe(
  280. false,
  281. );
  282. });
  283. it.each([
  284. {
  285. kind: "task_output",
  286. retrievalStatus: "success",
  287. taskStatus: "completed",
  288. output: "done",
  289. },
  290. {
  291. kind: "respond_to_coordinator",
  292. status: "success",
  293. },
  294. {
  295. kind: "mcp_tool",
  296. serverName: "browser",
  297. toolName: "open",
  298. },
  299. ] as const)("ToolOutput wire 接受 $kind display", (display) => {
  300. expect(toolOutputSchema.safeParse({ text: "done", display }).success).toBe(true);
  301. });
  302. // file_diff 仍然不是本端开放的 wire display kind——但"不开放"的代价只是这张卡没有载荷,
  303. // 不再是整条 row 被拒(display 在信封层不设门,见 zcodeProtocolV4DisplayTolerance.test.ts)。
  304. it("ToolCallRow wire 丢弃未开放的 file_diff display,但不拒整条 row", () => {
  305. const parsed = toolCallRowSchema.safeParse({
  306. rowId: 1,
  307. turnId: "turn-1",
  308. createdAt: 1,
  309. createdAtSeq: 1,
  310. kind: "toolCall",
  311. toolCallId: "call-1",
  312. toolName: "Edit",
  313. status: "success",
  314. inputText: "{}",
  315. display: {
  316. kind: "file_diff",
  317. filePath: "/workspace/app.ts",
  318. additions: 1,
  319. deletions: 0,
  320. structuredPatch: [],
  321. },
  322. });
  323. expect(parsed.success).toBe(true);
  324. if (parsed.success) expect(parsed.data.display).toBeUndefined();
  325. });
  326. it("按完整 notification envelope 执行 1MiB 前一字节、正好、后一字节边界", () => {
  327. const max = PROTOCOL_V4_LIMITS.maxFrameBytes;
  328. for (const target of [max - 1, max]) {
  329. const wires = encode(frameAtCompletePhysicalBytes(target));
  330. expect(wires).toHaveLength(1);
  331. expect(wires[0]?.kind).toBe("complete");
  332. expect(notificationBytes(wires[0]!)).toBe(target);
  333. }
  334. const fragmented = encode(frameAtCompletePhysicalBytes(max + 1));
  335. expect(fragmented.length).toBeGreaterThan(1);
  336. expect(fragmented.every((wire) => wire.kind === "fragment")).toBe(true);
  337. for (const wire of fragmented) {
  338. expect(notificationBytes(wire)).toBeLessThanOrEqual(max);
  339. }
  340. });
  341. it("在多字节 UTF-8 byte stream 中分片并逐字段无损重组", () => {
  342. const frame = makeFrame("中文🙂边界".repeat(400));
  343. const wires = encode(frame, 480);
  344. expect(wires.length).toBeGreaterThan(2);
  345. const result = reassembleTopicWireFrames(wires, conversationTopicFrameSchema);
  346. expect(result).toEqual({
  347. kind: "complete",
  348. frame,
  349. deliveryKind: DELIVERY_KIND,
  350. });
  351. });
  352. it("分片不改变 logical frame 的 seq 区间", () => {
  353. const frame = makeFrame("resume".repeat(500));
  354. const wires = encode(frame, 512);
  355. const result = reassembleTopicWireFrames(wires, conversationTopicFrameSchema);
  356. expect(result.kind).toBe("complete");
  357. if (result.kind === "complete") {
  358. expect(result.frame.fromSeq).toBe(10);
  359. expect(result.frame.toSeq).toBe(11);
  360. expect(result.frame).toEqual(frame);
  361. }
  362. });
  363. it("超大 snapshot 分片后完整校验并原子重组", () => {
  364. const frame = makeSnapshotFrame("snapshot-title".repeat(600));
  365. const wires = encode(frame, 480);
  366. expect(wires.length).toBeGreaterThan(2);
  367. expect(reassembleTopicWireFrames(wires, conversationTopicFrameSchema)).toEqual({
  368. kind: "complete",
  369. frame,
  370. deliveryKind: DELIVERY_KIND,
  371. });
  372. });
  373. it("乱序 fragment 与完全相同的重复片仍只组装一次", () => {
  374. const frame = makeFrame("out-of-order".repeat(500));
  375. const wires = encode(frame, 480);
  376. const reordered = [...wires].reverse();
  377. reordered.splice(1, 0, reordered[0]!);
  378. expect(reassembleTopicWireFrames(reordered, conversationTopicFrameSchema)).toEqual({
  379. kind: "complete",
  380. frame,
  381. deliveryKind: DELIVERY_KIND,
  382. });
  383. });
  384. it("缺失中间 fragment 时只返回 incomplete,不产生 partial logical frame", () => {
  385. const wires = encode(makeFrame("missing".repeat(600)), 480);
  386. expect(wires.length).toBeGreaterThan(2);
  387. const withoutMiddle = wires.filter((_, index) => index !== 1);
  388. expect(reassembleTopicWireFrames(withoutMiddle, conversationTopicFrameSchema)).toEqual({
  389. kind: "incomplete",
  390. logicalFrameId: LOGICAL_FRAME_ID,
  391. missingIndexes: [1],
  392. });
  393. });
  394. it("checksum 或 logicalBytes 被篡改时明确拒绝", () => {
  395. const wires = encode(makeFrame("checksum".repeat(500)), 480);
  396. const first = wires[0]!;
  397. expect(first.kind).toBe("fragment");
  398. if (first.kind !== "fragment") return;
  399. const tamperedChecksum = wires.map((wire) =>
  400. wire.kind === "fragment"
  401. ? {
  402. ...wire,
  403. checksum: { algorithm: "crc32" as const, value: "00000000" },
  404. }
  405. : wire,
  406. );
  407. expect(reassembleTopicWireFrames(tamperedChecksum, conversationTopicFrameSchema)).toMatchObject(
  408. {
  409. kind: "rejected",
  410. reasonCode: "proto.frameAssemblyChecksumMismatch",
  411. },
  412. );
  413. const tamperedLength = [{ ...first, logicalBytes: first.logicalBytes + 1 }, ...wires.slice(1)];
  414. expect(reassembleTopicWireFrames(tamperedLength, conversationTopicFrameSchema)).toMatchObject({
  415. kind: "rejected",
  416. reasonCode: "proto.frameAssemblyMetadataMismatch",
  417. });
  418. const mixedOrdinal = [
  419. first,
  420. ...wires
  421. .slice(1)
  422. .map((wire) =>
  423. wire.kind === "fragment"
  424. ? { ...wire, logicalFrameOrdinal: wire.logicalFrameOrdinal + 1 }
  425. : wire,
  426. ),
  427. ];
  428. expect(reassembleTopicWireFrames(mixedOrdinal, conversationTopicFrameSchema)).toMatchObject({
  429. kind: "rejected",
  430. reasonCode: "proto.frameAssemblyMetadataMismatch",
  431. });
  432. });
  433. it("logical assembly 正好 16MiB 可重组,超一字节明确拒绝", () => {
  434. const max = PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxBytes;
  435. const exact = frameAtLogicalBytes(max);
  436. const result = reassembleTopicWireFrames(encode(exact), conversationTopicFrameSchema);
  437. expect(result.kind).toBe("complete");
  438. expect(() => encode(frameAtLogicalBytes(max + 1))).toThrowError(
  439. expect.objectContaining({ reasonCode: "proto.frameAssemblyTooLarge" }),
  440. );
  441. expect(
  442. reassembleTopicWireFrames(
  443. [
  444. {
  445. wireVersion: 3,
  446. kind: "fragment",
  447. logicalFrameId: "oversized",
  448. logicalFrameOrdinal: 1,
  449. topic: TOPIC,
  450. subscriptionId: SUBSCRIPTION_ID,
  451. fragmentIndex: 0,
  452. fragmentCount: 1,
  453. logicalBytes: max + 1,
  454. checksum: { algorithm: "crc32", value: "00000000" },
  455. dataBase64: "AA==",
  456. },
  457. ],
  458. conversationTopicFrameSchema,
  459. ),
  460. ).toEqual({
  461. kind: "rejected",
  462. reasonCode: "proto.frameAssemblyTooLarge",
  463. });
  464. const oversizedComplete: ConversationTopicWireFrame = {
  465. wireVersion: 3,
  466. kind: "complete",
  467. logicalFrameId: "oversized-complete",
  468. logicalFrameOrdinal: 1,
  469. topic: TOPIC,
  470. subscriptionId: SUBSCRIPTION_ID,
  471. frame: makeFrame("x".repeat(200)),
  472. };
  473. expect(
  474. reassembleTopicWireFrames([oversizedComplete], conversationTopicFrameSchema, {
  475. maxAssemblyBytes: 100,
  476. }),
  477. ).toEqual({
  478. kind: "rejected",
  479. reasonCode: "proto.frameAssemblyTooLarge",
  480. });
  481. const cumulativeOverflow = {
  482. wireVersion: 3 as const,
  483. kind: "fragment" as const,
  484. logicalFrameId: "cumulative-overflow",
  485. logicalFrameOrdinal: 1,
  486. topic: TOPIC,
  487. subscriptionId: SUBSCRIPTION_ID,
  488. fragmentIndex: 0,
  489. fragmentCount: 2,
  490. logicalBytes: 100,
  491. checksum: { algorithm: "crc32" as const, value: "00000000" },
  492. // 102 个零字节;即使其余分片尚未到达,也不能把超限 staging 留在内存。
  493. dataBase64: "A".repeat(136),
  494. };
  495. expect(
  496. reassembleTopicWireFrames([cumulativeOverflow], conversationTopicFrameSchema, {
  497. maxAssemblyBytes: 100,
  498. }),
  499. ).toEqual({
  500. kind: "rejected",
  501. reasonCode: "proto.frameAssemblyTooLarge",
  502. });
  503. });
  504. it("wire schema fail-closed 拒绝非法 fragment metadata", () => {
  505. const invalid = {
  506. wireVersion: 3,
  507. kind: "fragment",
  508. logicalFrameId: "logical-invalid",
  509. logicalFrameOrdinal: 1,
  510. topic: TOPIC,
  511. subscriptionId: SUBSCRIPTION_ID,
  512. fragmentIndex: 2,
  513. fragmentCount: 2,
  514. logicalBytes: 10,
  515. checksum: { algorithm: "crc32", value: "12345678" },
  516. dataBase64: "AA==",
  517. };
  518. expect(conversationTopicWireFrameSchema.safeParse(invalid).success).toBe(false);
  519. expect(
  520. conversationTopicWireFrameSchema.safeParse({
  521. ...invalid,
  522. fragmentIndex: 0,
  523. fragmentCount: 11,
  524. logicalBytes: 10,
  525. }).success,
  526. ).toBe(false);
  527. const excessiveCount = {
  528. ...invalid,
  529. fragmentIndex: 0,
  530. fragmentCount: 1_025,
  531. logicalBytes: 1_025,
  532. };
  533. expect(conversationTopicWireFrameSchema.safeParse(excessiveCount).success).toBe(false);
  534. expect(reassembleTopicWireFrames([excessiveCount], conversationTopicFrameSchema)).toEqual({
  535. kind: "rejected",
  536. reasonCode: "proto.frameFragmentCountExceeded",
  537. });
  538. expect(() =>
  539. encodeTopicWireFrames(makeFrame("encoder-limit".repeat(100)), {
  540. topic: TOPIC,
  541. subscriptionId: SUBSCRIPTION_ID,
  542. logicalFrameId: "encoder-fragment-limit",
  543. logicalFrameOrdinal: 1,
  544. maxPhysicalFrameBytes: 1,
  545. // 强制每片只承载一个 logical byte,单独验证 encoder 的 admission guard。
  546. measurePhysicalFrameBytes: (wire) => (wire.kind === "complete" ? 2 : 1),
  547. }),
  548. ).toThrowError(
  549. expect.objectContaining({
  550. reasonCode: "proto.frameFragmentCountExceeded",
  551. }),
  552. );
  553. });
  554. });