automationRepo.test.ts 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842
  1. import { mkdtempSync, rmSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { DatabaseSync } from "node:sqlite";
  5. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  6. import {
  7. AutomationCreateLimitError,
  8. AutomationRepo,
  9. CLAIM_STALE_MS,
  10. DISPATCH_MAX_ATTEMPTS,
  11. DISPATCH_RETRY_BASE_MS,
  12. } from "../src/session/automationRepo.js";
  13. import {
  14. AutomationService,
  15. InvalidAutomationIntervalCarrierError,
  16. InvalidAutomationMaxRunsUpdateError,
  17. InvalidAutomationScheduleRuleError,
  18. } from "../src/session/automationService.js";
  19. import {
  20. computeAutomationNextRunAt,
  21. StaleOneShotAutomationScheduleError,
  22. } from "../src/session/automationCron.js";
  23. import {
  24. AUTOMATION_CREATE_LIMIT,
  25. type ZCodeAutomationCreateParams,
  26. type ZCodeAutomationLifecycleStatus,
  27. } from "@zcode/shared";
  28. // 固定基准时间,保证退避 / 重排断言可复现。
  29. const NOW = 1_700_000_000_000;
  30. const MINUTE = 60_000;
  31. function makeParams(
  32. overrides: Partial<ZCodeAutomationCreateParams> = {},
  33. ): ZCodeAutomationCreateParams {
  34. return {
  35. title: "每日巡检",
  36. cronExpr: "0 9 * * *",
  37. prompt: "检查昨天的错误日志并汇总",
  38. workspacePath: "/tmp/ws",
  39. recurring: true,
  40. ...overrides,
  41. };
  42. }
  43. // 修复原因:此前测试用 setDataBaseDir(tempDir) 把全局 _dataBaseDir 重定向到临时目录,
  44. // 但 vitest threads 池并发跑测试文件时,全局值会被其它文件的 setDataBaseDir 互相覆盖,
  45. // 导致 repo 与裸 SQL 操作在并发窗口内写进真实库 ~/.zcode/v2(/tmp/ws 系列脏数据即因此产生)。
  46. // 改为依赖注入:每个 describe 持有独立 tempDir,repo 通过构造参数接收 dbPath,
  47. // 裸 SQL 用同一 dbPath,彻底脱离全局单例。
  48. function buildTempDbPath(tempDir: string): string {
  49. return join(tempDir, "tasks-index.sqlite");
  50. }
  51. describe("AutomationRepo 调度状态机", () => {
  52. let tempDir: string | null = null;
  53. let dbPath: string;
  54. let repo: AutomationRepo;
  55. beforeEach(() => {
  56. tempDir = mkdtempSync(join(tmpdir(), "zcode-automation-repo-"));
  57. dbPath = buildTempDbPath(tempDir);
  58. repo = new AutomationRepo(dbPath);
  59. });
  60. afterEach(() => {
  61. repo.close();
  62. if (tempDir) {
  63. rmSync(tempDir, { recursive: true, force: true });
  64. tempDir = null;
  65. }
  66. });
  67. it("create + list + get:新建后可查询,初始为 active/enabled", async () => {
  68. const created = await repo.create(makeParams({ targetTaskId: "task-1" }), {
  69. nextRunAt: NOW + MINUTE,
  70. });
  71. expect(created.enabled).toBe(true);
  72. expect(created.lifecycleStatus).toBe("active");
  73. expect(created.recurring).toBe(true);
  74. expect(created.nextRunAt).toBe(NOW + MINUTE);
  75. expect(created.runCount).toBe(0);
  76. expect(created.targetTaskId).toBe("task-1");
  77. const list = await repo.list();
  78. expect(list).toHaveLength(1);
  79. const got = await repo.get(created.automationId);
  80. expect(got?.automationId).toBe(created.automationId);
  81. expect(got?.cronExpr).toBe("0 9 * * *");
  82. expect(got?.targetTaskId).toBe("task-1");
  83. });
  84. it.each([undefined, "yolo", "guarded"] as const)(
  85. "重开数据库保留 automation mode=%s,无默认值迁移",
  86. async (mode) => {
  87. const created = await repo.create(makeParams({ mode }), { nextRunAt: NOW + MINUTE });
  88. repo.close();
  89. repo = new AutomationRepo(dbPath);
  90. expect((await repo.get(created.automationId))?.mode).toBe(mode);
  91. expect((await repo.list())[0]?.mode).toBe(mode);
  92. },
  93. );
  94. it("首次派发区分跟随默认、未迁移旧选择和损坏新值,不从旧列恢复执行选择", async () => {
  95. const created = await repo.create(makeParams(), { nextRunAt: NOW + MINUTE });
  96. await expect(
  97. repo.getModelSelectionForDispatch(created.automationId, created.workspaceKey),
  98. ).resolves.toBeUndefined();
  99. const db = new DatabaseSync(dbPath);
  100. try {
  101. for (const raw of [null, "{}", "invalid-json"]) {
  102. db.prepare(
  103. "UPDATE automations SET model_selection = ?, model = ?, provider = ? WHERE automation_id = ?",
  104. ).run(raw, "unrecognized-old-model", "glm", created.automationId);
  105. await expect(
  106. repo.getModelSelectionForDispatch(created.automationId, created.workspaceKey),
  107. ).rejects.toThrow("Automation 模型选择不可用");
  108. }
  109. // 新版明确跟随是合法产品意图;保留的旧列仅供回滚,不得重新带回旧选择。
  110. db.prepare("UPDATE automations SET model_selection = 'null' WHERE automation_id = ?").run(
  111. created.automationId,
  112. );
  113. await expect(
  114. repo.getModelSelectionForDispatch(created.automationId, created.workspaceKey),
  115. ).resolves.toBeUndefined();
  116. const selection = {
  117. providerId: "custom",
  118. modelId: "model",
  119. options: { reasoningLevel: "high" },
  120. };
  121. db.prepare("UPDATE automations SET model_selection = ? WHERE automation_id = ?").run(
  122. JSON.stringify(selection),
  123. created.automationId,
  124. );
  125. await expect(
  126. repo.getModelSelectionForDispatch(created.automationId, created.workspaceKey),
  127. ).resolves.toEqual(selection);
  128. await expect(
  129. repo.getModelSelectionForDispatch(created.automationId, "another-workspace"),
  130. ).rejects.toThrow();
  131. } finally {
  132. db.close();
  133. }
  134. });
  135. it("旧账号与自定义选择仅凭存储即可导入,不需要账号或候选配置", async () => {
  136. const first = await repo.create(makeParams(), { nextRunAt: NOW + MINUTE });
  137. const second = await repo.create(makeParams(), { nextRunAt: NOW + MINUTE });
  138. const db = new DatabaseSync(dbPath);
  139. db.prepare(
  140. "UPDATE automations SET model_selection = NULL, model = ? WHERE automation_id = ?",
  141. ).run("builtin:bigmodel-coding-plan/GLM-5", first.automationId);
  142. db.prepare(
  143. "UPDATE automations SET model_selection = NULL, model = ? WHERE automation_id = ?",
  144. ).run("custom-provider/model", second.automationId);
  145. db.exec("DELETE FROM tasks_schema_migration WHERE id='0002_provider_selection'");
  146. db.close();
  147. repo.close();
  148. repo = new AutomationRepo(dbPath);
  149. const list = await repo.list();
  150. expect(
  151. list.find((item) => item.automationId === first.automationId)?.modelSelection?.providerId,
  152. ).toBe("account:bigmodel-individual-coding-plan");
  153. expect(
  154. list.find((item) => item.automationId === second.automationId)?.modelSelection?.providerId,
  155. ).toBe("custom-provider");
  156. expect((await repo.get(first.automationId))?.modelSelection?.providerId).toBe(
  157. "account:bigmodel-individual-coding-plan",
  158. );
  159. });
  160. it("delete:返回真实删除结果并限定 workspace", async () => {
  161. const created = await repo.create(makeParams(), { nextRunAt: NOW + MINUTE });
  162. await expect(repo.delete(created.automationId, created.workspaceKey)).resolves.toBe(true);
  163. await expect(repo.get(created.automationId)).resolves.toBeNull();
  164. await expect(repo.delete(created.automationId, created.workspaceKey)).resolves.toBe(false);
  165. });
  166. it.each([
  167. "builtin:zai-coding-plan/GLM-5.3-Flash",
  168. "custom:builtin%3Azai-coding-plan:GLM-5.3-Flash",
  169. ])("旧定时任务解码 %s,并在新列固定迁移结果但保留回滚字段", async (legacyModel) => {
  170. const created = await repo.create(makeParams(), { nextRunAt: NOW });
  171. repo.close();
  172. const db = new DatabaseSync(dbPath);
  173. db.prepare(
  174. "UPDATE automations SET model = ?, provider = 'glm', thought_level = 'high', model_selection = NULL WHERE automation_id = ?",
  175. ).run(legacyModel, created.automationId);
  176. db.exec("DELETE FROM tasks_schema_migration WHERE id='0002_provider_selection'");
  177. db.close();
  178. repo = new AutomationRepo(dbPath);
  179. const expected = {
  180. providerId: "account:zai-individual-coding-plan",
  181. modelId: "GLM-5.3-Flash",
  182. options: { reasoningLevel: "high" },
  183. };
  184. expect((await repo.get(created.automationId))?.modelSelection).toEqual(expected);
  185. await repo.update(created.automationId, { title: "Edited title" });
  186. repo.close();
  187. const persistedDb = new DatabaseSync(dbPath);
  188. const row = persistedDb
  189. .prepare(
  190. "SELECT model, provider, thought_level, model_selection FROM automations WHERE automation_id = ?",
  191. )
  192. .get(created.automationId);
  193. persistedDb.close();
  194. expect(row).toMatchObject({ model: legacyModel, provider: "glm", thought_level: "high" });
  195. expect(JSON.parse(String(row?.model_selection))).toEqual(expected);
  196. repo = new AutomationRepo(dbPath);
  197. expect((await repo.get(created.automationId))?.modelSelection).toEqual(expected);
  198. });
  199. it.each(["null", "{}", "{broken"])(
  200. "新选择 %s 不回读旧模型,清空后重启也不复活",
  201. async (modelSelection) => {
  202. const created = await repo.create(makeParams(), { nextRunAt: NOW });
  203. repo.close();
  204. const db = new DatabaseSync(dbPath);
  205. db.prepare(
  206. "UPDATE automations SET model = 'personal:p/m', provider = 'glm', thought_level = 'low', model_selection = ? WHERE automation_id = ?",
  207. ).run(modelSelection, created.automationId);
  208. db.close();
  209. repo = new AutomationRepo(dbPath);
  210. expect((await repo.get(created.automationId))?.modelSelection).toBeUndefined();
  211. await repo.update(created.automationId, { modelSelection: null });
  212. repo.close();
  213. repo = new AutomationRepo(dbPath);
  214. expect((await repo.get(created.automationId))?.modelSelection).toBeUndefined();
  215. },
  216. );
  217. it("delete:其他 workspace 的同 ID 不会被删除", async () => {
  218. const created = await repo.create(makeParams(), { nextRunAt: NOW + MINUTE });
  219. await expect(repo.delete(created.automationId, "other-workspace")).resolves.toBe(false);
  220. await expect(repo.get(created.automationId)).resolves.toBeDefined();
  221. });
  222. it("Bot 创建来源只在内部读取接口持久化,不泄露到 automation 展示模型", async () => {
  223. const botDeliveryTarget = {
  224. provider: "feishu" as const,
  225. botId: "bot-feishu",
  226. providerUserId: "chat-1",
  227. chatType: "group" as const,
  228. };
  229. const created = await repo.create(makeParams({ botDeliveryTarget }), {
  230. nextRunAt: NOW + MINUTE,
  231. });
  232. await expect(
  233. repo.getBotDeliveryTarget(created.automationId, created.workspaceKey),
  234. ).resolves.toEqual(botDeliveryTarget);
  235. expect(await repo.get(created.automationId)).not.toHaveProperty("botDeliveryTarget");
  236. repo.close();
  237. repo = new AutomationRepo(dbPath);
  238. await expect(
  239. repo.getBotDeliveryTarget(created.automationId, created.workspaceKey),
  240. ).resolves.toEqual(botDeliveryTarget);
  241. await expect(
  242. repo.getBotDeliveryTarget(created.automationId, "other-workspace"),
  243. ).resolves.toBeUndefined();
  244. });
  245. it("Bot 回推目标脏数据按未配置处理,不能拖垮定时任务列表", async () => {
  246. const created = await repo.create(makeParams(), { nextRunAt: NOW + MINUTE });
  247. repo.close();
  248. const db = new DatabaseSync(dbPath);
  249. db.prepare("UPDATE automations SET bot_delivery_target = ? WHERE automation_id = ?").run(
  250. '{"provider":"telegram"}',
  251. created.automationId,
  252. );
  253. db.close();
  254. repo = new AutomationRepo(dbPath);
  255. await expect(repo.getBotDeliveryTarget(created.automationId)).resolves.toBeUndefined();
  256. await expect(repo.list()).resolves.toHaveLength(1);
  257. });
  258. it("读取历史空白或未知 mode 时按未设置归一化,避免单条脏数据拖垮整批协议校验", async () => {
  259. const blankMode = await repo.create(makeParams({ title: "blank mode" }), {
  260. nextRunAt: NOW + MINUTE,
  261. });
  262. const unknownMode = await repo.create(makeParams({ title: "unknown mode" }), {
  263. nextRunAt: NOW + MINUTE,
  264. });
  265. repo.close();
  266. const db = new DatabaseSync(dbPath);
  267. db.prepare("UPDATE automations SET mode = ? WHERE automation_id = ?").run(
  268. "",
  269. blankMode.automationId,
  270. );
  271. db.prepare("UPDATE automations SET mode = ? WHERE automation_id = ?").run(
  272. "legacy-superuser",
  273. unknownMode.automationId,
  274. );
  275. db.close();
  276. repo = new AutomationRepo(dbPath);
  277. const automations = await repo.list({ workspacePath: "/tmp/ws" });
  278. expect(automations).toHaveLength(2);
  279. expect(automations.map((automation) => automation.mode)).toEqual([undefined, undefined]);
  280. });
  281. it("升级旧库时用历史 run_count 初始化定时派发计数", async () => {
  282. const created = await repo.create(makeParams({ recurring: false, maxRuns: 3 }), {
  283. nextRunAt: NOW,
  284. });
  285. await repo.markDispatched(created.automationId, {
  286. dispatchedAt: NOW,
  287. nextRunAt: NOW + MINUTE,
  288. });
  289. await repo.markDispatched(created.automationId, {
  290. dispatchedAt: NOW + MINUTE,
  291. nextRunAt: NOW + 2 * MINUTE,
  292. });
  293. repo.close();
  294. const db = new DatabaseSync(dbPath);
  295. db.exec("ALTER TABLE automations DROP COLUMN scheduled_run_count");
  296. db.exec("DELETE FROM tasks_schema_migration");
  297. db.close();
  298. repo = new AutomationRepo(dbPath);
  299. expect(await repo.getScheduledRunCount(created.automationId)).toBe(2);
  300. await repo.markDispatched(created.automationId, {
  301. dispatchedAt: NOW + 2 * MINUTE,
  302. nextRunAt: NOW + 3 * MINUTE,
  303. });
  304. await expect(repo.get(created.automationId)).resolves.toMatchObject({
  305. runCount: 3,
  306. lifecycleStatus: "completed",
  307. enabled: false,
  308. });
  309. });
  310. it("create/update 写入边界拒绝非法 mode,避免继续制造不可序列化数据", async () => {
  311. await expect(
  312. repo.create(makeParams({ mode: "legacy-superuser" as never }), {
  313. nextRunAt: NOW + MINUTE,
  314. }),
  315. ).rejects.toThrow(/mode/i);
  316. const created = await repo.create(makeParams({ mode: "build" }), {
  317. nextRunAt: NOW + MINUTE,
  318. });
  319. await expect(
  320. repo.update(created.automationId, { mode: "legacy-superuser" as never }),
  321. ).rejects.toThrow(/mode/i);
  322. await expect(repo.get(created.automationId)).resolves.toMatchObject({ mode: "build" });
  323. });
  324. it("hasTaskBinding 只在当前 workspaceKey 内按 targetTaskId 查询", async () => {
  325. await repo.create(
  326. makeParams({
  327. workspacePath: "/tmp/ws-a",
  328. workspaceIdentity: "remote:ssh:dev:/tmp/ws-a",
  329. targetTaskId: "session-1",
  330. }),
  331. { nextRunAt: NOW + MINUTE },
  332. );
  333. await repo.create(makeParams({ workspacePath: "/tmp/ws-b", targetTaskId: "session-other" }), {
  334. nextRunAt: NOW + MINUTE,
  335. });
  336. await expect(
  337. repo.hasTaskBinding({
  338. workspacePath: "/tmp/ws-a",
  339. workspaceIdentity: "remote:ssh:dev:/tmp/ws-a",
  340. targetTaskId: "session-1",
  341. }),
  342. ).resolves.toBe(true);
  343. await expect(
  344. repo.hasTaskBinding({
  345. workspacePath: "/tmp/ws-a",
  346. workspaceIdentity: "remote:ssh:other:/tmp/ws-a",
  347. targetTaskId: "session-1",
  348. }),
  349. ).resolves.toBe(false);
  350. await expect(
  351. repo.hasTaskBinding({ workspacePath: "/tmp/ws-b", targetTaskId: "session-1" }),
  352. ).resolves.toBe(false);
  353. });
  354. it("create:所有生命周期状态合计达到 20 条后拒绝创建,删除后释放名额", async () => {
  355. const statuses: ZCodeAutomationLifecycleStatus[] = ["active", "paused", "completed", "failed"];
  356. for (let index = 0; index < AUTOMATION_CREATE_LIMIT; index += 1) {
  357. await repo.create(makeParams({ title: `task-${index}` }), {
  358. nextRunAt: NOW + MINUTE,
  359. lifecycleStatus: statuses[index % statuses.length],
  360. });
  361. }
  362. const retained = await repo.list();
  363. expect(retained).toHaveLength(AUTOMATION_CREATE_LIMIT);
  364. expect(new Set(retained.map((automation) => automation.lifecycleStatus))).toEqual(
  365. new Set(statuses),
  366. );
  367. await expect(
  368. repo.create(makeParams({ title: "task-over-limit" }), {
  369. nextRunAt: NOW + MINUTE,
  370. }),
  371. ).rejects.toBeInstanceOf(AutomationCreateLimitError);
  372. await repo.delete(retained[0]!.automationId);
  373. await expect(
  374. repo.create(makeParams({ title: "task-after-delete" }), {
  375. nextRunAt: NOW + MINUTE,
  376. }),
  377. ).resolves.toMatchObject({ title: "task-after-delete" });
  378. });
  379. it("update:null 显式清空结构化模型选择与有限次数上限", async () => {
  380. const created = await repo.create(
  381. makeParams({
  382. modelSelection: {
  383. providerId: "zai",
  384. modelId: "glm-4.5",
  385. options: { reasoningLevel: "high" },
  386. },
  387. mode: "build",
  388. recurring: false,
  389. maxRuns: 3,
  390. }),
  391. { nextRunAt: NOW + MINUTE },
  392. );
  393. const updated = await repo.update(created.automationId, {
  394. modelSelection: null,
  395. mode: null,
  396. recurring: true,
  397. maxRuns: null,
  398. });
  399. expect(updated?.modelSelection).toBeUndefined();
  400. expect(updated?.mode).toBeUndefined();
  401. expect(updated?.recurring).toBe(true);
  402. expect(updated?.maxRuns).toBeUndefined();
  403. });
  404. it("service update:原地保留 automation 身份、绑定会话和运行历史", async () => {
  405. const service = new AutomationService(repo);
  406. const created = await repo.create(
  407. makeParams({
  408. targetTaskId: "task-history",
  409. modelSelection: { providerId: "zai", modelId: "glm-5" },
  410. }),
  411. { nextRunAt: NOW - 1 },
  412. );
  413. const [claimed] = await repo.claimDue(NOW);
  414. const runId = `${created.automationId}:${NOW}`;
  415. await repo.upsertRunClaimed({
  416. runId,
  417. automationId: created.automationId,
  418. workspaceKey: "/tmp/ws",
  419. scheduledAt: NOW,
  420. trigger: "schedule",
  421. });
  422. await repo.markRunDispatch({
  423. runId,
  424. dispatchStatus: "dispatched",
  425. sessionId: "run-session-1",
  426. });
  427. await repo.markDispatched(claimed!.automationId, {
  428. dispatchedAt: NOW,
  429. nextRunAt: NOW + MINUTE,
  430. });
  431. const updated = await service.update(created.automationId, {
  432. title: "更新后的巡检",
  433. prompt: "检查最近一小时的错误日志",
  434. scheduleEditedByUser: true,
  435. });
  436. expect(updated).toMatchObject({
  437. automationId: created.automationId,
  438. targetTaskId: "task-history",
  439. modelSelection: { providerId: "zai", modelId: "glm-5" },
  440. scheduleEditedByUser: true,
  441. runCount: 1,
  442. title: "更新后的巡检",
  443. prompt: "检查最近一小时的错误日志",
  444. });
  445. await expect(repo.listRuns(created.automationId)).resolves.toMatchObject([
  446. {
  447. automationId: created.automationId,
  448. sessionId: "run-session-1",
  449. },
  450. ]);
  451. });
  452. it("service update:拒绝单独清空有限次数上限且不改变活动任务", async () => {
  453. const service = new AutomationService(repo);
  454. const created = await repo.create(makeParams({ recurring: false, maxRuns: 5 }), {
  455. nextRunAt: NOW + MINUTE,
  456. });
  457. await repo.markDispatched(created.automationId, {
  458. dispatchedAt: NOW,
  459. nextRunAt: NOW + MINUTE,
  460. });
  461. await repo.markDispatched(created.automationId, {
  462. dispatchedAt: NOW + MINUTE,
  463. nextRunAt: NOW + 2 * MINUTE,
  464. });
  465. await expect(service.update(created.automationId, { maxRuns: null })).rejects.toBeInstanceOf(
  466. InvalidAutomationMaxRunsUpdateError,
  467. );
  468. await expect(repo.get(created.automationId)).resolves.toMatchObject({
  469. recurring: false,
  470. maxRuns: 5,
  471. runCount: 2,
  472. lifecycleStatus: "active",
  473. enabled: true,
  474. });
  475. await expect(
  476. service.update(created.automationId, {
  477. recurring: true,
  478. maxRuns: null,
  479. }),
  480. ).resolves.toMatchObject({
  481. recurring: true,
  482. maxRuns: undefined,
  483. runCount: 2,
  484. lifecycleStatus: "active",
  485. enabled: true,
  486. });
  487. });
  488. it("service update:切换无限循环时自动清除旧 maxRuns,并拒绝矛盾组合", async () => {
  489. const service = new AutomationService(repo);
  490. const created = await repo.create(makeParams({ recurring: false, maxRuns: 3 }), {
  491. nextRunAt: NOW + MINUTE,
  492. });
  493. await expect(
  494. service.update(created.automationId, { recurring: true, maxRuns: 3 }),
  495. ).rejects.toBeInstanceOf(InvalidAutomationMaxRunsUpdateError);
  496. await expect(repo.get(created.automationId)).resolves.toMatchObject({
  497. recurring: false,
  498. maxRuns: 3,
  499. lifecycleStatus: "active",
  500. enabled: true,
  501. });
  502. await expect(service.update(created.automationId, { recurring: true })).resolves.toMatchObject({
  503. recurring: true,
  504. maxRuns: undefined,
  505. lifecycleStatus: "active",
  506. enabled: true,
  507. });
  508. await expect(service.update(created.automationId, { maxRuns: 5 })).rejects.toBeInstanceOf(
  509. InvalidAutomationMaxRunsUpdateError,
  510. );
  511. await expect(repo.get(created.automationId)).resolves.toMatchObject({
  512. recurring: true,
  513. maxRuns: undefined,
  514. lifecycleStatus: "active",
  515. enabled: true,
  516. });
  517. const legacyDirty = await repo.create(
  518. makeParams({ title: "历史脏任务", recurring: true, maxRuns: 4 }),
  519. { nextRunAt: NOW + MINUTE },
  520. );
  521. await expect(
  522. service.update(legacyDirty.automationId, { title: "已归一化任务" }),
  523. ).resolves.toMatchObject({
  524. title: "已归一化任务",
  525. recurring: true,
  526. maxRuns: undefined,
  527. });
  528. });
  529. it("service update:只切换无限循环时保留长月度 scheduleRule", async () => {
  530. const service = new AutomationService(repo);
  531. const scheduleRule = {
  532. unit: "monthly" as const,
  533. interval: 29,
  534. hour: 9,
  535. minute: 0,
  536. anchorAt: NOW,
  537. monthDays: [1],
  538. };
  539. const created = await repo.create(
  540. makeParams({
  541. cronExpr: "0 9 1 * *",
  542. recurring: false,
  543. maxRuns: 3,
  544. scheduleRule,
  545. }),
  546. { nextRunAt: NOW + 29 * 31 * 24 * 60 * MINUTE },
  547. );
  548. const updated = await service.update(created.automationId, {
  549. title: "每 29 个月巡检",
  550. recurring: true,
  551. });
  552. expect(updated).toMatchObject({
  553. recurring: true,
  554. maxRuns: undefined,
  555. scheduleRule,
  556. nextRunAt: created.nextRunAt,
  557. });
  558. });
  559. it("service create/update:非法 scheduleRule 在写库前被领域层拒绝", async () => {
  560. const service = new AutomationService(repo);
  561. const invalidMonthlyRule = {
  562. unit: "monthly" as const,
  563. interval: 1_201,
  564. hour: 9,
  565. minute: 0,
  566. anchorAt: NOW,
  567. monthDays: [1],
  568. monthlyMode: "date" as const,
  569. };
  570. await expect(
  571. service.create(makeParams({ scheduleRule: invalidMonthlyRule })),
  572. ).rejects.toBeInstanceOf(InvalidAutomationScheduleRuleError);
  573. await expect(
  574. service.create(makeParams({ scheduleRule: { ...invalidMonthlyRule, interval: 0 } })),
  575. ).rejects.toBeInstanceOf(InvalidAutomationScheduleRuleError);
  576. await expect(repo.list()).resolves.toHaveLength(0);
  577. const created = await service.create(makeParams());
  578. await expect(
  579. service.update(created.automationId, {
  580. scheduleRule: {
  581. ...invalidMonthlyRule,
  582. interval: 1,
  583. monthDays: [],
  584. },
  585. }),
  586. ).rejects.toBeInstanceOf(InvalidAutomationScheduleRuleError);
  587. await expect(
  588. service.update(created.automationId, {
  589. scheduleRule: {
  590. ...invalidMonthlyRule,
  591. interval: 1,
  592. monthlyMode: "weekday",
  593. weekdays: [],
  594. },
  595. }),
  596. ).rejects.toBeInstanceOf(InvalidAutomationScheduleRuleError);
  597. await expect(repo.get(created.automationId)).resolves.toMatchObject({
  598. automationId: created.automationId,
  599. scheduleRule: undefined,
  600. });
  601. });
  602. it("service create:陈旧的一次性固定日历目标在写库前被拒绝", async () => {
  603. const service = new AutomationService(repo);
  604. const dateNow = vi
  605. .spyOn(Date, "now")
  606. .mockReturnValue(new Date(2026, 6, 28, 14, 38, 53).getTime());
  607. try {
  608. await expect(
  609. service.create(
  610. makeParams({
  611. cronExpr: "34 14 28 7 *",
  612. recurring: false,
  613. }),
  614. ),
  615. ).rejects.toBeInstanceOf(StaleOneShotAutomationScheduleError);
  616. await expect(repo.list()).resolves.toHaveLength(0);
  617. } finally {
  618. dateNow.mockRestore();
  619. }
  620. });
  621. it("service create:相对分钟任务忽略模型 cron,并以真实当前时间计算 nextRunAt", async () => {
  622. const service = new AutomationService(repo);
  623. const now = new Date(2026, 6, 28, 14, 44, 28).getTime();
  624. const dateNow = vi.spyOn(Date, "now").mockReturnValue(now);
  625. try {
  626. const created = await service.create(
  627. makeParams({
  628. // 模拟模型误以为当前是 16:39;该值不能再成为相对时间任务的调度真值。
  629. cronExpr: "42 16 28 7 *",
  630. relativeDelayMinutes: 3,
  631. recurring: false,
  632. }),
  633. );
  634. expect(created).toMatchObject({
  635. cronExpr: "47 14 28 7 *",
  636. nextRunAt: now + 3 * MINUTE,
  637. recurring: false,
  638. scheduleRule: {
  639. unit: "minute",
  640. interval: 3,
  641. anchorAt: now,
  642. },
  643. });
  644. } finally {
  645. dateNow.mockRestore();
  646. }
  647. });
  648. it("create + list + get:保留权限模式和稀疏结构化模型选择", async () => {
  649. const created = await repo.create(
  650. makeParams({
  651. mode: "build",
  652. modelSelection: {
  653. providerId: "zai",
  654. modelId: "glm-5",
  655. options: { reasoningLevel: "high" },
  656. },
  657. }),
  658. { nextRunAt: NOW + MINUTE },
  659. );
  660. expect(created.mode).toBe("build");
  661. expect(created.modelSelection).toEqual({
  662. providerId: "zai",
  663. modelId: "glm-5",
  664. options: { reasoningLevel: "high" },
  665. });
  666. const got = await repo.get(created.automationId);
  667. expect(got?.mode).toBe("build");
  668. expect(got?.modelSelection).toEqual(created.modelSelection);
  669. const list = await repo.list();
  670. expect(list[0]?.mode).toBe("build");
  671. expect(list[0]?.modelSelection).toEqual(created.modelSelection);
  672. });
  673. it("create + get:保留自定义重复规则", async () => {
  674. const scheduleRule = {
  675. unit: "weekly" as const,
  676. interval: 3,
  677. hour: 10,
  678. minute: 30,
  679. anchorAt: NOW,
  680. weekdays: [1, 3],
  681. };
  682. const created = await repo.create(makeParams({ scheduleRule }), {
  683. nextRunAt: NOW + MINUTE,
  684. });
  685. expect(created.scheduleRule).toEqual(scheduleRule);
  686. expect((await repo.get(created.automationId))?.scheduleRule).toEqual(scheduleRule);
  687. });
  688. it("service create:每 31 小时可用合法兼容 cron 保存并按真实规则排程", async () => {
  689. const createdAt = new Date(2026, 7, 4, 18, 38).getTime();
  690. const dateNow = vi.spyOn(Date, "now").mockReturnValue(createdAt);
  691. try {
  692. const created = await new AutomationService(repo).create(
  693. makeParams({
  694. cronExpr: "49 * * * *",
  695. scheduleRule: {
  696. unit: "hourly",
  697. interval: 31,
  698. hour: 0,
  699. minute: 49,
  700. anchorAt: 0,
  701. },
  702. }),
  703. );
  704. expect(created).toMatchObject({
  705. cronExpr: "49 * * * *",
  706. scheduleRule: {
  707. unit: "hourly",
  708. interval: 31,
  709. minute: 49,
  710. anchorAt: createdAt,
  711. },
  712. nextRunAt: new Date(2026, 7, 4, 18, 49).getTime(),
  713. });
  714. } finally {
  715. dateNow.mockRestore();
  716. }
  717. });
  718. it("service create/update:长分钟和天间隔使用合法兼容 cron,并持久化真实 scheduleRule", async () => {
  719. const createdAt = new Date(2026, 7, 4, 18, 38).getTime();
  720. const updatedAt = createdAt + MINUTE;
  721. const dateNow = vi.spyOn(Date, "now");
  722. const service = new AutomationService(repo);
  723. try {
  724. for (const [minuteInterval, dayInterval] of [
  725. [61, 32],
  726. [200, 200],
  727. ]) {
  728. dateNow.mockReturnValue(createdAt);
  729. const created = await service.create(
  730. makeParams({
  731. title: `每 ${minuteInterval} 分钟`,
  732. cronExpr: "* * * * *",
  733. scheduleRule: {
  734. unit: "minute",
  735. interval: minuteInterval,
  736. hour: 18,
  737. minute: 38,
  738. anchorAt: 0,
  739. },
  740. }),
  741. );
  742. expect(created).toMatchObject({
  743. cronExpr: "* * * * *",
  744. scheduleRule: {
  745. unit: "minute",
  746. interval: minuteInterval,
  747. anchorAt: createdAt,
  748. },
  749. nextRunAt: createdAt + minuteInterval * MINUTE,
  750. });
  751. await expect(repo.get(created.automationId)).resolves.toMatchObject({
  752. cronExpr: "* * * * *",
  753. scheduleRule: {
  754. unit: "minute",
  755. interval: minuteInterval,
  756. anchorAt: createdAt,
  757. },
  758. });
  759. dateNow.mockReturnValue(updatedAt);
  760. const updated = await service.update(created.automationId, {
  761. cronExpr: "49 17 * * *",
  762. scheduleRule: {
  763. unit: "daily",
  764. interval: dayInterval,
  765. hour: 17,
  766. minute: 49,
  767. anchorAt: 0,
  768. },
  769. });
  770. const expectedNextRun = new Date(updatedAt);
  771. expectedNextRun.setDate(expectedNextRun.getDate() + dayInterval);
  772. expectedNextRun.setHours(17, 49, 0, 0);
  773. expect(updated).toMatchObject({
  774. cronExpr: "49 17 * * *",
  775. scheduleRule: {
  776. unit: "daily",
  777. interval: dayInterval,
  778. hour: 17,
  779. minute: 49,
  780. anchorAt: updatedAt,
  781. },
  782. nextRunAt: expectedNextRun.getTime(),
  783. });
  784. await expect(repo.get(created.automationId)).resolves.toMatchObject({
  785. cronExpr: "49 17 * * *",
  786. scheduleRule: {
  787. unit: "daily",
  788. interval: dayInterval,
  789. hour: 17,
  790. minute: 49,
  791. anchorAt: updatedAt,
  792. },
  793. nextRunAt: expectedNextRun.getTime(),
  794. });
  795. }
  796. } finally {
  797. dateNow.mockRestore();
  798. }
  799. });
  800. it("service create/update:会话 interval carrier 以 scheduleRule 承载 1–200 的真实间隔", async () => {
  801. const createdAt = new Date(2026, 7, 4, 18, 38).getTime();
  802. const updatedAt = createdAt + MINUTE;
  803. const dateNow = vi.spyOn(Date, "now");
  804. const service = new AutomationService(repo);
  805. try {
  806. dateNow.mockReturnValue(createdAt);
  807. const created = await service.create(
  808. makeParams({
  809. title: "每200分钟提醒",
  810. // cron 仅作合法兼容表达式,真实频率必须由 carrier 归一化后的 scheduleRule 承载。
  811. cronExpr: "* * * * *",
  812. intervalUnit: "minute",
  813. interval: 200,
  814. }),
  815. );
  816. expect(created).toMatchObject({
  817. cronExpr: "* * * * *",
  818. scheduleRule: {
  819. unit: "minute",
  820. interval: 200,
  821. anchorAt: createdAt,
  822. },
  823. nextRunAt: createdAt + 200 * MINUTE,
  824. });
  825. dateNow.mockReturnValue(updatedAt);
  826. const updated = await service.update(created.automationId, {
  827. cronExpr: "49 * * * *",
  828. intervalUnit: "hourly",
  829. interval: 200,
  830. });
  831. expect(updated).toMatchObject({
  832. cronExpr: "49 * * * *",
  833. scheduleRule: {
  834. unit: "hourly",
  835. interval: 200,
  836. minute: 49,
  837. anchorAt: updatedAt,
  838. },
  839. });
  840. await expect(repo.get(created.automationId)).resolves.toMatchObject({
  841. scheduleRule: { unit: "hourly", interval: 200, minute: 49, anchorAt: updatedAt },
  842. });
  843. // 领域层也要守住 carrier=无限循环;旧客户端或内部调用不能写入矛盾状态。
  844. await expect(
  845. service.create(
  846. makeParams({
  847. cronExpr: "0 9 * * *",
  848. intervalUnit: "daily",
  849. interval: 40,
  850. recurring: false,
  851. }),
  852. ),
  853. ).rejects.toBeInstanceOf(InvalidAutomationIntervalCarrierError);
  854. await expect(
  855. service.update(created.automationId, {
  856. intervalUnit: "hourly",
  857. interval: 200,
  858. recurring: false,
  859. }),
  860. ).rejects.toBeInstanceOf(InvalidAutomationIntervalCarrierError);
  861. // 领域层不能只信任协议校验:旧客户端或内部调用绕过 protocol 时也必须拒绝越界 carrier。
  862. await expect(
  863. service.create(
  864. makeParams({
  865. cronExpr: "* * * * *",
  866. intervalUnit: "minute",
  867. interval: 201,
  868. }),
  869. ),
  870. ).rejects.toBeInstanceOf(InvalidAutomationIntervalCarrierError);
  871. await expect(
  872. service.update(created.automationId, { intervalUnit: "hourly", interval: 201 }),
  873. ).rejects.toBeInstanceOf(InvalidAutomationIntervalCarrierError);
  874. await expect(repo.get(created.automationId)).resolves.toMatchObject({
  875. scheduleRule: { unit: "hourly", interval: 200, minute: 49, anchorAt: updatedAt },
  876. });
  877. } finally {
  878. dateNow.mockRestore();
  879. }
  880. });
  881. it("service update:interval carrier 将一次性任务切换为无限循环,派发后仍保持 active", async () => {
  882. const createdAt = new Date(2026, 7, 4, 16, 38).getTime();
  883. const updatedAt = createdAt + MINUTE;
  884. const dateNow = vi.spyOn(Date, "now");
  885. const service = new AutomationService(repo);
  886. try {
  887. dateNow.mockReturnValue(createdAt);
  888. const created = await service.create(
  889. makeParams({
  890. title: "一次性日报",
  891. cronExpr: "49 17 * * *",
  892. recurring: false,
  893. }),
  894. );
  895. dateNow.mockReturnValue(updatedAt);
  896. const updated = await service.update(created.automationId, {
  897. intervalUnit: "daily",
  898. interval: 40,
  899. });
  900. // 第一次保留当天尚未到达的 17:49;后续轮次才按 40 天 interval 推进。
  901. const firstNextRunAt = new Date(2026, 7, 4, 17, 49).getTime();
  902. const secondNextRunAt = new Date(2026, 8, 13, 17, 49).getTime();
  903. expect(updated).toMatchObject({
  904. recurring: true,
  905. maxRuns: undefined,
  906. lifecycleStatus: "active",
  907. scheduleRule: {
  908. unit: "daily",
  909. interval: 40,
  910. hour: 17,
  911. minute: 49,
  912. anchorAt: updatedAt,
  913. },
  914. nextRunAt: firstNextRunAt,
  915. });
  916. expect(computeAutomationNextRunAt(updated!, firstNextRunAt)).toBe(secondNextRunAt);
  917. await repo.claimDue(firstNextRunAt);
  918. await repo.markDispatched(created.automationId, {
  919. dispatchedAt: firstNextRunAt,
  920. nextRunAt: secondNextRunAt,
  921. });
  922. await expect(repo.get(created.automationId)).resolves.toMatchObject({
  923. recurring: true,
  924. maxRuns: undefined,
  925. lifecycleStatus: "active",
  926. enabled: true,
  927. runCount: 1,
  928. nextRunAt: secondNextRunAt,
  929. });
  930. } finally {
  931. dateNow.mockRestore();
  932. }
  933. });
  934. it("service update:显式 scheduleRule=null 必须清除已有自定义重复规则", async () => {
  935. const createdAt = new Date(2026, 7, 4, 18, 38).getTime();
  936. const updatedAt = createdAt + MINUTE;
  937. const dateNow = vi.spyOn(Date, "now").mockReturnValue(createdAt);
  938. const service = new AutomationService(repo);
  939. try {
  940. const created = await service.create(
  941. makeParams({
  942. cronExpr: "49 * * * *",
  943. scheduleRule: {
  944. unit: "hourly",
  945. interval: 31,
  946. hour: 0,
  947. minute: 49,
  948. anchorAt: createdAt,
  949. },
  950. }),
  951. );
  952. dateNow.mockReturnValue(updatedAt);
  953. const updated = await service.update(created.automationId, { scheduleRule: null });
  954. expect(updated).toMatchObject({ cronExpr: "49 * * * *", scheduleRule: undefined });
  955. await expect(repo.get(created.automationId)).resolves.toMatchObject({
  956. cronExpr: "49 * * * *",
  957. scheduleRule: undefined,
  958. });
  959. } finally {
  960. dateNow.mockRestore();
  961. }
  962. });
  963. it("claimDue:到期任务被认领且置 running;同一轮不会被二次认领", async () => {
  964. const a = await repo.create(makeParams(), { nextRunAt: NOW - 1 });
  965. const first = await repo.claimDue(NOW);
  966. expect(first.map((x) => x.automationId)).toEqual([a.automationId]);
  967. expect(first[0]!.dispatchStatus).toBe("claimed");
  968. // 已 running,第二次认领应为空(single-flight)。
  969. const second = await repo.claimDue(NOW);
  970. expect(second).toHaveLength(0);
  971. });
  972. it("claimDue:未到期不认领", async () => {
  973. await repo.create(makeParams(), { nextRunAt: NOW + 10 * MINUTE });
  974. const due = await repo.claimDue(NOW);
  975. expect(due).toHaveLength(0);
  976. });
  977. it("claimDue:截止日期已过时转 completed 且不再认领", async () => {
  978. const automation = await repo.create(makeParams({ endAt: NOW - MINUTE }), {
  979. nextRunAt: NOW - 1,
  980. });
  981. expect(await repo.claimDue(NOW)).toHaveLength(0);
  982. expect(await repo.get(automation.automationId)).toMatchObject({
  983. endAt: NOW - MINUTE,
  984. enabled: false,
  985. lifecycleStatus: "completed",
  986. });
  987. });
  988. it("markDispatched(循环):run_count+1、推进 next_run_at、复位 running、保持 active", async () => {
  989. const a = await repo.create(makeParams(), { nextRunAt: NOW - 1 });
  990. await repo.claimDue(NOW);
  991. await repo.markDispatched(a.automationId, {
  992. dispatchedAt: NOW,
  993. nextRunAt: NOW + 24 * 60 * MINUTE,
  994. });
  995. const got = await repo.get(a.automationId);
  996. expect(got?.runCount).toBe(1);
  997. expect(got?.dispatchStatus).toBe("dispatched");
  998. expect(got?.lifecycleStatus).toBe("active");
  999. expect(got?.enabled).toBe(true);
  1000. expect(got?.nextRunAt).toBe(NOW + 24 * 60 * MINUTE);
  1001. expect(got?.lastRunAt).toBe(NOW);
  1002. });
  1003. it("markDispatched:下一次运行越过截止日期时转 completed", async () => {
  1004. const automation = await repo.create(makeParams({ endAt: NOW + MINUTE }), {
  1005. nextRunAt: NOW - 1,
  1006. });
  1007. await repo.claimDue(NOW);
  1008. await repo.markDispatched(automation.automationId, {
  1009. dispatchedAt: NOW,
  1010. nextRunAt: NOW + 2 * MINUTE,
  1011. });
  1012. expect(await repo.get(automation.automationId)).toMatchObject({
  1013. enabled: false,
  1014. lifecycleStatus: "completed",
  1015. runCount: 1,
  1016. });
  1017. });
  1018. it("markDispatched(有限次):达 max_runs 转 completed 并停用", async () => {
  1019. const a = await repo.create(makeParams({ recurring: false, maxRuns: 1 }), {
  1020. nextRunAt: NOW - 1,
  1021. });
  1022. await repo.claimDue(NOW);
  1023. await repo.markDispatched(a.automationId, {
  1024. dispatchedAt: NOW,
  1025. nextRunAt: null,
  1026. });
  1027. const got = await repo.get(a.automationId);
  1028. expect(got?.runCount).toBe(1);
  1029. expect(got?.lifecycleStatus).toBe("completed");
  1030. expect(got?.enabled).toBe(false);
  1031. expect(got?.nextRunAt).toBeUndefined();
  1032. // completed 不再被认领。
  1033. expect(await repo.claimDue(NOW + 100 * MINUTE)).toHaveLength(0);
  1034. });
  1035. it("markDispatchFailed(transient):累加 attempts + 写退避 retry_at,且退避后可被重认领", async () => {
  1036. const a = await repo.create(makeParams(), { nextRunAt: NOW - 1 });
  1037. await repo.claimDue(NOW);
  1038. await repo.markDispatchFailed(a.automationId, {
  1039. failedAt: NOW,
  1040. error: "host 不存在",
  1041. kind: "transient",
  1042. nextRunAt: NOW + 24 * 60 * MINUTE,
  1043. });
  1044. const got = await repo.get(a.automationId);
  1045. expect(got?.dispatchStatus).toBe("failed_to_dispatch");
  1046. expect(got?.dispatchAttempts).toBe(1);
  1047. expect(got?.retryAt).toBe(NOW + DISPATCH_RETRY_BASE_MS);
  1048. expect(got?.enabled).toBe(true);
  1049. // 退避时间未到不认领;到点后按 retry_at 认领。
  1050. expect(await repo.claimDue(NOW + DISPATCH_RETRY_BASE_MS - 1)).toHaveLength(0);
  1051. const retried = await repo.claimDue(NOW + DISPATCH_RETRY_BASE_MS);
  1052. expect(retried.map((x) => x.automationId)).toEqual([a.automationId]);
  1053. });
  1054. it("markDispatchFailed(permanent):直接转 failed 终态并停用", async () => {
  1055. const a = await repo.create(makeParams(), { nextRunAt: NOW - 1 });
  1056. await repo.claimDue(NOW);
  1057. await repo.markDispatchFailed(a.automationId, {
  1058. failedAt: NOW,
  1059. error: "workspace 不存在",
  1060. kind: "permanent",
  1061. });
  1062. const got = await repo.get(a.automationId);
  1063. expect(got?.lifecycleStatus).toBe("failed");
  1064. expect(got?.enabled).toBe(false);
  1065. expect(got?.lastError).toBe("workspace 不存在");
  1066. });
  1067. it("markDispatchFailed(transient 达上限,循环任务):放弃本轮、跳下一个 next_run_at、清重试态", async () => {
  1068. const a = await repo.create(makeParams(), { nextRunAt: NOW - 1 });
  1069. const nextNormal = NOW + 24 * 60 * MINUTE;
  1070. // 连续失败至 MAX_ATTEMPTS。
  1071. for (let i = 0; i < DISPATCH_MAX_ATTEMPTS; i++) {
  1072. await repo.markDispatchFailed(a.automationId, {
  1073. failedAt: NOW + i,
  1074. error: "反复超时",
  1075. kind: "transient",
  1076. nextRunAt: nextNormal,
  1077. });
  1078. }
  1079. const got = await repo.get(a.automationId);
  1080. expect(got?.dispatchStatus).toBe("idle");
  1081. expect(got?.dispatchAttempts).toBe(0);
  1082. expect(got?.retryAt).toBeUndefined();
  1083. expect(got?.nextRunAt).toBe(nextNormal);
  1084. expect(got?.lifecycleStatus).toBe("active");
  1085. expect(got?.enabled).toBe(true);
  1086. });
  1087. it("skipAndReschedule:写一条 skipped run + 前推 next_run_at + 复位认领", async () => {
  1088. const a = await repo.create(makeParams(), {
  1089. nextRunAt: NOW - 100 * MINUTE,
  1090. });
  1091. await repo.claimDue(NOW);
  1092. const runId = `${a.automationId}:${NOW - 100 * MINUTE}`;
  1093. await repo.skipAndReschedule({
  1094. automationId: a.automationId,
  1095. runId,
  1096. workspaceKey: "/tmp/ws",
  1097. scheduledAt: NOW - 100 * MINUTE,
  1098. reason: "computer_asleep_or_app_not_running",
  1099. nextRunAt: NOW + 24 * 60 * MINUTE,
  1100. });
  1101. const got = await repo.get(a.automationId);
  1102. expect(got?.nextRunAt).toBe(NOW + 24 * 60 * MINUTE);
  1103. expect(got?.dispatchStatus).toBe("idle");
  1104. const runs = await repo.listRuns(a.automationId);
  1105. expect(runs).toHaveLength(1);
  1106. expect(runs[0]!.dispatchStatus).toBe("skipped");
  1107. expect(runs[0]!.runId).toBe(runId);
  1108. });
  1109. it("skipAndReschedule(finalize):一次性任务错过窗口即 completed 终态,不再被认领", async () => {
  1110. // 相对时间任务(delayMinutes)落库为 minute scheduleRule;通用重算总能给出
  1111. // anchorAt + k*interval 的未来周期,一次性提醒错过后绝不能借此复活。
  1112. const a = await repo.create(
  1113. makeParams({
  1114. recurring: false,
  1115. cronExpr: "47 14 28 7 *",
  1116. scheduleRule: {
  1117. unit: "minute",
  1118. interval: 5,
  1119. hour: 14,
  1120. minute: 47,
  1121. anchorAt: NOW - 100 * MINUTE,
  1122. },
  1123. }),
  1124. { nextRunAt: NOW - 95 * MINUTE },
  1125. );
  1126. await repo.claimDue(NOW);
  1127. const runId = `${a.automationId}:${NOW - 95 * MINUTE}`;
  1128. await repo.skipAndReschedule({
  1129. automationId: a.automationId,
  1130. runId,
  1131. workspaceKey: "/tmp/ws",
  1132. scheduledAt: NOW - 95 * MINUTE,
  1133. reason: "computer_asleep_or_app_not_running",
  1134. nextRunAt: null,
  1135. finalize: true,
  1136. });
  1137. const got = await repo.get(a.automationId);
  1138. expect(got?.lifecycleStatus).toBe("completed");
  1139. expect(got?.enabled).toBe(false);
  1140. expect(got?.nextRunAt).toBeUndefined();
  1141. // skipped run 台账保留,后续任意 tick 都不得再认领该任务。
  1142. const runs = await repo.listRuns(a.automationId);
  1143. expect(runs).toHaveLength(1);
  1144. expect(runs[0]!.dispatchStatus).toBe("skipped");
  1145. expect(await repo.claimDue(NOW + 24 * 60 * MINUTE)).toHaveLength(0);
  1146. });
  1147. it("upsertRunClaimed:同一 runId 幂等(不新建行,累加 attempts)", async () => {
  1148. const a = await repo.create(makeParams(), { nextRunAt: NOW - 1 });
  1149. const runId = `${a.automationId}:${NOW}`;
  1150. const runParams = {
  1151. runId,
  1152. automationId: a.automationId,
  1153. workspaceKey: "/tmp/ws",
  1154. scheduledAt: NOW,
  1155. trigger: "schedule" as const,
  1156. };
  1157. await repo.upsertRunClaimed(runParams);
  1158. await repo.upsertRunClaimed(runParams);
  1159. const runs = await repo.listRuns(a.automationId);
  1160. expect(runs).toHaveLength(1);
  1161. expect(runs[0]!.attempts).toBe(1);
  1162. });
  1163. it("markRunDispatch + markRunOutcome:回填 session_id 与运行结果", async () => {
  1164. const a = await repo.create(makeParams(), { nextRunAt: NOW - 1 });
  1165. const runId = `${a.automationId}:${NOW}`;
  1166. await repo.upsertRunClaimed({
  1167. runId,
  1168. automationId: a.automationId,
  1169. workspaceKey: "/tmp/ws",
  1170. scheduledAt: NOW,
  1171. trigger: "schedule",
  1172. });
  1173. await repo.markRunDispatch({
  1174. runId,
  1175. dispatchStatus: "dispatched",
  1176. sessionId: "sess-1",
  1177. });
  1178. await repo.markRunOutcome(runId, "succeeded");
  1179. const runs = await repo.listRuns(a.automationId);
  1180. expect(runs[0]!.dispatchStatus).toBe("dispatched");
  1181. expect(runs[0]!.sessionId).toBe("sess-1");
  1182. expect(runs[0]!.outcome).toBe("succeeded");
  1183. });
  1184. it("同一 run 首次形成的 Submission Selection 在失败重试后保持不变", async () => {
  1185. const a = await repo.create(makeParams(), { nextRunAt: NOW - 1 });
  1186. const runId = `${a.automationId}:${NOW}`;
  1187. const fixedSelection = {
  1188. providerId: "provider-a",
  1189. modelId: "model-a",
  1190. options: { reasoningLevel: "high" },
  1191. } as const;
  1192. await repo.upsertRunClaimed({
  1193. runId,
  1194. automationId: a.automationId,
  1195. workspaceKey: "/tmp/ws",
  1196. scheduledAt: NOW,
  1197. trigger: "schedule",
  1198. });
  1199. await expect(repo.fixRunModelSelection(runId, fixedSelection)).resolves.toEqual(fixedSelection);
  1200. await repo.upsertRunClaimed({
  1201. runId,
  1202. automationId: a.automationId,
  1203. workspaceKey: "/tmp/ws",
  1204. scheduledAt: NOW,
  1205. trigger: "schedule",
  1206. });
  1207. await expect(
  1208. repo.fixRunModelSelection(runId, {
  1209. providerId: "provider-b",
  1210. modelId: "model-b",
  1211. }),
  1212. ).resolves.toEqual(fixedSelection);
  1213. await expect(repo.getRun(runId)).resolves.toMatchObject({
  1214. modelSelection: fixedSelection,
  1215. attempts: 1,
  1216. });
  1217. });
  1218. it("手动认领只保存执行台账,账号选择由目标 Host 首次解析后固定且不改长期配置", async () => {
  1219. const original = {
  1220. providerId: "old-account",
  1221. modelId: "model",
  1222. options: { reasoningLevel: "high" },
  1223. };
  1224. const automation = await repo.create(makeParams({ modelSelection: original }), {
  1225. nextRunAt: NOW + MINUTE,
  1226. });
  1227. const claimed = await repo.runNow(automation.automationId, { now: NOW });
  1228. expect(claimed?.run.modelSelection).toBeUndefined();
  1229. expect((await repo.getRun(claimed!.run.runId))?.modelSelection).toBeUndefined();
  1230. const effective = { ...original, providerId: "current-account" };
  1231. expect(await repo.fixRunModelSelection(claimed!.run.runId, effective)).toEqual(effective);
  1232. expect((await repo.get(automation.automationId))?.modelSelection).toEqual(original);
  1233. });
  1234. it("setEnabled:暂停后不参与调度", async () => {
  1235. const a = await repo.create(makeParams(), { nextRunAt: NOW - 1 });
  1236. await repo.setEnabled(a.automationId, false);
  1237. const got = await repo.get(a.automationId);
  1238. expect(got?.enabled).toBe(false);
  1239. expect(got?.lifecycleStatus).toBe("paused");
  1240. expect(await repo.claimDue(NOW)).toHaveLength(0);
  1241. });
  1242. it("restart:终态任务重跑 → 回 active、清计数、按新 next_run_at 重排", async () => {
  1243. const a = await repo.create(makeParams({ recurring: false, maxRuns: 1 }), {
  1244. nextRunAt: NOW - 1,
  1245. });
  1246. await repo.claimDue(NOW);
  1247. await repo.markDispatched(a.automationId, {
  1248. dispatchedAt: NOW,
  1249. nextRunAt: null,
  1250. });
  1251. expect((await repo.get(a.automationId))?.lifecycleStatus).toBe("completed");
  1252. await repo.restart(a.automationId, { nextRunAt: NOW + MINUTE });
  1253. const got = await repo.get(a.automationId);
  1254. expect(got?.lifecycleStatus).toBe("active");
  1255. expect(got?.enabled).toBe(true);
  1256. expect(got?.runCount).toBe(0);
  1257. expect(got?.nextRunAt).toBe(NOW + MINUTE);
  1258. });
  1259. it("service restart:completed 任务不再被复活", async () => {
  1260. const service = new AutomationService(repo);
  1261. const a = await service.create(makeParams({ recurring: false, maxRuns: 1 }));
  1262. await repo.claimDue(NOW);
  1263. await repo.markDispatched(a.automationId, {
  1264. dispatchedAt: NOW,
  1265. nextRunAt: null,
  1266. });
  1267. expect((await repo.get(a.automationId))?.lifecycleStatus).toBe("completed");
  1268. await service.restart(a.automationId);
  1269. const got = await repo.get(a.automationId);
  1270. expect(got?.lifecycleStatus).toBe("completed");
  1271. expect(got?.enabled).toBe(false);
  1272. expect(got?.runCount).toBe(1);
  1273. });
  1274. it("service:刚错过目标分钟的一次性日历任务立即派发一次后 completed", async () => {
  1275. const now = new Date(2026, 6, 16, 17, 31, 30).getTime();
  1276. vi.useFakeTimers();
  1277. vi.setSystemTime(now);
  1278. try {
  1279. const service = new AutomationService(repo);
  1280. const automation = await service.create(
  1281. makeParams({
  1282. title: "1分钟后发送对话总结",
  1283. cronExpr: "31 17 16 7 *",
  1284. recurring: false,
  1285. maxRuns: 1,
  1286. }),
  1287. );
  1288. expect(automation.nextRunAt).toBe(now);
  1289. expect(await repo.claimDue(now)).toHaveLength(1);
  1290. await repo.markDispatched(automation.automationId, {
  1291. dispatchedAt: now,
  1292. nextRunAt: new Date(2027, 6, 16, 17, 31, 0).getTime(),
  1293. });
  1294. const completed = await repo.get(automation.automationId);
  1295. expect(completed).toMatchObject({
  1296. enabled: false,
  1297. lifecycleStatus: "completed",
  1298. nextRunAt: undefined,
  1299. runCount: 1,
  1300. });
  1301. } finally {
  1302. vi.useRealTimers();
  1303. }
  1304. });
  1305. it("service:每 N 分钟在创建和修改时写入新锚点", async () => {
  1306. const createdAt = new Date(2026, 6, 20, 11, 46, 15).getTime();
  1307. vi.useFakeTimers();
  1308. vi.setSystemTime(createdAt);
  1309. try {
  1310. const service = new AutomationService(repo);
  1311. const automation = await service.create(
  1312. makeParams({ cronExpr: "*/10 * * * *", title: "每10分钟问候" }),
  1313. );
  1314. expect(automation.scheduleRule).toMatchObject({
  1315. unit: "minute",
  1316. interval: 10,
  1317. anchorAt: createdAt,
  1318. });
  1319. expect(automation.nextRunAt).toBe(createdAt + 10 * MINUTE);
  1320. const updatedAt = createdAt + 2 * MINUTE;
  1321. vi.setSystemTime(updatedAt);
  1322. const updated = await service.update(automation.automationId, {
  1323. cronExpr: "*/5 * * * *",
  1324. });
  1325. expect(updated?.scheduleRule).toMatchObject({
  1326. unit: "minute",
  1327. interval: 5,
  1328. anchorAt: updatedAt,
  1329. });
  1330. expect(updated?.nextRunAt).toBe(updatedAt + 5 * MINUTE);
  1331. const titleOnlyUpdatedAt = updatedAt + MINUTE;
  1332. vi.setSystemTime(titleOnlyUpdatedAt);
  1333. const titleOnly = await service.update(automation.automationId, {
  1334. title: "每5分钟问候",
  1335. scheduleRule: updated!.scheduleRule,
  1336. });
  1337. expect(titleOnly?.scheduleRule?.anchorAt).toBe(updatedAt);
  1338. const ruleUpdatedAt = titleOnlyUpdatedAt + MINUTE;
  1339. vi.setSystemTime(ruleUpdatedAt);
  1340. const ruleUpdated = await service.update(automation.automationId, {
  1341. cronExpr: "*/2 * * * *",
  1342. scheduleRule: { ...titleOnly!.scheduleRule!, interval: 2 },
  1343. });
  1344. expect(ruleUpdated?.scheduleRule?.anchorAt).toBe(ruleUpdatedAt);
  1345. expect(ruleUpdated?.nextRunAt).toBe(ruleUpdatedAt + 2 * MINUTE);
  1346. } finally {
  1347. vi.useRealTimers();
  1348. }
  1349. });
  1350. it("runNow:只创建 manual run,不修改原 cron 计划和生命周期", async () => {
  1351. const a = await repo.create(makeParams({ recurring: false, maxRuns: 1 }), {
  1352. nextRunAt: NOW + 10 * MINUTE,
  1353. });
  1354. await repo.setEnabled(a.automationId, false);
  1355. const claimed = await repo.runNow(a.automationId, { now: NOW });
  1356. const got = await repo.get(a.automationId);
  1357. expect(got?.nextRunAt).toBe(NOW + 10 * MINUTE);
  1358. expect(got?.runCount).toBe(0);
  1359. expect(got?.enabled).toBe(false);
  1360. expect(got?.lifecycleStatus).toBe("paused");
  1361. expect(await repo.claimDue(NOW)).toHaveLength(0);
  1362. const runs = await repo.listRuns(a.automationId);
  1363. expect(runs).toHaveLength(1);
  1364. expect(runs[0]!.trigger).toBe("manual");
  1365. expect(runs[0]!.runId).toContain(`${a.automationId}:manual:`);
  1366. expect(runs[0]!.scheduledAt).toBe(NOW);
  1367. expect(runs[0]!.attempts).toBe(1);
  1368. expect(claimed?.automation.automationId).toBe(a.automationId);
  1369. expect(claimed?.run.runId).toBe(runs[0]!.runId);
  1370. });
  1371. it("manual run 首次派发成功累计一次,重复回报幂等且不推进有限计划", async () => {
  1372. const a = await repo.create(makeParams({ recurring: false, maxRuns: 1 }), {
  1373. nextRunAt: NOW + 10 * MINUTE,
  1374. });
  1375. await repo.setEnabled(a.automationId, false);
  1376. const claimed = await repo.runNow(a.automationId, { now: NOW });
  1377. await repo.markManualRunDispatched({
  1378. runId: claimed!.run.runId,
  1379. sessionId: "manual-task",
  1380. dispatchedAt: NOW + 1,
  1381. });
  1382. await repo.markManualRunDispatched({
  1383. runId: claimed!.run.runId,
  1384. sessionId: "manual-task",
  1385. dispatchedAt: NOW + 2,
  1386. });
  1387. const got = await repo.get(a.automationId);
  1388. expect(got?.runCount).toBe(1);
  1389. expect(got?.lastRunAt).toBe(NOW + 1);
  1390. expect(got?.nextRunAt).toBe(NOW + 10 * MINUTE);
  1391. expect(got?.enabled).toBe(false);
  1392. expect(got?.lifecycleStatus).toBe("paused");
  1393. // prompt accepted/queued 后 claim 仍由真实 turn 终态释放,不能因计数提前解锁。
  1394. expect(await repo.runNow(a.automationId, { now: NOW + 3 })).toBeNull();
  1395. const runs = await repo.listRuns(a.automationId);
  1396. expect(runs[0]).toMatchObject({
  1397. dispatchStatus: "dispatched",
  1398. sessionId: "manual-task",
  1399. });
  1400. });
  1401. it("manual run 不消耗有限计划的定时派发次数", async () => {
  1402. const a = await repo.create(makeParams({ recurring: false, maxRuns: 3 }), {
  1403. nextRunAt: NOW + 10 * MINUTE,
  1404. });
  1405. for (let index = 0; index < 2; index += 1) {
  1406. const manual = await repo.runNow(a.automationId, { now: NOW + index });
  1407. await repo.markManualRunDispatched({
  1408. runId: manual!.run.runId,
  1409. sessionId: `manual-task-${index}`,
  1410. dispatchedAt: NOW + index,
  1411. });
  1412. await repo.releaseManualClaim(a.automationId, a.workspaceKey);
  1413. }
  1414. for (let scheduledCount = 1; scheduledCount <= 3; scheduledCount += 1) {
  1415. const scheduledAt = NOW + (9 + scheduledCount) * MINUTE;
  1416. expect(await repo.claimDue(scheduledAt)).toHaveLength(1);
  1417. await repo.markDispatched(a.automationId, {
  1418. dispatchedAt: scheduledAt,
  1419. nextRunAt: scheduledAt + MINUTE,
  1420. });
  1421. const got = await repo.get(a.automationId);
  1422. expect(got?.runCount).toBe(2 + scheduledCount);
  1423. expect(got?.lifecycleStatus).toBe(scheduledCount === 3 ? "completed" : "active");
  1424. expect(got?.enabled).toBe(scheduledCount !== 3);
  1425. }
  1426. });
  1427. it("编辑有限次数时只按定时派发次数重算生命周期", async () => {
  1428. const service = new AutomationService(repo);
  1429. const a = await repo.create(makeParams({ recurring: false, maxRuns: 3 }), {
  1430. nextRunAt: NOW + 10 * MINUTE,
  1431. });
  1432. for (let index = 0; index < 2; index += 1) {
  1433. const manual = await repo.runNow(a.automationId, { now: NOW + index });
  1434. await repo.markManualRunDispatched({
  1435. runId: manual!.run.runId,
  1436. dispatchedAt: NOW + index,
  1437. });
  1438. await repo.releaseManualClaim(a.automationId, a.workspaceKey);
  1439. }
  1440. await service.update(a.automationId, { maxRuns: 2 });
  1441. await expect(repo.get(a.automationId)).resolves.toMatchObject({
  1442. runCount: 2,
  1443. maxRuns: 2,
  1444. lifecycleStatus: "active",
  1445. enabled: true,
  1446. });
  1447. });
  1448. it("manual run 派发失败不累计运行次数", async () => {
  1449. const a = await repo.create(makeParams(), {
  1450. nextRunAt: NOW + 10 * MINUTE,
  1451. });
  1452. const claimed = await repo.runNow(a.automationId, { now: NOW });
  1453. await repo.markRunDispatch({
  1454. runId: claimed!.run.runId,
  1455. dispatchStatus: "failed_to_dispatch",
  1456. error: "dispatch failed",
  1457. });
  1458. const got = await repo.get(a.automationId);
  1459. expect(got?.runCount).toBe(0);
  1460. expect(got?.lastRunAt).toBeUndefined();
  1461. });
  1462. it("runNow:连续立即运行只认领一次,释放后才能再次创建 manual run", async () => {
  1463. const a = await repo.create(makeParams(), {
  1464. nextRunAt: NOW + 10 * MINUTE,
  1465. });
  1466. const first = await repo.runNow(a.automationId, { now: NOW });
  1467. const second = await repo.runNow(a.automationId, { now: NOW + 1 });
  1468. expect(first?.automation.automationId).toBe(a.automationId);
  1469. expect(second).toBeNull();
  1470. expect(await repo.listRuns(a.automationId)).toHaveLength(1);
  1471. expect(await repo.claimDue(NOW)).toHaveLength(0);
  1472. expect(await repo.claimManualRuns(NOW + 1)).toHaveLength(0);
  1473. // sendPrompt accepted/queued 只回写 dispatched;在 turn 终态前仍必须持有 claim。
  1474. await repo.markManualRunDispatched({
  1475. runId: first!.run.runId,
  1476. sessionId: "busy-task",
  1477. dispatchedAt: NOW + 2,
  1478. });
  1479. expect(await repo.runNow(a.automationId, { now: NOW + 3 })).toBeNull();
  1480. await repo.releaseManualClaim(a.automationId, a.workspaceKey);
  1481. const third = await repo.runNow(a.automationId, { now: NOW + 4 });
  1482. expect(third?.automation.automationId).toBe(a.automationId);
  1483. expect(await repo.listRuns(a.automationId)).toHaveLength(2);
  1484. });
  1485. it("touchManualClaim:长时间 queued manual run 续租后不会被 stale 回收", async () => {
  1486. const a = await repo.create(makeParams(), {
  1487. nextRunAt: NOW + 20 * MINUTE,
  1488. });
  1489. expect(await repo.runNow(a.automationId, { now: NOW })).not.toBeNull();
  1490. vi.useFakeTimers();
  1491. vi.setSystemTime(NOW + CLAIM_STALE_MS - MINUTE);
  1492. try {
  1493. await repo.touchManualClaim(a.automationId, a.workspaceKey);
  1494. } finally {
  1495. vi.useRealTimers();
  1496. }
  1497. expect(await repo.runNow(a.automationId, { now: NOW + CLAIM_STALE_MS + 1 })).toBeNull();
  1498. expect(await repo.listRuns(a.automationId)).toHaveLength(1);
  1499. });
  1500. it("claimManualRuns:正常路径不认领 host 直派任务,仅在超时后崩溃恢复", async () => {
  1501. const a = await repo.create(makeParams(), {
  1502. nextRunAt: NOW + 10 * MINUTE,
  1503. });
  1504. await repo.runNow(a.automationId, { now: NOW });
  1505. expect(await repo.claimManualRuns(NOW + 1)).toHaveLength(0);
  1506. const claimed = await repo.claimManualRuns(NOW + CLAIM_STALE_MS + 1);
  1507. expect(claimed).toHaveLength(1);
  1508. expect(claimed[0]!.automation.automationId).toBe(a.automationId);
  1509. expect(claimed[0]!.run.trigger).toBe("manual");
  1510. expect(claimed[0]!.run.attempts).toBe(2);
  1511. expect(await repo.claimManualRuns(NOW + CLAIM_STALE_MS + 2)).toHaveLength(0);
  1512. await repo.markManualRunDispatched({
  1513. runId: claimed[0]!.run.runId,
  1514. sessionId: "task-1",
  1515. dispatchedAt: NOW + CLAIM_STALE_MS + 2,
  1516. });
  1517. await repo.releaseManualClaim(a.automationId, a.workspaceKey);
  1518. const got = await repo.get(a.automationId);
  1519. expect(got?.runCount).toBe(1);
  1520. expect(got?.lastRunAt).toBe(NOW + CLAIM_STALE_MS + 2);
  1521. expect(got?.nextRunAt).toBe(NOW + 10 * MINUTE);
  1522. expect(got?.lifecycleStatus).toBe("active");
  1523. const runs = await repo.listRuns(a.automationId);
  1524. expect(runs[0]!.dispatchStatus).toBe("dispatched");
  1525. expect(runs[0]!.sessionId).toBe("task-1");
  1526. });
  1527. it("claimDue:僵尸认领(持有者崩溃)超过 CLAIM_STALE 后被回收重认领", async () => {
  1528. const a = await repo.create(makeParams(), { nextRunAt: NOW - 1 });
  1529. await repo.claimDue(NOW); // 认领后 running=1、claimed_at=NOW
  1530. // 未超时前不回收(仍 running)。
  1531. expect(await repo.claimDue(NOW + CLAIM_STALE_MS - 1)).toHaveLength(0);
  1532. // 超过 CLAIM_STALE 后回收并重新认领。
  1533. const reclaimed = await repo.claimDue(NOW + CLAIM_STALE_MS + 1);
  1534. expect(reclaimed.map((x) => x.automationId)).toEqual([a.automationId]);
  1535. });
  1536. it("delete + deleteRun:删除 automation 与单条运行记录", async () => {
  1537. const a = await repo.create(makeParams(), { nextRunAt: NOW - 1 });
  1538. const runId = `${a.automationId}:${NOW}`;
  1539. await repo.upsertRunClaimed({
  1540. runId,
  1541. automationId: a.automationId,
  1542. workspaceKey: "/tmp/ws",
  1543. scheduledAt: NOW,
  1544. trigger: "schedule",
  1545. });
  1546. await repo.deleteRun(runId);
  1547. expect(await repo.listRuns(a.automationId)).toHaveLength(0);
  1548. await repo.delete(a.automationId);
  1549. expect(await repo.get(a.automationId)).toBeNull();
  1550. });
  1551. });
  1552. describe("automation workspace 隔离", () => {
  1553. let tempDir: string | null = null;
  1554. let dbPath: string;
  1555. let repo: AutomationRepo;
  1556. const KEY_A = "/tmp/ws-a";
  1557. const KEY_B = "/tmp/ws-b";
  1558. beforeEach(() => {
  1559. tempDir = mkdtempSync(join(tmpdir(), "zcode-automation-iso-"));
  1560. dbPath = buildTempDbPath(tempDir);
  1561. repo = new AutomationRepo(dbPath);
  1562. });
  1563. afterEach(() => {
  1564. repo.close();
  1565. if (tempDir) {
  1566. rmSync(tempDir, { recursive: true, force: true });
  1567. tempDir = null;
  1568. }
  1569. });
  1570. it("repo:跨 workspace 的 get/update/delete/setEnabled/restart/runNow 均不生效且不改原记录", async () => {
  1571. const a = await repo.create(makeParams({ workspacePath: KEY_A }), {
  1572. nextRunAt: NOW + MINUTE,
  1573. });
  1574. // 错误 workspace 读不到;正确 workspace 读得到。
  1575. expect(await repo.get(a.automationId, KEY_B)).toBeNull();
  1576. expect((await repo.get(a.automationId, KEY_A))?.automationId).toBe(a.automationId);
  1577. // update:错误 workspace 返回 null,字段不变。
  1578. expect(await repo.update(a.automationId, { title: "hacked" }, undefined, KEY_B)).toBeNull();
  1579. expect((await repo.get(a.automationId, KEY_A))?.title).toBe(a.title);
  1580. // setEnabled:错误 workspace 不改 enabled。
  1581. await repo.setEnabled(a.automationId, false, KEY_B);
  1582. expect((await repo.get(a.automationId, KEY_A))?.enabled).toBe(true);
  1583. // restart:先在正确 workspace 置 paused,再用错误 workspace restart 应无效(仍 paused)。
  1584. await repo.setEnabled(a.automationId, false, KEY_A);
  1585. await repo.restart(a.automationId, { nextRunAt: NOW + 2 * MINUTE }, KEY_B);
  1586. expect((await repo.get(a.automationId, KEY_A))?.lifecycleStatus).toBe("paused");
  1587. // runNow:错误 workspace 返回 null 且不落 run。
  1588. expect(await repo.runNow(a.automationId, { now: NOW }, KEY_B)).toBeNull();
  1589. expect(await repo.listRuns(a.automationId, KEY_A)).toHaveLength(0);
  1590. // delete:错误 workspace 不删;正确 workspace 可删。
  1591. await repo.delete(a.automationId, KEY_B);
  1592. expect(await repo.get(a.automationId, KEY_A)).not.toBeNull();
  1593. await repo.delete(a.automationId, KEY_A);
  1594. expect(await repo.get(a.automationId, KEY_A)).toBeNull();
  1595. });
  1596. it("repo:run 的 listRuns/deleteRun 也按 workspace 隔离", async () => {
  1597. const a = await repo.create(makeParams({ workspacePath: KEY_A }), {
  1598. nextRunAt: NOW + MINUTE,
  1599. });
  1600. const claimed = await repo.runNow(a.automationId, { now: NOW }, KEY_A);
  1601. expect(claimed).not.toBeNull();
  1602. const runId = claimed!.run.runId;
  1603. expect(await repo.listRuns(a.automationId, KEY_B)).toHaveLength(0);
  1604. await repo.deleteRun(runId, KEY_B);
  1605. expect(await repo.listRuns(a.automationId, KEY_A)).toHaveLength(1);
  1606. await repo.deleteRun(runId, KEY_A);
  1607. expect(await repo.listRuns(a.automationId, KEY_A)).toHaveLength(0);
  1608. });
  1609. it("repo:getRun 可按 runId 找回 manual run 的 workspaceKey", async () => {
  1610. const a = await repo.create(makeParams({ workspacePath: KEY_A }), {
  1611. nextRunAt: NOW + MINUTE,
  1612. });
  1613. const claimed = await repo.runNow(a.automationId, { now: NOW }, KEY_A);
  1614. const run = await repo.getRun(claimed!.run.runId);
  1615. expect(run?.automationId).toBe(a.automationId);
  1616. expect(run?.workspaceKey).toBe(KEY_A);
  1617. });
  1618. it("repo:releaseManualClaim 只释放同 workspace 的立即运行锁", async () => {
  1619. const a = await repo.create(makeParams({ workspacePath: KEY_A }), {
  1620. nextRunAt: NOW + MINUTE,
  1621. });
  1622. expect(await repo.runNow(a.automationId, { now: NOW }, KEY_A)).not.toBeNull();
  1623. await repo.releaseManualClaim(a.automationId, KEY_B);
  1624. expect(await repo.runNow(a.automationId, { now: NOW + 1 }, KEY_A)).toBeNull();
  1625. await repo.releaseManualClaim(a.automationId, KEY_A);
  1626. expect(await repo.runNow(a.automationId, { now: NOW + 2 }, KEY_A)).not.toBeNull();
  1627. });
  1628. it("repo:相同 workspacePath 但不同 workspaceIdentity 互相隔离", async () => {
  1629. // workspaceKey = workspaceIdentity?.trim() || workspacePath。
  1630. const a = await repo.create(
  1631. makeParams({ workspacePath: "/tmp/shared", workspaceIdentity: "remote-A" }),
  1632. { nextRunAt: NOW + MINUTE },
  1633. );
  1634. expect(await repo.get(a.automationId, "remote-B")).toBeNull();
  1635. expect((await repo.get(a.automationId, "remote-A"))?.automationId).toBe(a.automationId);
  1636. await repo.delete(a.automationId, "remote-B");
  1637. expect(await repo.get(a.automationId, "remote-A")).not.toBeNull();
  1638. });
  1639. it("service:scope 为 workspace B 时无法操作 workspace A 的任务", async () => {
  1640. const service = new AutomationService(repo);
  1641. const a = await service.create(makeParams({ workspacePath: KEY_A }));
  1642. const scopeB = { workspacePath: KEY_B };
  1643. expect(await service.get(a.automationId, scopeB)).toBeNull();
  1644. expect(await service.update(a.automationId, { title: "x" }, scopeB)).toBeNull();
  1645. await service.delete(a.automationId, scopeB);
  1646. await service.setEnabled(a.automationId, false, scopeB);
  1647. await service.restart(a.automationId, scopeB);
  1648. expect(await service.runNow(a.automationId, scopeB)).toBeNull();
  1649. // A 仍存在且未被改动。
  1650. const stillA = await service.get(a.automationId, { workspacePath: KEY_A });
  1651. expect(stillA?.title).toBe(a.title);
  1652. expect(stillA?.enabled).toBe(true);
  1653. });
  1654. });