automationRepo.test.ts 67 KB

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