zcodeProtocolV4Command.test.ts 30 KB

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