cron-tool.test.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. import { describe, expect, it, vi } from "vitest";
  2. import { createToolRegistry, registerBuiltInTools } from "../src/tool/index.js";
  3. import {
  4. cronCreateHandler,
  5. cronCreateToolEntry,
  6. cronDeleteHandler,
  7. cronListHandler,
  8. cronUpdateHandler,
  9. cronUpdateToolEntry,
  10. } from "../src/tool/handlers/cron.js";
  11. import { CoreErrorType, type AutomationPort, type TraceId } from "@zcode/contracts";
  12. import type { ToolExecutionContext } from "../src/tool/types.js";
  13. import { createTestRuntimeModel } from "./test-runtime-model.js";
  14. function createContext(port?: AutomationPort): ToolExecutionContext {
  15. return {
  16. toolCallId: "tool-cron",
  17. traceId: "trace-cron" as TraceId,
  18. abortSignal: new AbortController().signal,
  19. automationPort: port,
  20. model: createTestRuntimeModel({
  21. generateText: async () => ({ finishReason: "stop", text: "" }),
  22. providerId: "zai-api",
  23. modelId: "GLM-5",
  24. }),
  25. workingDirectory: "/workspace",
  26. workspaceRoot: "/workspace",
  27. sessionId: "sess-cron" as never,
  28. };
  29. }
  30. const automation = {
  31. automationId: "automation-1",
  32. title: "daily report",
  33. cronExpr: "0 9 * * *",
  34. prompt: "write daily report",
  35. enabled: true,
  36. lifecycleStatus: "active" as const,
  37. nextRunAt: 1_700_000_000_000,
  38. runCount: 0,
  39. recurring: true,
  40. };
  41. describe("cron tools", () => {
  42. it("CronCreate 提醒模型在标题中保留用户的时间规则", () => {
  43. expect(cronCreateToolEntry.metadata.modelInstructions).toEqual(
  44. expect.arrayContaining([
  45. expect.stringContaining("preserve the user's natural-language schedule phrase"),
  46. ]),
  47. );
  48. });
  49. it("CronCreate 向模型说明本地时间、一次性和持久化语义", () => {
  50. expect(cronCreateToolEntry.metadata.description).toContain("persistent");
  51. expect(cronCreateToolEntry.metadata.description).toContain("must never ask the run to create");
  52. expect(cronCreateToolEntry.metadata.modelInstructions).toEqual(
  53. expect.arrayContaining([
  54. expect.stringContaining("Do not convert to UTC"),
  55. expect.stringContaining("delayMinutes=3"),
  56. // 相对延迟必须覆盖小时/中文表述并换算成分钟,避免模型只认“in N minutes”。
  57. expect.stringContaining("delayMinutes=120"),
  58. // 根因守卫:pin 绝对 cron 的指令必须显式声明相对一次性改走 delayMinutes,
  59. // 否则“一次性提醒就 pin 月日时分”会覆盖相对延迟规则,模型自算出会滚到下一年的固定日历 cron。
  60. expect.stringContaining("must use delayMinutes"),
  61. expect.stringContaining("recurring=false"),
  62. expect.stringContaining("maxRuns=N"),
  63. expect.stringContaining("not session-only or auto-deleted"),
  64. expect.stringContaining("without adding jitter"),
  65. expect.stringContaining("Never ask the scheduled run to create"),
  66. ]),
  67. );
  68. });
  69. it("registerBuiltInTools:只有注入 automation port 时才暴露 Cron 工具", () => {
  70. const withoutPort = createToolRegistry();
  71. registerBuiltInTools(withoutPort);
  72. expect(withoutPort.has("CronCreate")).toBe(false);
  73. expect(withoutPort.has("CronList")).toBe(false);
  74. expect(withoutPort.has("CronUpdate")).toBe(false);
  75. expect(withoutPort.has("CronDelete")).toBe(false);
  76. const withPort = createToolRegistry();
  77. registerBuiltInTools(withPort, { includeAutomation: true });
  78. expect(withPort.has("CronCreate")).toBe(true);
  79. expect(withPort.has("CronList")).toBe(true);
  80. expect(withPort.has("CronUpdate")).toBe(true);
  81. expect(withPort.has("CronDelete")).toBe(true);
  82. });
  83. it("CronCreate:通过 automationPort 创建当前 workspace 的定时任务", async () => {
  84. const port: AutomationPort = {
  85. create: vi.fn(async () => automation),
  86. list: vi.fn(),
  87. update: vi.fn(),
  88. delete: vi.fn(),
  89. };
  90. const result = await cronCreateHandler(
  91. {
  92. cron: "0 9 * * *",
  93. delayMinutes: null,
  94. prompt: "write daily report",
  95. title: "daily report",
  96. },
  97. createContext(port),
  98. );
  99. expect(port.create).toHaveBeenCalledWith(
  100. {
  101. cron: "0 9 * * *",
  102. delayMinutes: null,
  103. prompt: "write daily report",
  104. title: "daily report",
  105. },
  106. {
  107. model: "zai-api/GLM-5",
  108. sessionId: "sess-cron",
  109. },
  110. );
  111. expect(result).toMatchObject({
  112. automation: {
  113. automationId: "automation-1",
  114. cronExpr: "0 9 * * *",
  115. },
  116. });
  117. });
  118. it("CronCreate 透传 interval carrier,并在结果中保留权威 scheduleRule", async () => {
  119. const intervalAutomation = {
  120. ...automation,
  121. cronExpr: "49 * * * *",
  122. title: "每31小时的第49分提醒",
  123. scheduleRule: {
  124. unit: "hourly" as const,
  125. interval: 31,
  126. hour: 0,
  127. minute: 49,
  128. anchorAt: 1_700_000_000_000,
  129. },
  130. };
  131. const port: AutomationPort = {
  132. create: vi.fn(async () => intervalAutomation),
  133. list: vi.fn(async () => [intervalAutomation]),
  134. update: vi.fn(async () => intervalAutomation),
  135. delete: vi.fn(),
  136. };
  137. const created = await cronCreateHandler(
  138. {
  139. cron: "49 * * * *",
  140. prompt: "提醒我",
  141. title: "每31小时的第49分提醒",
  142. intervalUnit: "hourly",
  143. interval: 31,
  144. },
  145. createContext(port),
  146. );
  147. const updated = await cronUpdateHandler(
  148. {
  149. id: "automation-1",
  150. title: "每200年提醒",
  151. cron: "0 9 15 6 *",
  152. intervalUnit: "yearly",
  153. interval: 200,
  154. },
  155. createContext(port),
  156. );
  157. const listed = await cronListHandler({}, createContext(port));
  158. expect(port.create).toHaveBeenCalledWith(
  159. expect.objectContaining({ intervalUnit: "hourly", interval: 31 }),
  160. expect.anything(),
  161. );
  162. expect(port.update).toHaveBeenCalledWith(
  163. expect.objectContaining({ intervalUnit: "yearly", interval: 200 }),
  164. );
  165. for (const result of [created.automation, updated.automation, listed.automations[0]]) {
  166. expect(result).toMatchObject({
  167. scheduleRule: { unit: "hourly", interval: 31, minute: 49 },
  168. });
  169. }
  170. });
  171. it("CronUpdate:原地更新当前 workspace 的同一个定时任务", async () => {
  172. const updatedAutomation = {
  173. ...automation,
  174. title: "updated report",
  175. maxRuns: undefined,
  176. };
  177. const port: AutomationPort = {
  178. create: vi.fn(),
  179. list: vi.fn(),
  180. update: vi.fn(async () => updatedAutomation),
  181. delete: vi.fn(),
  182. };
  183. const result = await cronUpdateHandler(
  184. {
  185. id: "automation-1",
  186. title: "updated report",
  187. recurring: true,
  188. maxRuns: null,
  189. },
  190. createContext(port),
  191. );
  192. expect(port.update).toHaveBeenCalledWith({
  193. id: "automation-1",
  194. title: "updated report",
  195. recurring: true,
  196. maxRuns: null,
  197. });
  198. expect(result).toMatchObject({
  199. automation: {
  200. automationId: "automation-1",
  201. title: "updated report",
  202. },
  203. });
  204. expect(cronUpdateToolEntry.metadata.modelInstructions).toEqual(
  205. expect.arrayContaining([
  206. expect.stringContaining("CronList first"),
  207. expect.stringContaining("Always pass title"),
  208. expect.stringContaining("every 5 minutes to every 6 minutes"),
  209. expect.stringContaining("Do not simulate an update"),
  210. expect.stringContaining("brief confirmation"),
  211. expect.stringContaining("fenced code block"),
  212. expect.stringContaining("updated automation card"),
  213. ]),
  214. );
  215. });
  216. it("CronList / CronDelete:通过 automationPort 管理当前 workspace 定时任务", async () => {
  217. const port: AutomationPort = {
  218. create: vi.fn(),
  219. list: vi.fn(async () => [automation]),
  220. update: vi.fn(),
  221. delete: vi.fn(async () => true),
  222. };
  223. await expect(cronListHandler({}, createContext(port))).resolves.toEqual({
  224. automations: [automation],
  225. });
  226. await expect(
  227. cronDeleteHandler({ id: "automation-1" }, createContext(port)),
  228. ).resolves.toMatchObject({ deleted: true, id: "automation-1" });
  229. expect(port.delete).toHaveBeenCalledWith({ id: "automation-1" });
  230. });
  231. it("CronDelete:删除不到任务时返回失败结果,避免模型误判为已删除", async () => {
  232. const port: AutomationPort = {
  233. create: vi.fn(),
  234. list: vi.fn(),
  235. update: vi.fn(),
  236. delete: vi.fn(async () => false),
  237. };
  238. await expect(cronDeleteHandler({ id: "stale-id" }, createContext(port))).resolves.toEqual({
  239. deleted: false,
  240. id: "stale-id",
  241. message: "Automation stale-id was not found in the current workspace.",
  242. });
  243. });
  244. it("automation turn 即使绕过 provider denylist 也拒绝三个写工具", async () => {
  245. const port: AutomationPort = {
  246. create: vi.fn(async () => automation),
  247. list: vi.fn(async () => [automation]),
  248. update: vi.fn(async () => automation),
  249. delete: vi.fn(async () => true),
  250. };
  251. const context = { ...createContext(port), automationTurn: true };
  252. const mutations = [
  253. () =>
  254. cronCreateHandler(
  255. {
  256. cron: "0 9 * * *",
  257. delayMinutes: null,
  258. prompt: "write daily report",
  259. title: "daily report",
  260. },
  261. context,
  262. ),
  263. () => cronUpdateHandler({ id: "automation-1", title: "updated", prompt: "updated" }, context),
  264. () => cronDeleteHandler({ id: "automation-1" }, context),
  265. ];
  266. for (const mutation of mutations) {
  267. await expect(mutation()).rejects.toMatchObject({ type: CoreErrorType.PermissionDenied });
  268. }
  269. expect(port.create).not.toHaveBeenCalled();
  270. expect(port.update).not.toHaveBeenCalled();
  271. expect(port.delete).not.toHaveBeenCalled();
  272. await expect(cronListHandler({}, context)).resolves.toEqual({ automations: [automation] });
  273. });
  274. });