resume-workflow-run-tool.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. RESUME_WORKFLOW_RUN_TOOL_NAME,
  4. ResumeWorkflowRunOutputSchema,
  5. type DynamicWorkflowRunPort,
  6. type DynamicWorkflowRunResumeResult,
  7. } from "@zcode/contracts";
  8. import { PermissionService } from "../src/permission/service.js";
  9. import { resolveRuntimePermissionCapability } from "../src/tool/executor/permission-capability.js";
  10. import { registerBuiltInTools } from "../src/tool/handlers/index.js";
  11. import { resumeWorkflowRunToolEntry } from "../src/tool/handlers/resume-workflow-run.js";
  12. import { createToolRegistry } from "../src/tool/registry.js";
  13. import { expectV2CommonContract } from "./tool-contract-assertions.js";
  14. import type { ToolExecutionContext, ToolHandlerFailure } from "../src/tool/types.js";
  15. /**
  16. * 只实现 `resume` 的桩端口;其余成员被触达即说明接线跑偏。成功/失败形态由参数决定,
  17. * 恢复的 runId 与请求的 run_id 不同时也按端口返回值透传(端口是身份权威)。
  18. */
  19. function stubResumePort(
  20. resume: (runId: string) => Promise<DynamicWorkflowRunResumeResult>,
  21. ): DynamicWorkflowRunPort {
  22. const unreachable = (name: string) => () => {
  23. throw new Error(`stubResumePort.${name} 不应被 ResumeWorkflowRun handler 触及`);
  24. };
  25. return {
  26. submit: unreachable("submit"),
  27. getTask: unreachable("getTask"),
  28. waitForTask: unreachable("waitForTask"),
  29. cancel: unreachable("cancel"),
  30. listEvents: unreachable("listEvents"),
  31. listRuns: unreachable("listRuns"),
  32. getRunDetail: unreachable("getRunDetail"),
  33. resume,
  34. } as unknown as DynamicWorkflowRunPort;
  35. }
  36. function contextWith(port?: DynamicWorkflowRunPort): ToolExecutionContext {
  37. return {
  38. abortSignal: new AbortController().signal,
  39. sessionId: "sess_resume_run" as never,
  40. toolCallId: "toolu_resume_run",
  41. traceId: "trace_resume_run" as never,
  42. workingDirectory: "/workspace/project",
  43. workspaceRoot: "/workspace/project",
  44. ...(port === undefined ? {} : { dynamicWorkflowRunPort: port }),
  45. } as ToolExecutionContext;
  46. }
  47. async function call(
  48. runId: string,
  49. port?: DynamicWorkflowRunPort,
  50. ): Promise<Record<string, unknown>> {
  51. return (await resumeWorkflowRunToolEntry.handler({ run_id: runId }, contextWith(port))) as Record<
  52. string,
  53. unknown
  54. >;
  55. }
  56. function asFailure(output: unknown): ToolHandlerFailure {
  57. const failure = output as ToolHandlerFailure;
  58. expect(failure.result).toBe(false);
  59. return failure;
  60. }
  61. describe("ResumeWorkflowRun handler — capability", () => {
  62. // 「端口缺席」(journal 不可用 → run service 整个不构造)与「端口在场但方法缺席」
  63. // (stub 不带 resume)对模型是同一件事:本会话没有这个能力。
  64. it("returns the same business failure for an absent port and an absent method", async () => {
  65. const portWithoutMethod = {
  66. async submit() {
  67. throw new Error("unreachable");
  68. },
  69. } as unknown as DynamicWorkflowRunPort;
  70. const withoutPort = asFailure(await call("dwfrun-x"));
  71. const withoutMethod = asFailure(await call("dwfrun-x", portWithoutMethod));
  72. expect(withoutPort.message).toContain("workflow_resume_unavailable");
  73. expect(withoutMethod).toEqual(withoutPort);
  74. });
  75. });
  76. describe("ResumeWorkflowRun handler — success", () => {
  77. it("passes run_id to port.resume and returns the backgrounded shape", async () => {
  78. const resumed: string[] = [];
  79. const output = await call(
  80. "dwfrun-1",
  81. stubResumePort(async (runId) => {
  82. resumed.push(runId);
  83. return { ok: true, runId };
  84. }),
  85. );
  86. expect(resumed).toEqual(["dwfrun-1"]);
  87. // runId ≡ taskId ≡ workId:backgroundTaskId 就是 runId,三条路径共用一个键。
  88. expect(output.backgroundTaskId).toBe("dwfrun-1");
  89. expect(output.status).toBe("backgrounded");
  90. expect(output.ok).toBe(true);
  91. expect(ResumeWorkflowRunOutputSchema.parse(output)).toEqual({
  92. ok: true,
  93. runId: "dwfrun-1",
  94. response: output.response,
  95. status: "backgrounded",
  96. backgroundTaskId: "dwfrun-1",
  97. });
  98. });
  99. // 异步引导(照 CreateWorkflow 的 backgrounded 文案):模型拿到输出后不得立刻 TaskOutput
  100. // 阻塞等待或轮询——桌面实测过它会把异步 run 变成同步等待。钉关键词,不钉逐字。
  101. it("steers the model away from polling and towards the completion notification", async () => {
  102. const output = await call(
  103. "dwfrun-1",
  104. stubResumePort(async () => ({ ok: true, runId: "dwfrun-1" })),
  105. );
  106. const response = String(output.response);
  107. expect(response).toContain("dwfrun-1");
  108. expect(response).toMatch(/background/i);
  109. expect(response).toMatch(/notified/i);
  110. expect(response).toMatch(/do not wait/i);
  111. expect(response).toContain("TaskOutput");
  112. });
  113. });
  114. describe("ResumeWorkflowRun handler — structured failures", () => {
  115. const REASONS = [
  116. "not_found",
  117. "not_resumable",
  118. "already_running",
  119. "script_missing",
  120. "script_mismatch",
  121. "compile_failed",
  122. ] as const;
  123. it.each(REASONS)("maps port reason %s to a prefixed, actionable failure", async (reason) => {
  124. const failure = asFailure(
  125. await call(
  126. "dwfrun-1",
  127. stubResumePort(async () => ({ ok: false, reason })),
  128. ),
  129. );
  130. // 判别键是 message 前缀(errorCode 数值不进模型,executor 投影成 code:"N" 字符串)。
  131. // not_found 复用内省工具的 run_not_found 键(同键同码)。
  132. const expectedPrefix =
  133. reason === "not_found" ? "run_not_found" : `workflow_run_${reason}`;
  134. expect(failure.message.startsWith(`${expectedPrefix}:`)).toBe(true);
  135. // 可操作性:失败要说清下一步(not_found 指向 ListWorkflowRuns,其余各自说清因由)。
  136. expect(failure.message.length).toBeGreaterThan(expectedPrefix.length + 1);
  137. });
  138. it("compile_failed 指向 AmendWorkflow 并附上端口的诊断", async () => {
  139. const failure = asFailure(
  140. await call(
  141. "dwfrun-1",
  142. stubResumePort(async () => ({
  143. ok: false,
  144. reason: "compile_failed",
  145. message: "L3:C1 Property 'askWithOldFacade' does not exist",
  146. })),
  147. ),
  148. );
  149. expect(failure.message.startsWith("workflow_run_compile_failed:")).toBe(true);
  150. expect(failure.message).toContain("AmendWorkflow");
  151. expect(failure.message).toContain("askWithOldFacade");
  152. });
  153. it("keeps not_found key and code identical to the introspection tool's failure", async () => {
  154. const failure = asFailure(
  155. await call(
  156. "dwfrun-nope",
  157. stubResumePort(async () => ({ ok: false, reason: "not_found" })),
  158. ),
  159. );
  160. expect(failure.message).toContain("dwfrun-nope");
  161. expect(failure.message).toContain("ListWorkflowRuns");
  162. });
  163. });
  164. describe("ResumeWorkflowRun model content", () => {
  165. it("renders the response text for a valid output", () => {
  166. const content = String(
  167. resumeWorkflowRunToolEntry.formatModelContent?.({
  168. ok: true,
  169. runId: "dwfrun-1",
  170. response: "resumed in the background",
  171. status: "backgrounded",
  172. backgroundTaskId: "dwfrun-1",
  173. }),
  174. );
  175. expect(content).toContain("resumed in the background");
  176. });
  177. it("reports an invalid result instead of throwing", () => {
  178. expect(String(resumeWorkflowRunToolEntry.formatModelContent?.({ runId: 42 }))).toContain(
  179. "invalid result",
  180. );
  181. });
  182. });
  183. describe("ResumeWorkflowRun declaration", () => {
  184. it("declares an executing, prompt-less capability consistently on both faces", () => {
  185. expect(resumeWorkflowRunToolEntry.metadata).toMatchObject({
  186. name: RESUME_WORKFLOW_RUN_TOOL_NAME,
  187. // 恢复 = 重新启动执行子进程与 actor 会话,与 CreateWorkflow 同档,只读声明不成立。
  188. readOnly: false,
  189. destructive: false,
  190. concurrentSafe: true,
  191. // 免确认(2026-08-30 用户裁决):resume 钉死在已批准的同一脚本上,不弹窗。
  192. needsApproval: false,
  193. sideEffectScope: "none",
  194. riskLevel: "low",
  195. timeoutMs: 15_000,
  196. });
  197. expect(resumeWorkflowRunToolEntry.permission).toMatchObject({
  198. permission: "resumeWorkflowRun",
  199. needsApproval: false,
  200. sideEffectScope: "none",
  201. riskLevel: "low",
  202. denyPriority: "beforeAsk",
  203. patternSources: ["toolName", "input"],
  204. alwaysAllowPatternSources: ["toolName"],
  205. });
  206. // 免确认裁决的负面钉子:alwaysAsk 若被顺手加回,这里必须红。
  207. expect(resumeWorkflowRunToolEntry.permission).not.toHaveProperty("alwaysAsk");
  208. expect(resumeWorkflowRunToolEntry.permission).not.toHaveProperty("askOptions");
  209. });
  210. it("budgets and times the result like the sibling run tools", () => {
  211. expect(resumeWorkflowRunToolEntry.resultBudget).toMatchObject({
  212. maxInlineBytes: 24_000,
  213. maxModelBytes: 24_000,
  214. strategy: "truncate",
  215. });
  216. expect(resumeWorkflowRunToolEntry.resultBudget.maxInlineBytes).toBeGreaterThan(0);
  217. // timeout 与 metadata.timeoutMs 一致(v2 common contract 断言之外再各自钉一遍)。
  218. expect(resumeWorkflowRunToolEntry.timeout).toMatchObject({
  219. kind: "timed",
  220. defaultMs: 15_000,
  221. maxMs: 15_000,
  222. allowCallOverride: false,
  223. });
  224. });
  225. // tool-contracts.test.ts 的 v2 全量循环在第一处不一致就中止;新工具在这里各自再钉一遍。
  226. it("declares the v2 common contract", () => {
  227. expectV2CommonContract(resumeWorkflowRunToolEntry);
  228. });
  229. it("describes the resumable set and the do-not-poll steering", () => {
  230. const description = resumeWorkflowRunToolEntry.metadata.description ?? "";
  231. expect(description).toMatch(/cancel/i);
  232. expect(description).toContain("interrupted");
  233. expect(description).toMatch(/errored/);
  234. expect(description).toMatch(/do not wait|do not poll/i);
  235. expect(description).toContain("TaskOutput");
  236. expect(description).toContain("GetWorkflowRun");
  237. });
  238. // 用户取消之后主代理不得自行恢复(apps/zcode-cli/packages/dynamic-workflow/docs/execution-engine.md「Cancel and resume」 2026-09-09):
  239. // 描述要把「cancelled 是有人故意停的,只在用户要求时恢复」说出来。钉关键词不钉逐字。
  240. it("tells the model a cancelled run is resumed only when the user asks", () => {
  241. const description = resumeWorkflowRunToolEntry.metadata.description ?? "";
  242. expect(description).toMatch(/stopped it on purpose/i);
  243. expect(description).toMatch(/only when the user asks/i);
  244. expect(description).toContain("TaskStop");
  245. });
  246. });
  247. describe("ResumeWorkflowRun registration", () => {
  248. it("is always on, with no gate option", () => {
  249. const registry = createToolRegistry();
  250. registerBuiltInTools(registry);
  251. expect(registry.has(RESUME_WORKFLOW_RUN_TOOL_NAME)).toBe(true);
  252. expect(registry.toContracts().map((tool) => tool.name)).toContain(RESUME_WORKFLOW_RUN_TOOL_NAME);
  253. });
  254. // 免确认(2026-08-30):build/yolo 自动放行(prompt-less 直行);plan 按 read-only 契约
  255. // 拒绝(mode.plan.nonReadOnly——resume 是执行面工具,plan 模式不执行副作用)。
  256. // 完整的 run() 全链路权限矩阵在 resume-workflow-run-permission.test.ts。
  257. it("auto-allows in build and yolo; plan mode still denies (read-only contract)", () => {
  258. const service = new PermissionService();
  259. const capability = resolveRuntimePermissionCapability(
  260. resumeWorkflowRunToolEntry,
  261. { run_id: "dwfrun-1" },
  262. {
  263. workingDirectory: "/workspace/project",
  264. workspaceRoot: "/workspace/project",
  265. } as never,
  266. );
  267. for (const mode of ["build", "yolo"] as const) {
  268. const decision = service.checkPermission(
  269. {
  270. input: { run_id: "dwfrun-1" },
  271. mode,
  272. riskLevel: "low",
  273. toolName: RESUME_WORKFLOW_RUN_TOOL_NAME,
  274. },
  275. capability,
  276. );
  277. expect(decision.allowed, mode).toBe(true);
  278. }
  279. const planDecision = service.checkPermission(
  280. {
  281. input: { run_id: "dwfrun-1" },
  282. mode: "plan",
  283. riskLevel: "low",
  284. toolName: RESUME_WORKFLOW_RUN_TOOL_NAME,
  285. },
  286. capability,
  287. );
  288. expect(planDecision.allowed).toBe(false);
  289. });
  290. });