zcodeProtocolV4WorkspaceHookReview.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. V4_WIRE_PROTOCOL_VERSION,
  4. clientHelloSchema,
  5. commandPayloadSchemas,
  6. conversationDeltaSchema,
  7. conversationSnapshotSchema,
  8. helloMessageSchema,
  9. hookExecutionDescriptorSchema,
  10. hostSupportsWorkspaceHookReview,
  11. hostSupportsWorkflowRunDeltas,
  12. clientSupportsWorkspaceHookReview,
  13. clientSupportsWorkflowRunDeltas,
  14. v4ConversationSubscribeParamsSchema,
  15. pendingInteractionSchema,
  16. workspaceHookReviewDecisionSchema,
  17. workspaceHookReviewRequestPayloadSchema,
  18. } from "../src/zcode-protocol-v4/index.js";
  19. import {
  20. taskOwnerCommandDeliverySchema,
  21. taskOwnerCommandRequestSchema,
  22. } from "../src/task-realtime-core.js";
  23. const DIGEST = "a".repeat(64);
  24. function request() {
  25. return workspaceHookReviewRequestPayloadSchema.parse({
  26. kind: "workspaceHookReview",
  27. reviewFlowId: "flow-1",
  28. generation: 2,
  29. interactionId: "interaction-2",
  30. sessionId: "session-1",
  31. taskId: "task-1",
  32. runId: "run-1",
  33. workspaceIdentity: "remote:ssh:host:/workspace",
  34. workspaceLabel: "workspace",
  35. remoteSessionId: "remote-1",
  36. bundleDigest: DIGEST,
  37. createdAt: 1,
  38. deadlineAt: 600_001,
  39. sourceFiles: [
  40. { path: "/workspace/.zcode/config.json", displayPath: ".zcode/config.json", editable: true },
  41. ],
  42. summary: { eventCount: 1, hookCount: 1, pendingCount: 1 },
  43. items: [
  44. {
  45. reviewItemId: "item-1",
  46. event: "SessionStart",
  47. matcher: "resume",
  48. type: "command",
  49. displayName: "SessionStart hook",
  50. displayCommand: "./scripts/resume.sh",
  51. sourcePath: ".zcode/config.json",
  52. resolvedTimeoutMs: 30_000,
  53. resolvedMaxOutputBytes: 32_768,
  54. executionMode: "background",
  55. configuredEnabled: true,
  56. editable: true,
  57. trustState: "pending_trust",
  58. },
  59. ],
  60. warningCode: "workspace_hooks_execute_code",
  61. });
  62. }
  63. function snapshotWithReview() {
  64. return {
  65. protocolVersion: 1,
  66. sessionId: "session-1",
  67. logEpoch: "epoch-1",
  68. seq: 1,
  69. revision: 1,
  70. control: {
  71. phase: "running",
  72. sessionEnded: false,
  73. canStop: true,
  74. stopState: "stoppable",
  75. stopTargetKind: "assistant",
  76. activeWorks: [{ kind: "primaryTurn", startedAt: 1 }],
  77. lastError: null,
  78. apiRetry: null,
  79. },
  80. availability: {
  81. fork: { allowed: true },
  82. compact: { allowed: true },
  83. switchModelConfig: { allowed: true },
  84. setFollowupMode: { allowed: true },
  85. queueEdit: { allowed: true },
  86. sendQueuedNow: { allowed: true },
  87. pauseGoal: { allowed: false, reasonCode: "guard.noGoal" },
  88. resumeGoal: { allowed: false, reasonCode: "guard.noGoal" },
  89. },
  90. inputRouting: { mode: "enqueue" },
  91. meta: { title: "workspace", titleSource: "custom" },
  92. config: {
  93. provider: "glm",
  94. model: "glm-5",
  95. thought: "medium",
  96. thoughtLevels: [],
  97. followupMode: "queue",
  98. mode: "build",
  99. },
  100. modelTransition: null,
  101. usage: {
  102. contextWindow: { usedTokens: 0, maxTokens: 200_000, autoCompactThresholdTokens: null },
  103. cumulative: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 },
  104. },
  105. queue: { items: [], autoDrain: true },
  106. pendingInteractions: [
  107. {
  108. interactionId: "interaction-2",
  109. kind: "workspaceHookReview",
  110. anchorRowId: null,
  111. createdAt: 1,
  112. payload: request(),
  113. },
  114. ],
  115. pendingCommands: [],
  116. backgroundWorks: [],
  117. goal: null,
  118. plan: null,
  119. rows: { window: [], totalCount: 0, firstRowId: null },
  120. };
  121. }
  122. // workflowRunDeltas 能力位(docs/v4-refactor/10-protocol-spec §4.5):与 workspaceHookReview 同族的
  123. // fail-closed 握手,钉在同一处是因为踩坑点也是同一个——clientHello.capabilities 是 .strict() 的。
  124. describe("workflowRunDeltas capability handshake", () => {
  125. const hello = (capabilities: Record<string, unknown>) =>
  126. helloMessageSchema.parse({
  127. kind: "hello",
  128. protocolVersion: V4_WIRE_PROTOCOL_VERSION,
  129. connectionId: "connection-1",
  130. clientMode: "desktop-continuous",
  131. deliveryProfile: "continuous",
  132. serverTime: 1,
  133. capabilities: {
  134. nativeDialogs: true,
  135. localTerminal: true,
  136. binaryFrames: false,
  137. compression: "none",
  138. ...capabilities,
  139. },
  140. auth: {},
  141. });
  142. it("Host 侧缺失即 false,显式 true 才算有", () => {
  143. expect(hostSupportsWorkflowRunDeltas(hello({}).capabilities)).toBe(false);
  144. expect(hostSupportsWorkflowRunDeltas(hello({ workflowRunDeltas: false }).capabilities)).toBe(
  145. false,
  146. );
  147. expect(hostSupportsWorkflowRunDeltas(hello({ workflowRunDeltas: true }).capabilities)).toBe(
  148. true,
  149. );
  150. });
  151. it("Client 侧同样 fail closed;capabilities 整个缺席也只是 false", () => {
  152. const clientHello = (capabilities?: Record<string, unknown>) =>
  153. clientHelloSchema.parse({
  154. kind: "clientHello",
  155. protocolVersion: V4_WIRE_PROTOCOL_VERSION,
  156. clientId: "client-1",
  157. appVersion: "test",
  158. ...(capabilities === undefined ? {} : { capabilities }),
  159. });
  160. expect(clientSupportsWorkflowRunDeltas(clientHello())).toBe(false);
  161. expect(clientSupportsWorkflowRunDeltas(clientHello({ workspaceHookReviewUi: true }))).toBe(
  162. false,
  163. );
  164. expect(clientSupportsWorkflowRunDeltas(clientHello({ workflowRunDeltas: true }))).toBe(true);
  165. // 两个能力位互不干扰(同一个 strict 对象里的两个可选键)。
  166. expect(
  167. clientSupportsWorkspaceHookReview(
  168. clientHello({ workspaceHookReviewUi: true, workflowRunDeltas: true }),
  169. ),
  170. ).toBe(true);
  171. });
  172. it("clientHello.capabilities 是 .strict():这正是「Host 没广播就不许声明」的由来", () => {
  173. // 老 Host 的 schema 里没有 workflowRunDeltas 这个键,客户端贸然带上会让**整条 clientHello**
  174. // 解析失败、连接握不上手——不是少一个键那么轻。这条断言用一个假想的未来键复现那个形状。
  175. expect(
  176. clientHelloSchema.safeParse({
  177. kind: "clientHello",
  178. protocolVersion: V4_WIRE_PROTOCOL_VERSION,
  179. clientId: "client-1",
  180. appVersion: "test",
  181. capabilities: { workflowRunDeltas: true, someFutureCapability: true },
  182. }).success,
  183. ).toBe(false);
  184. });
  185. it("subscribe 参数带该位(由可信 host 从连接的 clientHello 注入,UI 侧选不了)", () => {
  186. const params = v4ConversationSubscribeParamsSchema.parse({
  187. topic: "conversation/session-1",
  188. connectionId: "connection-1",
  189. clientMode: "desktop-continuous",
  190. workflowRunDeltas: true,
  191. });
  192. expect(params.workflowRunDeltas).toBe(true);
  193. // 缺席 = 按旧消费者处理(整键 patch + 旧界裁剪),不是解析失败。
  194. expect(
  195. v4ConversationSubscribeParamsSchema.parse({
  196. topic: "conversation/session-1",
  197. connectionId: "connection-1",
  198. clientMode: "desktop-continuous",
  199. }).workflowRunDeltas,
  200. ).toBeUndefined();
  201. });
  202. });
  203. describe("workspaceHookReview protocol contracts", () => {
  204. it("Host/Client capabilities 对缺失值 fail closed,capable attachment 显式声明", () => {
  205. const hello = helloMessageSchema.parse({
  206. kind: "hello",
  207. protocolVersion: V4_WIRE_PROTOCOL_VERSION,
  208. connectionId: "connection-1",
  209. clientMode: "desktop-continuous",
  210. deliveryProfile: "continuous",
  211. serverTime: 1,
  212. capabilities: {
  213. nativeDialogs: true,
  214. localTerminal: true,
  215. binaryFrames: false,
  216. compression: "none",
  217. },
  218. auth: {},
  219. });
  220. expect(hostSupportsWorkspaceHookReview(hello.capabilities)).toBe(false);
  221. expect(
  222. hostSupportsWorkspaceHookReview({ ...hello.capabilities, workspaceHookReview: true }),
  223. ).toBe(true);
  224. expect(
  225. clientSupportsWorkspaceHookReview(
  226. clientHelloSchema.parse({
  227. kind: "clientHello",
  228. protocolVersion: V4_WIRE_PROTOCOL_VERSION,
  229. clientId: "client-1",
  230. appVersion: "test",
  231. }),
  232. ),
  233. ).toBe(false);
  234. expect(
  235. clientSupportsWorkspaceHookReview(
  236. clientHelloSchema.parse({
  237. kind: "clientHello",
  238. protocolVersion: V4_WIRE_PROTOCOL_VERSION,
  239. clientId: "client-2",
  240. appVersion: "test",
  241. capabilities: { workspaceHookReviewUi: true },
  242. }),
  243. ),
  244. ).toBe(true);
  245. });
  246. it("project Hook lifecycle descriptor 对客户端可见", () => {
  247. expect(
  248. hookExecutionDescriptorSchema.safeParse({
  249. clientVisible: true,
  250. sourceKind: "project",
  251. sourcePath: "/workspace/.zcode/config.json",
  252. executionType: "command",
  253. executionMode: "foreground",
  254. commandDisplay: "./scripts/start.sh",
  255. timeoutMs: 30_000,
  256. }).success,
  257. ).toBe(true);
  258. });
  259. it("workspaceHookReview 独立于 permission/userInput 且永不携带 autoResolution", () => {
  260. const interaction = pendingInteractionSchema.parse({
  261. interactionId: "interaction-2",
  262. kind: "workspaceHookReview",
  263. anchorRowId: null,
  264. createdAt: 1,
  265. payload: request(),
  266. });
  267. expect(interaction.kind).toBe("workspaceHookReview");
  268. expect(
  269. pendingInteractionSchema.safeParse({
  270. ...interaction,
  271. interactionId: "forged-interaction",
  272. }).success,
  273. ).toBe(false);
  274. expect(
  275. pendingInteractionSchema.safeParse({
  276. ...interaction,
  277. autoResolution: {
  278. state: "visibleCountdown",
  279. startedAt: 1,
  280. visibleAt: 2,
  281. deadlineAt: 3,
  282. },
  283. }).success,
  284. ).toBe(false);
  285. });
  286. it("Desktop continuous delta 与 mobile replayable snapshot 使用同一权威 projection", () => {
  287. const snapshot = conversationSnapshotSchema.parse(snapshotWithReview());
  288. expect(snapshot.pendingInteractions[0]?.payload.kind).toBe("workspaceHookReview");
  289. expect(
  290. conversationDeltaSchema.safeParse({
  291. op: "state.updated",
  292. patch: { pendingInteractions: snapshot.pendingInteractions },
  293. }).success,
  294. ).toBe(true);
  295. });
  296. it("decision schema 只允许精确持久信任,不再接受临时授权或批量/阻断动作", () => {
  297. expect(
  298. workspaceHookReviewDecisionSchema.safeParse({
  299. action: "trust_selected",
  300. reviewItemIds: ["item-1"],
  301. }).success,
  302. ).toBe(true);
  303. expect(
  304. workspaceHookReviewDecisionSchema.safeParse({
  305. action: "trust_selected",
  306. reviewItemIds: [],
  307. }).success,
  308. ).toBe(false);
  309. expect(
  310. workspaceHookReviewDecisionSchema.safeParse({
  311. action: "trust_selected",
  312. reviewItemIds: ["item-1", "item-1"],
  313. }).success,
  314. ).toBe(false);
  315. for (const legacyDecision of [
  316. { action: "trust_all" },
  317. { action: "allow_once" },
  318. { action: "allow_once", reviewItemIds: ["item-1"] },
  319. { action: "keep_blocked" },
  320. ]) {
  321. expect(
  322. workspaceHookReviewDecisionSchema.safeParse(legacyDecision).success,
  323. `${legacyDecision.action} 应已从 Workspace Hook 协议移除`,
  324. ).toBe(false);
  325. }
  326. });
  327. it("mobile replayable response 只能通过现有 owner/lease/stale-run command envelope", () => {
  328. const ownerRouteCommand = {
  329. commandRequestId: "owner-command-1",
  330. type: "respond_workspace_hook_review",
  331. workspacePath: "/workspace",
  332. workspaceIdentity: "remote:ssh:host:/workspace",
  333. workspaceKey: "remote:ssh:host:/workspace",
  334. remoteSessionId: "remote-1",
  335. taskId: "task-1",
  336. runId: "run-1",
  337. sessionId: "session-1",
  338. bundleDigest: DIGEST,
  339. reviewFlowId: "flow-1",
  340. generation: 2,
  341. interactionId: "interaction-2",
  342. decision: { action: "trust_selected", reviewItemIds: ["item-1"] },
  343. };
  344. expect(taskOwnerCommandRequestSchema.safeParse(ownerRouteCommand).success).toBe(true);
  345. expect(
  346. taskOwnerCommandDeliverySchema.safeParse({
  347. ...ownerRouteCommand,
  348. requesterHostId: "host-mobile-attachment",
  349. }).success,
  350. ).toBe(true);
  351. expect(
  352. taskOwnerCommandRequestSchema.safeParse({
  353. ...ownerRouteCommand,
  354. workspaceKey: "/workspace",
  355. }).success,
  356. ).toBe(false);
  357. });
  358. // —— 软门禁(Soft Gate) S1 契约测试 ——
  359. it("snapshot 旧数据(无 workspaceHookAdmission 字段)解析得 null", () => {
  360. const raw = snapshotWithReview();
  361. // 模拟旧发送端:不带 workspaceHookAdmission 字段
  362. const parsed = conversationSnapshotSchema.parse(raw);
  363. expect(parsed.workspaceHookAdmission).toBeNull();
  364. });
  365. it("snapshot 带 workspaceHookAdmission 字段解析通过", () => {
  366. const raw = {
  367. ...snapshotWithReview(),
  368. workspaceHookAdmission: {
  369. pendingCount: 2,
  370. bundleDigest: DIGEST,
  371. workspaceIdentity: "remote:ssh:host:/workspace",
  372. },
  373. };
  374. const parsed = conversationSnapshotSchema.parse(raw);
  375. expect(parsed.workspaceHookAdmission).toEqual({
  376. pendingCount: 2,
  377. bundleDigest: DIGEST,
  378. workspaceIdentity: "remote:ssh:host:/workspace",
  379. });
  380. });
  381. it("workspaceHookAdmission 不带 workspaceIdentity 也可解析", () => {
  382. const raw = {
  383. ...snapshotWithReview(),
  384. workspaceHookAdmission: {
  385. pendingCount: 1,
  386. bundleDigest: DIGEST,
  387. },
  388. };
  389. const parsed = conversationSnapshotSchema.parse(raw);
  390. expect(parsed.workspaceHookAdmission).toEqual({
  391. pendingCount: 1,
  392. bundleDigest: DIGEST,
  393. });
  394. });
  395. it("workspaceHookAdmission.pendingCount 不允许负数", () => {
  396. const raw = {
  397. ...snapshotWithReview(),
  398. workspaceHookAdmission: {
  399. pendingCount: -1,
  400. bundleDigest: DIGEST,
  401. },
  402. };
  403. expect(conversationSnapshotSchema.safeParse(raw).success).toBe(false);
  404. });
  405. it("requestWorkspaceHookReview 命令 schema 校验通过(valid target)", () => {
  406. const payload = commandPayloadSchemas.requestWorkspaceHookReview.parse({
  407. sessionId: "session-1",
  408. workspaceIdentity: "remote:ssh:host:/workspace",
  409. bundleDigest: DIGEST,
  410. });
  411. expect(payload).toEqual({
  412. sessionId: "session-1",
  413. workspaceIdentity: "remote:ssh:host:/workspace",
  414. bundleDigest: DIGEST,
  415. });
  416. });
  417. it("requestWorkspaceHookReview 命令 schema 支持 remoteSessionId", () => {
  418. const payload = commandPayloadSchemas.requestWorkspaceHookReview.parse({
  419. sessionId: "session-1",
  420. remoteSessionId: "remote-1",
  421. workspaceIdentity: "remote:ssh:host:/workspace",
  422. bundleDigest: DIGEST,
  423. });
  424. expect(payload.remoteSessionId).toBe("remote-1");
  425. });
  426. it("requestWorkspaceHookReview 命令 schema 拒绝空 sessionId", () => {
  427. expect(
  428. commandPayloadSchemas.requestWorkspaceHookReview.safeParse({
  429. sessionId: "",
  430. workspaceIdentity: "remote:ssh:host:/workspace",
  431. bundleDigest: DIGEST,
  432. }).success,
  433. ).toBe(false);
  434. });
  435. it("requestWorkspaceHookReview 命令 schema 拒绝非 sha256 bundleDigest", () => {
  436. expect(
  437. commandPayloadSchemas.requestWorkspaceHookReview.safeParse({
  438. sessionId: "session-1",
  439. workspaceIdentity: "remote:ssh:host:/workspace",
  440. bundleDigest: "not-a-digest",
  441. }).success,
  442. ).toBe(false);
  443. });
  444. it("requestWorkspaceHookReview 命令 schema 拒绝多余字段(strict)", () => {
  445. expect(
  446. commandPayloadSchemas.requestWorkspaceHookReview.safeParse({
  447. sessionId: "session-1",
  448. workspaceIdentity: "remote:ssh:host:/workspace",
  449. bundleDigest: DIGEST,
  450. reviewFlowId: "flow-1",
  451. }).success,
  452. ).toBe(false);
  453. });
  454. });