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

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