zcodeProtocolV4Wire.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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("超大 snapshot 分片后完整校验并原子重组", () => {
  353. const frame = makeSnapshotFrame("snapshot-title".repeat(600));
  354. const wires = encode(frame, 480);
  355. expect(wires.length).toBeGreaterThan(2);
  356. expect(reassembleTopicWireFrames(wires, conversationTopicFrameSchema)).toEqual({
  357. kind: "complete",
  358. frame,
  359. deliveryKind: DELIVERY_KIND,
  360. });
  361. });
  362. it("乱序 fragment 与完全相同的重复片仍只组装一次", () => {
  363. const frame = makeFrame("out-of-order".repeat(500));
  364. const wires = encode(frame, 480);
  365. const reordered = [...wires].reverse();
  366. reordered.splice(1, 0, reordered[0]!);
  367. expect(reassembleTopicWireFrames(reordered, conversationTopicFrameSchema)).toEqual({
  368. kind: "complete",
  369. frame,
  370. deliveryKind: DELIVERY_KIND,
  371. });
  372. });
  373. it("缺失中间 fragment 时只返回 incomplete,不产生 partial logical frame", () => {
  374. const wires = encode(makeFrame("missing".repeat(600)), 480);
  375. expect(wires.length).toBeGreaterThan(2);
  376. const withoutMiddle = wires.filter((_, index) => index !== 1);
  377. expect(reassembleTopicWireFrames(withoutMiddle, conversationTopicFrameSchema)).toEqual({
  378. kind: "incomplete",
  379. logicalFrameId: LOGICAL_FRAME_ID,
  380. missingIndexes: [1],
  381. });
  382. });
  383. it("checksum 或 logicalBytes 被篡改时明确拒绝", () => {
  384. const wires = encode(makeFrame("checksum".repeat(500)), 480);
  385. const first = wires[0]!;
  386. expect(first.kind).toBe("fragment");
  387. if (first.kind !== "fragment") return;
  388. const tamperedChecksum = wires.map((wire) =>
  389. wire.kind === "fragment"
  390. ? {
  391. ...wire,
  392. checksum: { algorithm: "crc32" as const, value: "00000000" },
  393. }
  394. : wire,
  395. );
  396. expect(reassembleTopicWireFrames(tamperedChecksum, conversationTopicFrameSchema)).toMatchObject(
  397. {
  398. kind: "rejected",
  399. reasonCode: "proto.frameAssemblyChecksumMismatch",
  400. },
  401. );
  402. const tamperedLength = [{ ...first, logicalBytes: first.logicalBytes + 1 }, ...wires.slice(1)];
  403. expect(reassembleTopicWireFrames(tamperedLength, conversationTopicFrameSchema)).toMatchObject({
  404. kind: "rejected",
  405. reasonCode: "proto.frameAssemblyMetadataMismatch",
  406. });
  407. const mixedOrdinal = [
  408. first,
  409. ...wires
  410. .slice(1)
  411. .map((wire) =>
  412. wire.kind === "fragment"
  413. ? { ...wire, logicalFrameOrdinal: wire.logicalFrameOrdinal + 1 }
  414. : wire,
  415. ),
  416. ];
  417. expect(reassembleTopicWireFrames(mixedOrdinal, conversationTopicFrameSchema)).toMatchObject({
  418. kind: "rejected",
  419. reasonCode: "proto.frameAssemblyMetadataMismatch",
  420. });
  421. });
  422. it("logical assembly 正好 16MiB 可重组,超一字节明确拒绝", () => {
  423. const max = PROTOCOL_V4_LIMITS.logicalFrameAssemblyMaxBytes;
  424. const exact = frameAtLogicalBytes(max);
  425. const result = reassembleTopicWireFrames(encode(exact), conversationTopicFrameSchema);
  426. expect(result.kind).toBe("complete");
  427. expect(() => encode(frameAtLogicalBytes(max + 1))).toThrowError(
  428. expect.objectContaining({ reasonCode: "proto.frameAssemblyTooLarge" }),
  429. );
  430. expect(
  431. reassembleTopicWireFrames(
  432. [
  433. {
  434. wireVersion: 3,
  435. kind: "fragment",
  436. logicalFrameId: "oversized",
  437. logicalFrameOrdinal: 1,
  438. topic: TOPIC,
  439. subscriptionId: SUBSCRIPTION_ID,
  440. fragmentIndex: 0,
  441. fragmentCount: 1,
  442. logicalBytes: max + 1,
  443. checksum: { algorithm: "crc32", value: "00000000" },
  444. dataBase64: "AA==",
  445. },
  446. ],
  447. conversationTopicFrameSchema,
  448. ),
  449. ).toEqual({
  450. kind: "rejected",
  451. reasonCode: "proto.frameAssemblyTooLarge",
  452. });
  453. const oversizedComplete: ConversationTopicWireFrame = {
  454. wireVersion: 3,
  455. kind: "complete",
  456. logicalFrameId: "oversized-complete",
  457. logicalFrameOrdinal: 1,
  458. topic: TOPIC,
  459. subscriptionId: SUBSCRIPTION_ID,
  460. frame: makeFrame("x".repeat(200)),
  461. };
  462. expect(
  463. reassembleTopicWireFrames([oversizedComplete], conversationTopicFrameSchema, {
  464. maxAssemblyBytes: 100,
  465. }),
  466. ).toEqual({
  467. kind: "rejected",
  468. reasonCode: "proto.frameAssemblyTooLarge",
  469. });
  470. const cumulativeOverflow = {
  471. wireVersion: 3 as const,
  472. kind: "fragment" as const,
  473. logicalFrameId: "cumulative-overflow",
  474. logicalFrameOrdinal: 1,
  475. topic: TOPIC,
  476. subscriptionId: SUBSCRIPTION_ID,
  477. fragmentIndex: 0,
  478. fragmentCount: 2,
  479. logicalBytes: 100,
  480. checksum: { algorithm: "crc32" as const, value: "00000000" },
  481. // 102 个零字节;即使其余分片尚未到达,也不能把超限 staging 留在内存。
  482. dataBase64: "A".repeat(136),
  483. };
  484. expect(
  485. reassembleTopicWireFrames([cumulativeOverflow], conversationTopicFrameSchema, {
  486. maxAssemblyBytes: 100,
  487. }),
  488. ).toEqual({
  489. kind: "rejected",
  490. reasonCode: "proto.frameAssemblyTooLarge",
  491. });
  492. });
  493. it("wire schema fail-closed 拒绝非法 fragment metadata", () => {
  494. const invalid = {
  495. wireVersion: 3,
  496. kind: "fragment",
  497. logicalFrameId: "logical-invalid",
  498. logicalFrameOrdinal: 1,
  499. topic: TOPIC,
  500. subscriptionId: SUBSCRIPTION_ID,
  501. fragmentIndex: 2,
  502. fragmentCount: 2,
  503. logicalBytes: 10,
  504. checksum: { algorithm: "crc32", value: "12345678" },
  505. dataBase64: "AA==",
  506. };
  507. expect(conversationTopicWireFrameSchema.safeParse(invalid).success).toBe(false);
  508. expect(
  509. conversationTopicWireFrameSchema.safeParse({
  510. ...invalid,
  511. fragmentIndex: 0,
  512. fragmentCount: 11,
  513. logicalBytes: 10,
  514. }).success,
  515. ).toBe(false);
  516. const excessiveCount = {
  517. ...invalid,
  518. fragmentIndex: 0,
  519. fragmentCount: 1_025,
  520. logicalBytes: 1_025,
  521. };
  522. expect(conversationTopicWireFrameSchema.safeParse(excessiveCount).success).toBe(false);
  523. expect(reassembleTopicWireFrames([excessiveCount], conversationTopicFrameSchema)).toEqual({
  524. kind: "rejected",
  525. reasonCode: "proto.frameFragmentCountExceeded",
  526. });
  527. expect(() =>
  528. encodeTopicWireFrames(makeFrame("encoder-limit".repeat(100)), {
  529. topic: TOPIC,
  530. subscriptionId: SUBSCRIPTION_ID,
  531. logicalFrameId: "encoder-fragment-limit",
  532. logicalFrameOrdinal: 1,
  533. maxPhysicalFrameBytes: 1,
  534. // 强制每片只承载一个 logical byte,单独验证 encoder 的 admission guard。
  535. measurePhysicalFrameBytes: (wire) => (wire.kind === "complete" ? 2 : 1),
  536. }),
  537. ).toThrowError(
  538. expect.objectContaining({
  539. reasonCode: "proto.frameFragmentCountExceeded",
  540. }),
  541. );
  542. });
  543. });