zcodeProtocolV4Command.test.ts 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. COMMANDS_REQUIRING_BASE_REVISION,
  4. SAVED_WORKFLOW_START_REJECTED_FAULT_PREFIX,
  5. V4_WIRE_PROTOCOL_VERSION,
  6. WORKFLOW_RUN_SETTINGS_REJECTED_FAULT_PREFIX,
  7. commandAckSchema,
  8. commandPayloadSchemas,
  9. commandResultSchema,
  10. helloMessageSchema,
  11. parseCommandEnvelope,
  12. savedWorkflowStartRejectionReasonSchema,
  13. modelSelectionSchema,
  14. workflowRunSettingsRejectionReasonSchema,
  15. } from "../src/zcode-protocol-v4/index.js";
  16. describe("zcode-protocol-v4 command", () => {
  17. it("parses a valid sendText envelope with typed payload", () => {
  18. const result = parseCommandEnvelope({
  19. commandId: "018f0000-0000-7000-8000-000000000001",
  20. clientId: "client-1",
  21. sessionId: "s-1",
  22. type: "sendText",
  23. payload: { text: "帮我重构" },
  24. issuedAt: 1000,
  25. });
  26. expect(result.ok).toBe(true);
  27. if (result.ok) {
  28. expect(result.envelope.type).toBe("sendText");
  29. expect(result.envelope.payload).toEqual({ text: "帮我重构" });
  30. }
  31. });
  32. it("keeps the submitted model selection and mode in the same sendText payload", () => {
  33. const modelSelection = modelSelectionSchema.parse({
  34. providerId: "deepseek",
  35. modelId: "deepseek-v4",
  36. options: { reasoningLevel: "high" },
  37. });
  38. const payload = commandPayloadSchemas.sendText.parse({
  39. text: "使用这次提交选择的模型",
  40. modelSelection,
  41. mode: "build",
  42. });
  43. expect(payload).toMatchObject({
  44. modelSelection,
  45. mode: "build",
  46. });
  47. });
  48. it("parses sendText turn-scoped tool disallowlist", () => {
  49. const payload = commandPayloadSchemas.sendText.parse({
  50. text: "继续当前定时任务会话",
  51. toolDisallowlist: ["CronCreate"],
  52. });
  53. expect(payload.toolDisallowlist).toEqual(["CronCreate"]);
  54. });
  55. it("parses strict Highspeed message metadata on sendText", () => {
  56. const highspeedMeta = {
  57. schemaVersion: 1 as const,
  58. cardId: "hsc-1",
  59. taskId: "task-1",
  60. provider: "zai",
  61. model: "glm-5",
  62. issuedAt: 1_000,
  63. expiresAt: 10_000,
  64. };
  65. expect(commandPayloadSchemas.sendText.parse({ text: "accelerate", highspeedMeta })).toEqual({
  66. text: "accelerate",
  67. highspeedMeta,
  68. });
  69. expect(() =>
  70. commandPayloadSchemas.sendText.parse({
  71. text: "invalid",
  72. highspeedMeta: { ...highspeedMeta, runtimeApiKey: "must-not-persist" },
  73. }),
  74. ).toThrow();
  75. });
  76. it("preserves strict shared-context references on sendText", () => {
  77. const payload = commandPayloadSchemas.sendText.parse({
  78. text: "请继续这个分享里的工作",
  79. context_refs: [{ kind: "shared_context_import", context_id: "context-1" }],
  80. });
  81. expect(payload.context_refs).toEqual([
  82. { kind: "shared_context_import", context_id: "context-1" },
  83. ]);
  84. expect(
  85. commandPayloadSchemas.sendText.safeParse({
  86. text: "invalid",
  87. context_refs: [{ kind: "shared_context_import", context_id: "" }],
  88. }).success,
  89. ).toBe(false);
  90. expect(
  91. commandPayloadSchemas.sendText.safeParse({
  92. text: "invalid",
  93. context_refs: [{ kind: "other", context_id: "context-1" }],
  94. }).success,
  95. ).toBe(false);
  96. });
  97. it("accepts the authoritative shared-context discard command", () => {
  98. expect(commandPayloadSchemas.discardSharedContext.parse({ contextId: "context-1" })).toEqual({
  99. contextId: "context-1",
  100. });
  101. expect(commandPayloadSchemas.discardSharedContext.safeParse({ contextId: "" }).success).toBe(
  102. false,
  103. );
  104. });
  105. it("parses a one-message start-now, queue or guide delivery override", () => {
  106. expect(
  107. commandPayloadSchemas.sendText.parse({
  108. text: "preempt current turn",
  109. requestedDelivery: "startNow",
  110. }),
  111. ).toEqual({ text: "preempt current turn", requestedDelivery: "startNow" });
  112. expect(
  113. commandPayloadSchemas.sendText.parse({
  114. text: "opposite follow-up",
  115. requestedDelivery: "guide",
  116. }),
  117. ).toEqual({ text: "opposite follow-up", requestedDelivery: "guide" });
  118. expect(
  119. commandPayloadSchemas.sendText.parse({
  120. text: "opposite follow-up",
  121. requestedDelivery: "queue",
  122. }),
  123. ).toEqual({ text: "opposite follow-up", requestedDelivery: "queue" });
  124. });
  125. it("validates bot delivery target on sendText", () => {
  126. const payload = commandPayloadSchemas.sendText.parse({
  127. text: "创建一个定时任务",
  128. botDeliveryTarget: {
  129. provider: "feishu",
  130. botId: "bot-feishu",
  131. providerUserId: "chat-1",
  132. chatType: "group",
  133. },
  134. });
  135. expect(payload.botDeliveryTarget).toEqual({
  136. provider: "feishu",
  137. botId: "bot-feishu",
  138. providerUserId: "chat-1",
  139. chatType: "group",
  140. });
  141. expect(
  142. commandPayloadSchemas.sendText.safeParse({
  143. text: "invalid",
  144. botDeliveryTarget: {
  145. provider: "telegram",
  146. botId: "bot-telegram",
  147. providerUserId: "chat-1",
  148. chatType: "private",
  149. },
  150. }).success,
  151. ).toBe(false);
  152. expect(
  153. commandPayloadSchemas.sendText.safeParse({
  154. text: "invalid",
  155. botDeliveryTarget: {
  156. provider: "weixin",
  157. botId: "bot-weixin",
  158. providerUserId: "chat-1",
  159. chatType: "private",
  160. providerMessageId: "must-not-persist",
  161. },
  162. }).success,
  163. ).toBe(false);
  164. });
  165. it("Off-Peak attribution is turn-scoped and mutually exclusive with automation", () => {
  166. expect(
  167. commandPayloadSchemas.sendText.parse({
  168. text: "resume",
  169. offPeakTaskId: "offpeak-1",
  170. offPeakRunType: "resume",
  171. toolDisallowlist: ["CronCreate"],
  172. futureAdditiveField: "ignored-by-current-cli",
  173. }),
  174. ).toEqual({
  175. text: "resume",
  176. offPeakTaskId: "offpeak-1",
  177. offPeakRunType: "resume",
  178. toolDisallowlist: ["CronCreate"],
  179. });
  180. expect(() =>
  181. commandPayloadSchemas.sendText.parse({
  182. text: "invalid",
  183. offPeakRunType: "init",
  184. }),
  185. ).toThrow();
  186. expect(() =>
  187. commandPayloadSchemas.sendText.parse({
  188. text: "invalid",
  189. automationId: "automation-1",
  190. offPeakTaskId: "offpeak-1",
  191. }),
  192. ).toThrow();
  193. });
  194. it("keeps execution-scoped model context narrow and drops the legacy runtime snapshot", () => {
  195. const payload = commandPayloadSchemas.sendText.parse({
  196. text: "run with an execution-scoped model",
  197. modelSelection: {
  198. providerId: "account:zai-offpeak-idle-plan",
  199. modelId: "GLM-5.2",
  200. },
  201. modelExecution: {
  202. memoryExtraction: "skip",
  203. selectionScope: "execution",
  204. requestAuth: {
  205. apiKey: "request-key",
  206. headers: { "X-Off-Peak-Ticket-ID": "ticket-1" },
  207. },
  208. subagents: {
  209. foregroundModel: "submission",
  210. background: "deny",
  211. },
  212. },
  213. turnRuntimeModel: {
  214. provider: { api: { baseUrl: "https://must-not-cross-the-wire.example" } },
  215. },
  216. });
  217. expect(payload).toEqual({
  218. text: "run with an execution-scoped model",
  219. modelSelection: {
  220. providerId: "account:zai-offpeak-idle-plan",
  221. modelId: "GLM-5.2",
  222. },
  223. modelExecution: {
  224. memoryExtraction: "skip",
  225. selectionScope: "execution",
  226. requestAuth: {
  227. apiKey: "request-key",
  228. headers: { "X-Off-Peak-Ticket-ID": "ticket-1" },
  229. },
  230. subagents: {
  231. foregroundModel: "submission",
  232. background: "deny",
  233. },
  234. },
  235. });
  236. });
  237. it("only accepts the explicit per-turn Memory Extraction skip policy", () => {
  238. expect(
  239. commandPayloadSchemas.sendText.parse({
  240. text: "do not extract this turn",
  241. modelSelection: { providerId: "offpeak", modelId: "model" },
  242. modelExecution: { memoryExtraction: "skip", selectionScope: "execution" },
  243. }),
  244. ).toMatchObject({ modelExecution: { memoryExtraction: "skip" } });
  245. expect(
  246. commandPayloadSchemas.sendText.safeParse({
  247. text: "invalid Memory policy",
  248. modelSelection: { providerId: "offpeak", modelId: "model" },
  249. modelExecution: { memoryExtraction: "disabled", selectionScope: "execution" },
  250. }).success,
  251. ).toBe(false);
  252. });
  253. it("rejects static provider facts inside model execution context", () => {
  254. expect(
  255. commandPayloadSchemas.sendText.safeParse({
  256. text: "invalid execution context",
  257. modelSelection: {
  258. providerId: "account:zai-offpeak-idle-plan",
  259. modelId: "GLM-5.2",
  260. },
  261. modelExecution: {
  262. selectionScope: "execution",
  263. endpoint: "https://must-not-cross-the-wire.example",
  264. },
  265. }).success,
  266. ).toBe(false);
  267. });
  268. it("rejects payload that does not match the command type", () => {
  269. const result = parseCommandEnvelope({
  270. commandId: "cmd-1",
  271. clientId: "client-1",
  272. sessionId: "s-1",
  273. type: "forkAssistant",
  274. payload: { wrongField: true },
  275. issuedAt: 1000,
  276. });
  277. expect(result.ok).toBe(false);
  278. });
  279. it("hard-cuts row commands to wire v3 target identity and epoch CAS", () => {
  280. expect(V4_WIRE_PROTOCOL_VERSION).toBe(3);
  281. expect(
  282. helloMessageSchema.safeParse({
  283. kind: "hello",
  284. protocolVersion: 2,
  285. connectionId: "connection-1",
  286. clientMode: "desktop-continuous",
  287. deliveryProfile: "continuous",
  288. serverTime: 1000,
  289. capabilities: {
  290. nativeDialogs: true,
  291. localTerminal: true,
  292. binaryFrames: true,
  293. compression: "none",
  294. },
  295. auth: {},
  296. }).success,
  297. ).toBe(false);
  298. const valid = parseCommandEnvelope({
  299. commandId: "cmd-edit-v3",
  300. clientId: "client-1",
  301. sessionId: "s-1",
  302. baseRevision: 7,
  303. baseLogEpoch: "epoch-7",
  304. type: "editUserQuery",
  305. payload: {
  306. target: { rowId: 12, entityId: "message-user-12" },
  307. newText: "edited",
  308. },
  309. issuedAt: 1000,
  310. });
  311. expect(valid.ok).toBe(true);
  312. for (const invalid of [
  313. {
  314. commandId: "cmd-edit-old-row",
  315. clientId: "client-1",
  316. sessionId: "s-1",
  317. baseRevision: 7,
  318. baseLogEpoch: "epoch-7",
  319. type: "editUserQuery",
  320. payload: { targetRowId: 12, newText: "edited" },
  321. issuedAt: 1000,
  322. },
  323. {
  324. commandId: "cmd-edit-no-epoch",
  325. clientId: "client-1",
  326. sessionId: "s-1",
  327. baseRevision: 7,
  328. type: "editUserQuery",
  329. payload: {
  330. target: { rowId: 12, entityId: "message-user-12" },
  331. newText: "edited",
  332. },
  333. issuedAt: 1000,
  334. },
  335. ]) {
  336. expect(parseCommandEnvelope(invalid).ok).toBe(false);
  337. }
  338. });
  339. it.each(["editUserQuery", "sendQueuedNow"] as const)(
  340. "%s accepts a refreshed Highspeed execution model for an explicit rerun",
  341. (type) => {
  342. const target = { rowId: 12, entityId: "message-user-12" };
  343. const highspeedMeta = {
  344. schemaVersion: 1 as const,
  345. cardId: "hsc-edit",
  346. taskId: "s-1",
  347. provider: "builtin:bigmodel-coding-plan",
  348. model: "GLM-5.3",
  349. issuedAt: 1_000,
  350. expiresAt: 60_000,
  351. };
  352. // 显式重跑会重新抽卡,因此 Selection 与执行材料必须能整体刷新;加速轮永远是
  353. // execution 作用域,不允许改写 Session Selection。
  354. const modelSelection = {
  355. providerId: "account:bigmodel-highspeed-card",
  356. modelId: "GLM-5.3",
  357. };
  358. const modelExecution = {
  359. selectionScope: "execution" as const,
  360. requestAuth: {
  361. apiKey: "card-jwt",
  362. headers: { "X-Highspeed-Card-ID": "hsc-edit" },
  363. },
  364. selectionFallback: {
  365. providerId: "account:bigmodel-highspeed-card",
  366. rules: [
  367. { reason: "highspeed_card_expired" as const, providerErrorCode: "3402" },
  368. { reason: "highspeed_request_failed" as const },
  369. ],
  370. // 退回目标随声明下发:重跑时也必须带上当时的会话原模型,CLI 不再依赖运行态常驻选择。
  371. target: { providerId: "account:bigmodel-team-coding-plan", modelId: "GLM-5.3" },
  372. },
  373. };
  374. const result = parseCommandEnvelope({
  375. commandId: `cmd-${type}`,
  376. clientId: "client-1",
  377. sessionId: "s-1",
  378. baseRevision: 7,
  379. baseLogEpoch: "epoch-7",
  380. type,
  381. payload:
  382. type === "editUserQuery"
  383. ? { target, newText: "edited", highspeedMeta, modelSelection, modelExecution }
  384. : { queueItemId: "queue-1", highspeedMeta, modelSelection, modelExecution },
  385. issuedAt: 1_000,
  386. });
  387. expect(result).toMatchObject({
  388. ok: true,
  389. envelope: { payload: { highspeedMeta, modelSelection, modelExecution } },
  390. });
  391. },
  392. );
  393. it.each(["editUserQuery", "sendQueuedNow"] as const)(
  394. "%s rejects modelExecution without the Selection it constrains",
  395. (type) => {
  396. const result = parseCommandEnvelope({
  397. commandId: `cmd-${type}-orphan-execution`,
  398. clientId: "client-1",
  399. sessionId: "s-1",
  400. baseRevision: 7,
  401. baseLogEpoch: "epoch-7",
  402. type,
  403. payload:
  404. type === "editUserQuery"
  405. ? {
  406. target: { rowId: 12, entityId: "message-user-12" },
  407. newText: "edited",
  408. modelExecution: { selectionScope: "execution" as const },
  409. }
  410. : {
  411. queueItemId: "queue-1",
  412. modelExecution: { selectionScope: "execution" as const },
  413. },
  414. issuedAt: 1_000,
  415. });
  416. expect(result.ok).toBe(false);
  417. },
  418. );
  419. it("allows createSession without firstInput (draft session, 2026-07-05 ruling)", () => {
  420. const result = parseCommandEnvelope({
  421. commandId: "cmd-2",
  422. clientId: "client-1",
  423. sessionId: null,
  424. type: "createSession",
  425. payload: { workspaceId: "ws-1" },
  426. issuedAt: 1000,
  427. });
  428. expect(result.ok).toBe(true);
  429. });
  430. it("parses an atomic Submission in createSession.firstInput", () => {
  431. const result = parseCommandEnvelope({
  432. commandId: "cmd-create-submission",
  433. clientId: "client-1",
  434. sessionId: null,
  435. type: "createSession",
  436. payload: {
  437. workspaceId: "ws-1",
  438. firstInput: {
  439. text: "hello",
  440. modelSelection: {
  441. providerId: "provider-a",
  442. modelId: "model-a",
  443. options: { reasoningLevel: "high" },
  444. },
  445. mode: "plan",
  446. },
  447. },
  448. issuedAt: 1000,
  449. });
  450. expect(result.ok).toBe(true);
  451. });
  452. it("parses createSession MCP runtime configuration", () => {
  453. const result = parseCommandEnvelope({
  454. commandId: "cmd-create-mcp",
  455. clientId: "client-1",
  456. sessionId: null,
  457. type: "createSession",
  458. payload: {
  459. workspaceId: "ws-1",
  460. mcpServers: [
  461. {
  462. name: "docs",
  463. command: "node",
  464. args: ["server.js"],
  465. env: [{ name: "TOKEN", value: "secret-ref" }],
  466. },
  467. ],
  468. },
  469. issuedAt: 1000,
  470. });
  471. expect(result.ok).toBe(true);
  472. if (result.ok) {
  473. expect(result.envelope.payload).toMatchObject({
  474. mcpServers: [{ name: "docs", command: "node" }],
  475. });
  476. }
  477. });
  478. it("preserves explicit side first input model selection and rejects malformed selection", () => {
  479. const command = {
  480. commandId: "side-model",
  481. clientId: "c",
  482. sessionId: "parent",
  483. type: "createSelectionSideSession",
  484. issuedAt: 1,
  485. };
  486. const modelSelection = {
  487. providerId: "account:bigmodel-start-plan",
  488. modelId: "glm-5",
  489. options: { reasoningLevel: "high" },
  490. };
  491. const result = parseCommandEnvelope({
  492. ...command,
  493. payload: { firstInput: { text: "hello", modelSelection } },
  494. });
  495. expect(result.ok).toBe(true);
  496. if (result.ok)
  497. expect(result.envelope.payload).toEqual({ firstInput: { text: "hello", modelSelection } });
  498. expect(
  499. parseCommandEnvelope({
  500. ...command,
  501. payload: { firstInput: { text: "hello", modelSelection: { providerId: "" } } },
  502. }).ok,
  503. ).toBe(false);
  504. });
  505. it("parses non-CAS createSelectionSideSession and its ACK result", () => {
  506. const result = parseCommandEnvelope({
  507. commandId: "cmd-selection-side-1",
  508. clientId: "client-1",
  509. sessionId: "parent-1",
  510. type: "createSelectionSideSession",
  511. payload: {},
  512. issuedAt: 1000,
  513. });
  514. expect(result.ok).toBe(true);
  515. expect(COMMANDS_REQUIRING_BASE_REVISION.has("createSelectionSideSession")).toBe(false);
  516. expect(
  517. commandAckSchema.parse({
  518. commandId: "cmd-selection-side-1",
  519. status: "accepted",
  520. revisionAtDecision: 7,
  521. result: {
  522. type: "createSelectionSideSession",
  523. sessionId: "child-1",
  524. },
  525. }).result,
  526. ).toEqual({ type: "createSelectionSideSession", sessionId: "child-1" });
  527. });
  528. it("keeps omitted createSession.config.mode absent so workspace default mode can win", () => {
  529. const result = parseCommandEnvelope({
  530. commandId: "cmd-create-config-no-mode",
  531. clientId: "client-1",
  532. sessionId: null,
  533. type: "createSession",
  534. payload: {
  535. workspaceId: "ws-1",
  536. config: {
  537. provider: "default-deepseek",
  538. model: "deepseek-v4-flash",
  539. thought: "max",
  540. followupMode: "queue",
  541. },
  542. },
  543. issuedAt: 1000,
  544. });
  545. expect(result.ok).toBe(true);
  546. if (result.ok) {
  547. expect(result.envelope.payload).toEqual({
  548. workspaceId: "ws-1",
  549. config: {
  550. provider: "default-deepseek",
  551. model: "deepseek-v4-flash",
  552. thought: "max",
  553. followupMode: "queue",
  554. },
  555. });
  556. }
  557. });
  558. it("普通 create/switch 命令不再保留 Host runtimeModel", () => {
  559. const runtimeModel = {
  560. revision: "model-runtime:test",
  561. generatedAt: 1,
  562. model: { providerId: "legacy", modelId: "model" },
  563. provider: {
  564. providerId: "legacy",
  565. kind: "anthropic",
  566. apiFormat: "anthropic-messages",
  567. baseURL: "https://example.com",
  568. models: [{ modelId: "model" }],
  569. },
  570. };
  571. const create = commandPayloadSchemas.createSession.parse({
  572. workspaceId: "ws-1",
  573. runtimeModel,
  574. });
  575. const change = commandPayloadSchemas.switchModelConfig.parse({
  576. provider: "legacy",
  577. model: "model",
  578. thought: "high",
  579. runtimeModel,
  580. });
  581. expect("runtimeModel" in create).toBe(false);
  582. expect("runtimeModel" in change).toBe(false);
  583. });
  584. it("keeps legacy rewind absent while allowing workspace-only applyFileRewind", () => {
  585. expect("rewind" in commandPayloadSchemas).toBe(false);
  586. const result = parseCommandEnvelope({
  587. commandId: "cmd-file-rewind-1",
  588. clientId: "client-1",
  589. sessionId: "s-1",
  590. baseRevision: 7,
  591. baseLogEpoch: "epoch-7",
  592. type: "applyFileRewind",
  593. payload: { target: { rowId: 12, entityId: "turn-12" } },
  594. issuedAt: 1000,
  595. });
  596. expect(result.ok).toBe(true);
  597. expect(COMMANDS_REQUIRING_BASE_REVISION.has("applyFileRewind")).toBe(true);
  598. });
  599. it("has no forkOf on createSession (P5)", () => {
  600. expect(
  601. commandPayloadSchemas.createSession.safeParse({
  602. workspaceId: "ws-1",
  603. forkOf: "s-0",
  604. }).success,
  605. // zod object 默认 strip 未知键——这里断言的是类型层没有 forkOf 定义
  606. ).toBe(true);
  607. const parsed = commandPayloadSchemas.createSession.parse({
  608. workspaceId: "ws-1",
  609. forkOf: "s-0",
  610. });
  611. expect("forkOf" in parsed).toBe(false);
  612. });
  613. it("CAS command set matches the spec table", () => {
  614. expect([...COMMANDS_REQUIRING_BASE_REVISION].sort()).toEqual(
  615. [
  616. "deleteQueueItem",
  617. "editQueueItem",
  618. "editUserQuery",
  619. "applyFileRewind",
  620. "forkAssistant",
  621. "pauseGoal",
  622. "reorderQueueItem",
  623. "resumeGoal",
  624. "retryTurn",
  625. "sendQueuedNow",
  626. "setAssistantFeedback",
  627. "setAutoDrain",
  628. "setFollowupMode",
  629. "switchCollaborationMode",
  630. "switchModelConfig",
  631. ].sort(),
  632. );
  633. // stop 永不 stale:不在 CAS 集合
  634. expect(COMMANDS_REQUIRING_BASE_REVISION.has("compact")).toBe(false);
  635. expect(COMMANDS_REQUIRING_BASE_REVISION.has("stop")).toBe(false);
  636. expect(COMMANDS_REQUIRING_BASE_REVISION.has("resolveInteraction")).toBe(false);
  637. // 完成态统计是同一 user message 的幂等后台补写,不能被 Renderer revision 漂移丢弃。
  638. expect(COMMANDS_REQUIRING_BASE_REVISION.has("setHighspeedMetrics")).toBe(false);
  639. });
  640. it("parses persisted Highspeed completion metrics", () => {
  641. const parsed = parseCommandEnvelope({
  642. commandId: "cmd-highspeed-metrics",
  643. clientId: "desktop-1",
  644. sessionId: "s-1",
  645. baseLogEpoch: "epoch-1",
  646. type: "setHighspeedMetrics",
  647. payload: {
  648. target: { rowId: 8, entityId: "user-1" },
  649. regularTps: 73,
  650. outputTokens: 120_000,
  651. durationMs: 881_000,
  652. highspeedTps: 90,
  653. savedDurationMs: 762_836,
  654. },
  655. issuedAt: 1000,
  656. });
  657. expect(parsed.ok).toBe(true);
  658. });
  659. // M5 additive:switchCollaborationMode——值域 = core CollaborationMode 可切换子集。
  660. it("parses switchCollaborationMode and rejects out-of-catalog mode", () => {
  661. const ok = parseCommandEnvelope({
  662. commandId: "cmd-mode-1",
  663. clientId: "client-1",
  664. sessionId: "s-1",
  665. baseRevision: 3,
  666. baseLogEpoch: "epoch-3",
  667. type: "switchCollaborationMode",
  668. payload: { mode: "plan" },
  669. issuedAt: 1000,
  670. });
  671. expect(ok.ok).toBe(true);
  672. const bad = parseCommandEnvelope({
  673. commandId: "cmd-mode-2",
  674. clientId: "client-1",
  675. sessionId: "s-1",
  676. type: "switchCollaborationMode",
  677. // auto 非用户可切换模式,不进命令面
  678. payload: { mode: "auto" },
  679. issuedAt: 1000,
  680. });
  681. expect(bad.ok).toBe(false);
  682. });
  683. // M5 ③-2 additive:resolveInteraction answer 的 action/content——elicitation
  684. // 回执收敛(多题答案/注解无损)。黄金断言:旧形态(仅 optionId/freeText)继续合法。
  685. it("parses resolveInteraction with additive action/content and keeps legacy answers valid", () => {
  686. const legacy = parseCommandEnvelope({
  687. commandId: "cmd-ri-1",
  688. clientId: "client-1",
  689. sessionId: "s-1",
  690. type: "resolveInteraction",
  691. payload: { interactionId: "req-1", answer: { optionId: "allowOnce" } },
  692. issuedAt: 1000,
  693. });
  694. expect(legacy.ok).toBe(true);
  695. const extended = parseCommandEnvelope({
  696. commandId: "cmd-ri-2",
  697. clientId: "client-1",
  698. sessionId: "s-1",
  699. type: "resolveInteraction",
  700. payload: {
  701. interactionId: "req-2",
  702. answer: {
  703. action: "accept",
  704. content: { answers: { "要哪种?": "B" }, annotations: {} },
  705. },
  706. },
  707. issuedAt: 1000,
  708. });
  709. expect(extended.ok).toBe(true);
  710. if (extended.ok) {
  711. expect(extended.envelope.payload).toEqual({
  712. interactionId: "req-2",
  713. answer: {
  714. action: "accept",
  715. content: { answers: { "要哪种?": "B" }, annotations: {} },
  716. },
  717. });
  718. }
  719. const badAction = parseCommandEnvelope({
  720. commandId: "cmd-ri-3",
  721. clientId: "client-1",
  722. sessionId: "s-1",
  723. type: "resolveInteraction",
  724. payload: { interactionId: "req-3", answer: { action: "maybe" } },
  725. issuedAt: 1000,
  726. });
  727. expect(badAction.ok).toBe(false);
  728. });
  729. it("keeps the shared freeText answer shape backward compatible", () => {
  730. expect(
  731. commandPayloadSchemas.resolveInteraction.safeParse({
  732. interactionId: "permission-1",
  733. answer: { optionId: "deny", freeText: "请改用只读方案" },
  734. }).success,
  735. ).toBe(true);
  736. expect(
  737. commandPayloadSchemas.resolveInteraction.safeParse({
  738. interactionId: "user-input-2",
  739. answer: { freeText: "x".repeat(4097) },
  740. }).success,
  741. ).toBe(true);
  742. });
  743. it("parses dedicated Workspace Hook review/toggle/revoke commands and rejects malformed targets", () => {
  744. const target = {
  745. sessionId: "s-1",
  746. taskId: "task-1",
  747. runId: "run-1",
  748. workspaceIdentity: "workspace:1",
  749. bundleDigest: "a".repeat(64),
  750. reviewFlowId: "flow-1",
  751. generation: 1,
  752. interactionId: "interaction-1",
  753. };
  754. for (const [type, payload] of [
  755. [
  756. "respondWorkspaceHookReview",
  757. {
  758. ...target,
  759. decision: { action: "trust_selected", reviewItemIds: ["item-1"] },
  760. },
  761. ],
  762. ["toggleWorkspaceHookReviewItem", { ...target, reviewItemId: "item-1", enabled: false }],
  763. ["revokeWorkspaceHookTrust", { ...target, reviewItemIds: ["item-1"] }],
  764. ] as const) {
  765. expect(
  766. parseCommandEnvelope({
  767. commandId: `cmd-${type}`,
  768. clientId: "client-1",
  769. sessionId: "s-1",
  770. type,
  771. payload,
  772. issuedAt: 1000,
  773. }).ok,
  774. ).toBe(true);
  775. }
  776. expect(
  777. parseCommandEnvelope({
  778. commandId: "cmd-revoke-current",
  779. clientId: "client-1",
  780. sessionId: "s-1",
  781. type: "revokeWorkspaceHookTrust",
  782. payload: {
  783. sessionId: "s-1",
  784. workspaceIdentity: "workspace:1",
  785. bundleDigest: "a".repeat(64),
  786. hookDeclarationDigests: ["b".repeat(64)],
  787. },
  788. issuedAt: 1000,
  789. }).ok,
  790. ).toBe(true);
  791. expect(
  792. parseCommandEnvelope({
  793. commandId: "cmd-hook-bad",
  794. clientId: "client-1",
  795. sessionId: "s-1",
  796. type: "respondWorkspaceHookReview",
  797. payload: {
  798. ...target,
  799. bundleDigest: "not-a-digest",
  800. decision: { action: "trust_selected", reviewItemIds: ["item-1"] },
  801. },
  802. issuedAt: 1000,
  803. }).ok,
  804. ).toBe(false);
  805. });
  806. it("validates ack statuses including noop (R-09)", () => {
  807. const ack = commandAckSchema.parse({
  808. commandId: "cmd-3",
  809. status: "noop",
  810. reasonCode: "proto.alreadyResolved",
  811. revisionAtDecision: 42,
  812. result: {
  813. type: "resolveInteraction",
  814. resolvedBy: { clientId: "other-client", optionId: "allow" },
  815. },
  816. });
  817. expect(ack.status).toBe("noop");
  818. });
  819. it("validates restart input disposition for delivery-aware recovery", () => {
  820. const ack = commandAckSchema.parse({
  821. commandId: "cmd-discarded-queue",
  822. status: "failed",
  823. reasonCode: "fault.command.inputDiscardedOnRestart",
  824. revisionAtDecision: 42,
  825. result: { type: "inputDisposition", delivery: "queue" },
  826. });
  827. expect(ack.result).toEqual({ type: "inputDisposition", delivery: "queue" });
  828. });
  829. it("validates applyFileRewind ack result", () => {
  830. const ack = commandAckSchema.parse({
  831. commandId: "cmd-file-rewind-2",
  832. status: "accepted",
  833. revisionAtDecision: 8,
  834. result: {
  835. type: "applyFileRewind",
  836. applied: true,
  837. response: "Rewound 1 file from summary checkpoints.",
  838. preview: {
  839. canApply: true,
  840. safeFiles: [
  841. {
  842. path: "/work/src/demo.ts",
  843. action: "restore",
  844. operationCount: 1,
  845. toolNames: ["Write"],
  846. },
  847. ],
  848. unsafeFiles: [],
  849. ignoredFiles: [],
  850. },
  851. },
  852. });
  853. expect(ack.result?.type).toBe("applyFileRewind");
  854. });
  855. it("validates edit ACK disposition and destination session", () => {
  856. const rewind = commandAckSchema.parse({
  857. commandId: "cmd-edit-rewind",
  858. status: "accepted",
  859. revisionAtDecision: 8,
  860. result: {
  861. type: "editUserQuery",
  862. disposition: "rewind",
  863. sessionId: "s-1",
  864. },
  865. });
  866. const fork = commandAckSchema.parse({
  867. commandId: "cmd-edit-fork",
  868. status: "accepted",
  869. revisionAtDecision: 8,
  870. result: {
  871. type: "editUserQuery",
  872. disposition: "fork",
  873. sessionId: "s-child",
  874. },
  875. });
  876. expect(rewind.result).toEqual({
  877. type: "editUserQuery",
  878. disposition: "rewind",
  879. sessionId: "s-1",
  880. });
  881. expect(fork.result).toEqual({
  882. type: "editUserQuery",
  883. disposition: "fork",
  884. sessionId: "s-child",
  885. });
  886. });
  887. it("parses a startSavedWorkflow payload and rejects bad shapes", () => {
  888. // 直接启动命令:不携 baseRevision,与 cancel / resume 同类。
  889. expect(
  890. parseCommandEnvelope({
  891. commandId: "018f0000-0000-7000-8000-0000000000aa",
  892. clientId: "client-1",
  893. sessionId: "s-empty",
  894. type: "startSavedWorkflow",
  895. payload: { name: "deep-research", scope: "global", args: { topic: "x", depth: 2 } },
  896. issuedAt: 1000,
  897. }).ok,
  898. ).toBe(true);
  899. // scope 可选:项目档缺省不传。
  900. expect(commandPayloadSchemas.startSavedWorkflow.parse({ name: "cleanup" })).toEqual({
  901. name: "cleanup",
  902. });
  903. // 空名字被拒(invalid_name 属于运行时诊断,但 schema 先挡空串)。
  904. expect(commandPayloadSchemas.startSavedWorkflow.safeParse({ name: "" }).success).toBe(false);
  905. // scope 只认 project / global。
  906. expect(
  907. commandPayloadSchemas.startSavedWorkflow.safeParse({ name: "x", scope: "team" }).success,
  908. ).toBe(false);
  909. });
  910. it("parses the startSavedWorkflow accepted result branch", () => {
  911. const ack = commandAckSchema.parse({
  912. commandId: "cmd-start-saved",
  913. status: "accepted",
  914. revisionAtDecision: 0,
  915. result: {
  916. type: "startSavedWorkflow",
  917. runId: "run-123",
  918. toolCallId: "launch-abc",
  919. },
  920. });
  921. expect(ack.result).toEqual({
  922. type: "startSavedWorkflow",
  923. runId: "run-123",
  924. toolCallId: "launch-abc",
  925. });
  926. // runId / toolCallId 必带且非空。
  927. expect(
  928. commandResultSchema.safeParse({ type: "startSavedWorkflow", runId: "", toolCallId: "x" })
  929. .success,
  930. ).toBe(false);
  931. });
  932. it("exposes the saved-workflow rejection vocabulary and fault prefix", () => {
  933. expect(SAVED_WORKFLOW_START_REJECTED_FAULT_PREFIX).toBe(
  934. "fault.command.savedWorkflowStartRejected.",
  935. );
  936. expect(savedWorkflowStartRejectionReasonSchema.options).toEqual([
  937. "invalid_name",
  938. "not_found",
  939. "invalid_args",
  940. "compile_failed",
  941. "session_busy",
  942. "start_failed",
  943. ]);
  944. // 前缀 + reason 拼成完整 fault code;bootstrap 铸造、ui 前缀匹配。
  945. expect(`${SAVED_WORKFLOW_START_REJECTED_FAULT_PREFIX}not_found`).toBe(
  946. "fault.command.savedWorkflowStartRejected.not_found",
  947. );
  948. });
  949. // 「配置」弹层的命令(docs/dynamic-workflow/launch.md「Changing a run's settings from the GUI」)。
  950. it("parses amendWorkflowRunSettings payloads with the omit / null / value tri-state", () => {
  951. const schema = commandPayloadSchemas.amendWorkflowRunSettings;
  952. // 不携 baseRevision,与 cancel / resume 同类。
  953. expect(
  954. parseCommandEnvelope({
  955. commandId: "018f0000-0000-7000-8000-0000000000ab",
  956. clientId: "client-1",
  957. sessionId: "s-1",
  958. type: "amendWorkflowRunSettings",
  959. payload: { workId: "run-a", subagentModel: "zhipu/glm-5.3-flash$high", maxConcurrency: 4 },
  960. issuedAt: 1000,
  961. }).ok,
  962. ).toBe(true);
  963. expect(schema.parse({ workId: "run-a" })).toEqual({ workId: "run-a" });
  964. expect(schema.parse({ workId: "run-a", subagentModel: null, maxConcurrency: null })).toEqual({
  965. workId: "run-a",
  966. subagentModel: null,
  967. maxConcurrency: null,
  968. });
  969. expect(schema.safeParse({ workId: "run-a", maxConcurrency: 0 }).success).toBe(false);
  970. expect(schema.safeParse({ workId: "run-a", maxConcurrency: 2.5 }).success).toBe(false);
  971. expect(schema.safeParse({ workId: "run-a", subagentModel: "" }).success).toBe(false);
  972. });
  973. it("parses the amendWorkflowRunSettings accepted result and exposes its rejection vocabulary", () => {
  974. const ack = commandAckSchema.parse({
  975. commandId: "cmd-settings",
  976. status: "accepted",
  977. revisionAtDecision: 0,
  978. result: {
  979. type: "amendWorkflowRunSettings",
  980. runId: "run-b",
  981. toolCallId: "settings-abc",
  982. supersededRunId: "run-a",
  983. },
  984. });
  985. expect(ack.result).toEqual({
  986. type: "amendWorkflowRunSettings",
  987. runId: "run-b",
  988. toolCallId: "settings-abc",
  989. supersededRunId: "run-a",
  990. });
  991. expect(
  992. commandResultSchema.safeParse({
  993. type: "amendWorkflowRunSettings",
  994. runId: "run-b",
  995. toolCallId: "",
  996. }).success,
  997. ).toBe(false);
  998. expect(workflowRunSettingsRejectionReasonSchema.options).toEqual([
  999. "not_found",
  1000. "not_configurable",
  1001. "unchanged",
  1002. "script_missing",
  1003. "model_unavailable",
  1004. "compile_failed",
  1005. "missing_boundaries",
  1006. "start_failed",
  1007. ]);
  1008. expect(`${WORKFLOW_RUN_SETTINGS_REJECTED_FAULT_PREFIX}unchanged`).toBe(
  1009. "fault.command.workflowRunSettingsRejected.unchanged",
  1010. );
  1011. });
  1012. });