automation-port.test.ts 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. import { describe, expect, it, vi } from "vitest";
  2. import { AutomationCreateLimitError, isAutomationCreateLimitError } from "@zcode/contracts";
  3. import { AUTOMATION_CREATE_LIMIT_ERROR_CODE, isHighspeedProviderId, zcodeProtocolMethods } from "@zcode/shared";
  4. import {
  5. AUTOMATION_CREATE_BOUND_SESSION_CHECK_ERROR,
  6. AUTOMATION_CREATE_FROM_AUTOMATION_RUN_ERROR,
  7. AUTOMATION_CREATE_IN_BOUND_SESSION_ERROR,
  8. createProtocolAutomationPort,
  9. } from "../src/zcode-protocol/automation-port.js";
  10. import {
  11. ProtocolRequestError,
  12. type ZCodeProtocolAgentServerContext,
  13. } from "../src/zcode-protocol/server-types.js";
  14. describe("createProtocolAutomationPort", () => {
  15. it("拒绝 automation 执行 turn 里再次 CronCreate,且不调用 automation/create", async () => {
  16. const requestClient = vi.fn();
  17. const port = createProtocolAutomationPort({
  18. requestClient,
  19. sessions: new Map([
  20. [
  21. "session-1",
  22. {
  23. activeAutomationId: "automation-parent",
  24. app: {
  25. runtime: {
  26. getSessionModelSelection: () => ({ providerId: "zai-api", modelId: "GLM-5" }),
  27. },
  28. getModel: () => "zai-api/GLM-5",
  29. getMode: () => "yolo",
  30. getThoughtLevel: () => "nothink",
  31. setCustomSessionTitle: vi.fn(async () => undefined),
  32. },
  33. traceContext: { traceId: "trace-session-1" },
  34. },
  35. ],
  36. ]),
  37. } as unknown as ZCodeProtocolAgentServerContext);
  38. await expect(
  39. port.create(
  40. {
  41. cron: "*/5 * * * *",
  42. delayMinutes: null,
  43. prompt: "nested",
  44. title: "nested",
  45. },
  46. { sessionId: "session-1" },
  47. ),
  48. ).rejects.toThrow(AUTOMATION_CREATE_FROM_AUTOMATION_RUN_ERROR);
  49. expect(requestClient).not.toHaveBeenCalled();
  50. });
  51. it("拒绝在已归属定时任务的会话里再次 CronCreate(按 targetTaskId 兜底),且不调用 automation/create", async () => {
  52. // Bugfix 回归:桌面交互输入直连 CLI,绕过 host adapter 的 toolDenylist 注入;用户在一个已归属
  53. // 定时任务的会话里继续输入时,CronCreate 仍会被注册。这里在创建入口按 targetTaskId 兜底拒绝。
  54. const requestClient = vi.fn(async (method: string) => {
  55. if (method === zcodeProtocolMethods.automationCheckTaskBinding) {
  56. return { bound: true };
  57. }
  58. throw new Error(`unexpected method ${method}`);
  59. });
  60. const port = createProtocolAutomationPort({
  61. requestClient,
  62. sessions: new Map([
  63. [
  64. "session-1",
  65. {
  66. app: {
  67. runtime: { getSessionModelSelection: () => undefined },
  68. getModel: () => undefined,
  69. getMode: () => undefined,
  70. getThoughtLevel: () => undefined,
  71. setCustomSessionTitle: vi.fn(async () => undefined),
  72. },
  73. traceContext: { traceId: "trace-session-1" },
  74. },
  75. ],
  76. ]),
  77. } as unknown as ZCodeProtocolAgentServerContext);
  78. await expect(
  79. port.create(
  80. {
  81. cron: "*/5 * * * *",
  82. delayMinutes: null,
  83. prompt: "再帮我建一个",
  84. title: "再帮我建一个",
  85. },
  86. { sessionId: "session-1" },
  87. ),
  88. ).rejects.toThrow(AUTOMATION_CREATE_IN_BOUND_SESSION_ERROR);
  89. expect(requestClient).toHaveBeenCalledWith(
  90. zcodeProtocolMethods.automationCheckTaskBinding,
  91. { targetTaskId: "session-1" },
  92. expect.anything(),
  93. );
  94. expect(requestClient).not.toHaveBeenCalledWith(
  95. zcodeProtocolMethods.automationList,
  96. expect.anything(),
  97. expect.anything(),
  98. );
  99. expect(requestClient).not.toHaveBeenCalledWith(
  100. zcodeProtocolMethods.automationCreate,
  101. expect.anything(),
  102. expect.anything(),
  103. );
  104. });
  105. it.each([undefined, "yolo", "guarded"] as const)(
  106. "普通会话创建 automation 保留显式模式 %s,不迁移未设置值",
  107. async (mode) => {
  108. const requestClient = vi.fn(async (method: string) => {
  109. if (method === zcodeProtocolMethods.automationCheckTaskBinding) return { bound: false };
  110. if (method === zcodeProtocolMethods.automationCreate) {
  111. return {
  112. automation: {
  113. automationId: "automation-new",
  114. title: "每5分钟提醒",
  115. cronExpr: "*/5 * * * *",
  116. prompt: "提醒我",
  117. enabled: true,
  118. lifecycleStatus: "active" as const,
  119. runCount: 0,
  120. recurring: true,
  121. mode,
  122. },
  123. };
  124. }
  125. throw new Error(`unexpected method ${method}`);
  126. });
  127. const port = createProtocolAutomationPort({
  128. requestClient,
  129. sessions: new Map([
  130. [
  131. "session-1",
  132. {
  133. app: {
  134. runtime: { getSessionModelSelection: () => undefined },
  135. getModel: () => undefined,
  136. getMode: () => mode,
  137. getThoughtLevel: () => undefined,
  138. setCustomSessionTitle: vi.fn(async () => undefined),
  139. },
  140. traceContext: { traceId: "trace-session-1" },
  141. },
  142. ],
  143. ]),
  144. } as unknown as ZCodeProtocolAgentServerContext);
  145. await expect(
  146. port.create(
  147. {
  148. cron: "*/5 * * * *",
  149. delayMinutes: null,
  150. prompt: "提醒我",
  151. title: "每5分钟提醒",
  152. },
  153. { sessionId: "session-1" },
  154. ),
  155. ).resolves.toEqual(expect.objectContaining({ automationId: "automation-new", mode }));
  156. expect(requestClient).toHaveBeenCalledWith(
  157. zcodeProtocolMethods.automationCreate,
  158. expect.objectContaining({ targetTaskId: "session-1", ...(mode ? { mode } : {}) }),
  159. expect.anything(),
  160. );
  161. expect(requestClient).not.toHaveBeenCalledWith(
  162. zcodeProtocolMethods.automationList,
  163. expect.anything(),
  164. expect.anything(),
  165. );
  166. },
  167. );
  168. it("CronCreate、CronUpdate 与 CronList 透传 interval carrier 并保留权威 scheduleRule", async () => {
  169. const minuteRule = {
  170. unit: "minute" as const,
  171. interval: 200,
  172. hour: 10,
  173. minute: 30,
  174. anchorAt: 1_700_000_000_000,
  175. };
  176. const requestClient = vi.fn(async (method: string) => {
  177. if (method === zcodeProtocolMethods.automationCheckTaskBinding) return { bound: false };
  178. if (method === zcodeProtocolMethods.automationCreate) {
  179. return {
  180. automation: {
  181. automationId: "automation-interval",
  182. title: "每200分钟提醒",
  183. cronExpr: "* * * * *",
  184. prompt: "提醒我",
  185. enabled: true,
  186. lifecycleStatus: "active" as const,
  187. runCount: 0,
  188. recurring: true,
  189. scheduleRule: minuteRule,
  190. },
  191. };
  192. }
  193. if (method === zcodeProtocolMethods.automationUpdate) {
  194. return {
  195. automation: {
  196. automationId: "automation-interval",
  197. title: "每200小时的第49分提醒",
  198. cronExpr: "49 * * * *",
  199. prompt: "提醒我",
  200. enabled: true,
  201. lifecycleStatus: "active" as const,
  202. runCount: 0,
  203. recurring: true,
  204. scheduleRule: {
  205. unit: "hourly" as const,
  206. interval: 200,
  207. hour: 0,
  208. minute: 49,
  209. anchorAt: 1_700_000_060_000,
  210. },
  211. },
  212. };
  213. }
  214. if (method === zcodeProtocolMethods.automationList) {
  215. return {
  216. automations: [
  217. {
  218. automationId: "automation-interval",
  219. title: "每200小时的第49分提醒",
  220. cronExpr: "49 * * * *",
  221. prompt: "提醒我",
  222. enabled: true,
  223. lifecycleStatus: "active" as const,
  224. runCount: 0,
  225. recurring: true,
  226. scheduleRule: {
  227. unit: "hourly" as const,
  228. interval: 200,
  229. hour: 0,
  230. minute: 49,
  231. anchorAt: 1_700_000_060_000,
  232. },
  233. },
  234. ],
  235. };
  236. }
  237. throw new Error(`unexpected method ${method}`);
  238. });
  239. const port = createProtocolAutomationPort({
  240. requestClient,
  241. sessions: new Map([
  242. [
  243. "session-1",
  244. {
  245. app: {
  246. runtime: { getSessionModelSelection: () => undefined },
  247. getModel: () => undefined,
  248. getMode: () => undefined,
  249. getThoughtLevel: () => undefined,
  250. setCustomSessionTitle: vi.fn(async () => undefined),
  251. },
  252. traceContext: { traceId: "trace-session-1" },
  253. },
  254. ],
  255. ]),
  256. } as unknown as ZCodeProtocolAgentServerContext);
  257. const created = await port.create(
  258. {
  259. cron: "* * * * *",
  260. delayMinutes: null,
  261. prompt: "提醒我",
  262. title: "每200分钟提醒",
  263. intervalUnit: "minute",
  264. interval: 200,
  265. },
  266. { sessionId: "session-1" },
  267. );
  268. const updated = await port.update({
  269. id: "automation-interval",
  270. cron: "49 * * * *",
  271. intervalUnit: "hourly",
  272. interval: 200,
  273. });
  274. const listed = await port.list();
  275. expect(requestClient).toHaveBeenCalledWith(
  276. zcodeProtocolMethods.automationCreate,
  277. expect.objectContaining({
  278. intervalUnit: "minute",
  279. interval: 200,
  280. recurring: true,
  281. }),
  282. expect.anything(),
  283. );
  284. expect(requestClient).toHaveBeenCalledWith(
  285. zcodeProtocolMethods.automationUpdate,
  286. expect.objectContaining({
  287. intervalUnit: "hourly",
  288. interval: 200,
  289. recurring: true,
  290. maxRuns: null,
  291. }),
  292. expect.anything(),
  293. );
  294. expect(created.scheduleRule).toEqual(minuteRule);
  295. expect(updated.scheduleRule).toMatchObject({ unit: "hourly", interval: 200, minute: 49 });
  296. expect(listed[0]?.scheduleRule).toMatchObject({ unit: "hourly", interval: 200, minute: 49 });
  297. });
  298. it("将当前 Bot turn 的回推目标注入 automation/create,普通模型输入不能自行指定", async () => {
  299. const requestClient = vi.fn(async (method: string) => {
  300. if (method === zcodeProtocolMethods.automationCheckTaskBinding) return { bound: false };
  301. if (method === zcodeProtocolMethods.automationCreate) {
  302. return {
  303. automation: {
  304. automationId: "automation-bot",
  305. title: "Bot 日报",
  306. cronExpr: "0 9 * * *",
  307. prompt: "生成日报",
  308. enabled: true,
  309. lifecycleStatus: "active" as const,
  310. runCount: 0,
  311. recurring: true,
  312. },
  313. };
  314. }
  315. throw new Error(`unexpected method ${method}`);
  316. });
  317. const botDeliveryTarget = {
  318. provider: "feishu" as const,
  319. botId: "bot-feishu",
  320. providerUserId: "chat-1",
  321. chatType: "group" as const,
  322. };
  323. const port = createProtocolAutomationPort(
  324. { requestClient, sessions: new Map() } as unknown as ZCodeProtocolAgentServerContext,
  325. () =>
  326. ({
  327. activeBotDeliveryTarget: botDeliveryTarget,
  328. app: {
  329. runtime: { getSessionModelSelection: () => undefined },
  330. sessionId: "session-1",
  331. getModel: () => undefined,
  332. getMode: () => undefined,
  333. getThoughtLevel: () => undefined,
  334. setCustomSessionTitle: vi.fn(async () => undefined),
  335. },
  336. traceContext: { traceId: "trace-session-1" },
  337. }) as never,
  338. );
  339. await port.create(
  340. { cron: "0 9 * * *", delayMinutes: null, prompt: "生成日报", title: "Bot 日报" },
  341. { sessionId: "session-1" },
  342. );
  343. expect(requestClient).toHaveBeenCalledWith(
  344. zcodeProtocolMethods.automationCreate,
  345. expect.objectContaining({ botDeliveryTarget }),
  346. expect.anything(),
  347. );
  348. });
  349. it("旧 Host 缺少归属查询方法时回退 automation/list,并允许未绑定会话 CronCreate", async () => {
  350. const requestClient = vi.fn(async (method: string) => {
  351. if (method === zcodeProtocolMethods.automationCheckTaskBinding) {
  352. throw new ProtocolRequestError(-32601, "Method not found");
  353. }
  354. if (method === zcodeProtocolMethods.automationList) {
  355. return {
  356. automations: [
  357. {
  358. automationId: "automation-other",
  359. title: "其他会话任务",
  360. cronExpr: "0 8 * * *",
  361. prompt: "提醒其他会话",
  362. targetTaskId: "session-other",
  363. enabled: true,
  364. lifecycleStatus: "active" as const,
  365. runCount: 0,
  366. recurring: true,
  367. },
  368. ],
  369. };
  370. }
  371. if (method === zcodeProtocolMethods.automationCreate) {
  372. return {
  373. automation: {
  374. automationId: "automation-new",
  375. title: "每5分钟提醒",
  376. cronExpr: "*/5 * * * *",
  377. prompt: "提醒我",
  378. targetTaskId: "session-1",
  379. enabled: true,
  380. lifecycleStatus: "active" as const,
  381. runCount: 0,
  382. recurring: true,
  383. },
  384. };
  385. }
  386. throw new Error(`unexpected method ${method}`);
  387. });
  388. const port = createProtocolAutomationPort({
  389. requestClient,
  390. sessions: new Map(),
  391. } as unknown as ZCodeProtocolAgentServerContext);
  392. await expect(
  393. port.create(
  394. {
  395. cron: "*/5 * * * *",
  396. delayMinutes: null,
  397. prompt: "提醒我",
  398. title: "每5分钟提醒",
  399. },
  400. { sessionId: "session-1" },
  401. ),
  402. ).resolves.toEqual(expect.objectContaining({ automationId: "automation-new" }));
  403. expect(requestClient).toHaveBeenCalledWith(
  404. zcodeProtocolMethods.automationList,
  405. {},
  406. expect.anything(),
  407. );
  408. expect(requestClient).toHaveBeenCalledWith(
  409. zcodeProtocolMethods.automationCreate,
  410. expect.objectContaining({ targetTaskId: "session-1" }),
  411. expect.anything(),
  412. );
  413. });
  414. it("旧 Host 回退列表命中当前会话绑定时仍拒绝 CronCreate", async () => {
  415. const requestClient = vi.fn(async (method: string) => {
  416. if (method === zcodeProtocolMethods.automationCheckTaskBinding) {
  417. throw new ProtocolRequestError(-32601, "Method not found");
  418. }
  419. if (method === zcodeProtocolMethods.automationList) {
  420. return {
  421. automations: [
  422. {
  423. automationId: "automation-owner",
  424. title: "当前会话任务",
  425. cronExpr: "*/10 * * * *",
  426. prompt: "提醒当前会话",
  427. targetTaskId: "session-1",
  428. enabled: true,
  429. lifecycleStatus: "active" as const,
  430. runCount: 0,
  431. recurring: true,
  432. },
  433. ],
  434. };
  435. }
  436. throw new Error(`unexpected method ${method}`);
  437. });
  438. const port = createProtocolAutomationPort({
  439. requestClient,
  440. sessions: new Map(),
  441. } as unknown as ZCodeProtocolAgentServerContext);
  442. await expect(
  443. port.create(
  444. {
  445. cron: "*/5 * * * *",
  446. delayMinutes: null,
  447. prompt: "再建一个任务",
  448. title: "再建一个任务",
  449. },
  450. { sessionId: "session-1" },
  451. ),
  452. ).rejects.toThrow(AUTOMATION_CREATE_IN_BOUND_SESSION_ERROR);
  453. expect(requestClient).not.toHaveBeenCalledWith(
  454. zcodeProtocolMethods.automationCreate,
  455. expect.anything(),
  456. expect.anything(),
  457. );
  458. });
  459. it("相对时间通过 relativeDelayMinutes 交给 Host,模型不再计算绝对 cron", async () => {
  460. const requestClient = vi.fn(async (method: string) => {
  461. if (method === zcodeProtocolMethods.automationCreate) {
  462. return {
  463. automation: {
  464. automationId: "automation-relative",
  465. title: "3分钟后接水提醒",
  466. cronExpr: "47 14 28 7 *",
  467. prompt: "提醒我接水",
  468. enabled: true,
  469. lifecycleStatus: "active" as const,
  470. nextRunAt: 1_785_221_068_000,
  471. runCount: 0,
  472. recurring: false,
  473. },
  474. };
  475. }
  476. throw new Error(`unexpected method ${method}`);
  477. });
  478. const port = createProtocolAutomationPort({
  479. requestClient,
  480. sessions: new Map(),
  481. } as unknown as ZCodeProtocolAgentServerContext);
  482. await port.create({
  483. delayMinutes: 3,
  484. prompt: "提醒我接水",
  485. title: "3分钟后接水提醒",
  486. recurring: false,
  487. });
  488. expect(requestClient).toHaveBeenCalledWith(
  489. zcodeProtocolMethods.automationCreate,
  490. expect.objectContaining({
  491. cronExpr: "* * * * *",
  492. relativeDelayMinutes: 3,
  493. recurring: false,
  494. }),
  495. expect.anything(),
  496. );
  497. });
  498. it("省略 delayMinutes 的普通 cron 创建保持 recurring 默认,不误走相对分支", async () => {
  499. const requestClient = vi.fn(async (method: string) => {
  500. if (method === zcodeProtocolMethods.automationCreate) {
  501. return {
  502. automation: {
  503. automationId: "automation-plain",
  504. title: "每天9点喝水提醒",
  505. cronExpr: "0 9 * * *",
  506. prompt: "提醒我喝水",
  507. enabled: true,
  508. lifecycleStatus: "active" as const,
  509. runCount: 0,
  510. recurring: true,
  511. },
  512. };
  513. }
  514. throw new Error(`unexpected method ${method}`);
  515. });
  516. const port = createProtocolAutomationPort({
  517. requestClient,
  518. sessions: new Map(),
  519. } as unknown as ZCodeProtocolAgentServerContext);
  520. // Bug 原因:`delayMinutes !== null` 判定下,省略字段(很多 provider 不稳定保留
  521. // null 字段)会被误当成相对任务,把普通 recurring 调度错建成一次性。
  522. await port.create({
  523. cron: "0 9 * * *",
  524. prompt: "提醒我喝水",
  525. title: "每天9点喝水提醒",
  526. });
  527. expect(requestClient).toHaveBeenCalledWith(
  528. zcodeProtocolMethods.automationCreate,
  529. expect.objectContaining({ cronExpr: "0 9 * * *", recurring: true }),
  530. expect.anything(),
  531. );
  532. const createPayload = requestClient.mock.calls.find(
  533. ([method]) => method === zcodeProtocolMethods.automationCreate,
  534. )?.[1] as Record<string, unknown>;
  535. expect(createPayload).not.toHaveProperty("relativeDelayMinutes");
  536. });
  537. it("将完整 task mode 归一化为 Cron 工具兼容的权限模式", async () => {
  538. const modeCases = [
  539. ["default", "build"],
  540. ["auto", "build"],
  541. ["acceptEdits", "build"],
  542. ["autoEdit", "build"],
  543. ["dontAsk", "yolo"],
  544. ["bypassPermissions", "yolo"],
  545. ["build", "build"],
  546. ["edit", "edit"],
  547. ["plan", "plan"],
  548. ["yolo", "yolo"],
  549. ] as const;
  550. const requestClient = vi.fn(async (method: string) => {
  551. if (method === zcodeProtocolMethods.automationList) {
  552. return {
  553. automations: modeCases.map(([mode], index) => ({
  554. automationId: `automation-${index}`,
  555. title: `automation ${index}`,
  556. cronExpr: "0 9 * * *",
  557. prompt: "生成晨报",
  558. mode,
  559. enabled: true,
  560. lifecycleStatus: "active" as const,
  561. runCount: 0,
  562. recurring: true,
  563. })),
  564. };
  565. }
  566. throw new Error(`unexpected method ${method}`);
  567. });
  568. const port = createProtocolAutomationPort({
  569. requestClient,
  570. sessions: new Map(),
  571. } as unknown as ZCodeProtocolAgentServerContext);
  572. const automations = await port.list();
  573. expect(automations.map(({ mode }) => mode)).toEqual(
  574. modeCases.map(([, expectedMode]) => expectedMode),
  575. );
  576. });
  577. it("将 automation/create 上限错误映射为 CLI 稳定领域错误", async () => {
  578. const requestClient = vi.fn(async (method: string) => {
  579. if (method === zcodeProtocolMethods.automationCheckTaskBinding) return { bound: false };
  580. if (method === zcodeProtocolMethods.automationCreate) {
  581. throw new Error(
  582. `[${AUTOMATION_CREATE_LIMIT_ERROR_CODE}] At most 20 automations may be retained.`,
  583. );
  584. }
  585. throw new Error(`unexpected method ${method}`);
  586. });
  587. const port = createProtocolAutomationPort({
  588. requestClient,
  589. sessions: new Map(),
  590. } as unknown as ZCodeProtocolAgentServerContext);
  591. const error = await port
  592. .create(
  593. { cron: "0 9 * * *", prompt: "生成晨报", title: "每天 9 点晨报" },
  594. { sessionId: "session-1" },
  595. )
  596. .catch((caught: unknown) => caught);
  597. expect(error).toBeInstanceOf(AutomationCreateLimitError);
  598. expect(isAutomationCreateLimitError(error)).toBe(true);
  599. });
  600. it("automation 归属查询失败时 fail-closed,且不调用 automation/create", async () => {
  601. const logger = { warn: vi.fn() };
  602. const requestClient = vi.fn(async (method: string) => {
  603. if (method === zcodeProtocolMethods.automationCheckTaskBinding) {
  604. throw new Error("automation storage unavailable");
  605. }
  606. throw new Error(`unexpected method ${method}`);
  607. });
  608. const port = createProtocolAutomationPort({
  609. logger,
  610. requestClient,
  611. sessions: new Map(),
  612. } as unknown as ZCodeProtocolAgentServerContext);
  613. await expect(
  614. port.create(
  615. {
  616. cron: "*/5 * * * *",
  617. delayMinutes: null,
  618. prompt: "提醒我",
  619. title: "每5分钟提醒",
  620. },
  621. { sessionId: "session-unknown" },
  622. ),
  623. ).rejects.toThrow(AUTOMATION_CREATE_BOUND_SESSION_CHECK_ERROR);
  624. expect(logger.warn).toHaveBeenCalledWith(
  625. "Failed to check bound automations before CronCreate",
  626. expect.objectContaining({
  627. event: "automation.create.bound_session_check.failed",
  628. sessionId: "session-unknown",
  629. }),
  630. );
  631. expect(requestClient).not.toHaveBeenCalledWith(
  632. zcodeProtocolMethods.automationList,
  633. expect.anything(),
  634. expect.anything(),
  635. );
  636. expect(requestClient).not.toHaveBeenCalledWith(
  637. zcodeProtocolMethods.automationCreate,
  638. expect.anything(),
  639. expect.anything(),
  640. );
  641. });
  642. it("CronCreate 协议请求继承活跃会话的模型、权限和思考等级", async () => {
  643. const setCustomSessionTitle = vi.fn(async () => undefined);
  644. const requestClient = vi.fn(async () => ({
  645. automation: {
  646. automationId: "automation-1",
  647. title: "daily report",
  648. cronExpr: "0 9 * * *",
  649. prompt: "write daily report",
  650. model: "zai-api/GLM-5",
  651. provider: "glm",
  652. mode: "yolo" as const,
  653. thoughtLevel: "nothink",
  654. enabled: true,
  655. lifecycleStatus: "active" as const,
  656. runCount: 0,
  657. recurring: true,
  658. },
  659. }));
  660. const port = createProtocolAutomationPort({
  661. requestClient,
  662. sessions: new Map([
  663. [
  664. "session-1",
  665. {
  666. app: {
  667. runtime: {
  668. getSessionModelSelection: () => ({
  669. providerId: "zai-api",
  670. modelId: "GLM-5",
  671. options: { reasoningLevel: "nothink" },
  672. }),
  673. },
  674. getModel: () => "zai-api/GLM-5",
  675. getMode: () => "yolo",
  676. getThoughtLevel: () => "nothink",
  677. setCustomSessionTitle,
  678. },
  679. traceContext: { traceId: "trace-session-1" },
  680. },
  681. ],
  682. ]),
  683. } as unknown as ZCodeProtocolAgentServerContext);
  684. await port.create(
  685. {
  686. cron: "0 9 * * *",
  687. delayMinutes: null,
  688. prompt: "write daily report",
  689. title: "daily report",
  690. },
  691. { model: "stale-provider/stale-model", sessionId: "session-1" },
  692. );
  693. expect(requestClient).toHaveBeenCalledWith(
  694. zcodeProtocolMethods.automationCreate,
  695. {
  696. cronExpr: "0 9 * * *",
  697. prompt: "write daily report",
  698. title: "daily report",
  699. recurring: true,
  700. modelSelection: {
  701. providerId: "zai-api",
  702. modelId: "GLM-5",
  703. options: { reasoningLevel: "nothink" },
  704. },
  705. mode: "yolo",
  706. targetTaskId: "session-1",
  707. },
  708. expect.anything(),
  709. );
  710. expect(setCustomSessionTitle).toHaveBeenCalledWith({
  711. title: "daily report",
  712. traceContext: { traceId: "trace-session-1" },
  713. });
  714. });
  715. it("Highspeed Turn 中 CronCreate 持久化加速前的会话模型", async () => {
  716. const requestClient = vi.fn(async (method: string) => {
  717. if (method === zcodeProtocolMethods.automationCheckTaskBinding) return { bound: false };
  718. return {
  719. automation: {
  720. automationId: "automation-highspeed",
  721. title: "daily report",
  722. cronExpr: "0 9 * * *",
  723. prompt: "write daily report",
  724. model: "builtin:zai/GLM-5",
  725. provider: "glm",
  726. enabled: true,
  727. lifecycleStatus: "active" as const,
  728. runCount: 0,
  729. recurring: true,
  730. },
  731. };
  732. });
  733. // 加速轮的模型只存在于本轮 modelExecution(selectionScope=execution),从不写回
  734. // Session Selection;所以 CronCreate 读到的 Session Selection 必须仍是加速前的普通选型。
  735. const getSessionModelSelection = vi.fn(() => ({
  736. providerId: "account:zai-individual-coding-plan",
  737. modelId: "GLM-5",
  738. }));
  739. const port = createProtocolAutomationPort({
  740. requestClient,
  741. sessions: new Map([
  742. [
  743. "session-1",
  744. {
  745. app: {
  746. runtime: { getSessionModelSelection },
  747. getMode: () => "build",
  748. setCustomSessionTitle: vi.fn(async () => undefined),
  749. },
  750. traceContext: { traceId: "trace-session-1" },
  751. },
  752. ],
  753. ]),
  754. } as unknown as ZCodeProtocolAgentServerContext);
  755. await port.create(
  756. {
  757. cron: "0 9 * * *",
  758. delayMinutes: null,
  759. prompt: "write daily report",
  760. title: "daily report",
  761. },
  762. { sessionId: "session-1" },
  763. );
  764. expect(requestClient).toHaveBeenCalledWith(
  765. zcodeProtocolMethods.automationCreate,
  766. expect.objectContaining({
  767. modelSelection: { providerId: "account:zai-individual-coding-plan", modelId: "GLM-5" },
  768. }),
  769. expect.anything(),
  770. );
  771. // 定时任务禁止落库加速卡 Provider,否则后续触发会拿不到卡凭据而失败。
  772. const createdPayload = requestClient.mock.calls.find(
  773. (call) => call[0] === zcodeProtocolMethods.automationCreate,
  774. )?.[1] as { modelSelection?: { providerId?: string } } | undefined;
  775. expect(isHighspeedProviderId(createdPayload?.modelSelection?.providerId)).toBe(false);
  776. });
  777. it("CronCreate 成功后冻结当前会话标题,避免迟到 generated title 覆盖 automation 语义", async () => {
  778. const setCustomSessionTitle = vi.fn(async () => undefined);
  779. const port = createProtocolAutomationPort({
  780. requestClient: vi.fn(async () => ({
  781. automation: {
  782. automationId: "automation-1",
  783. title: "每5分钟给我讲个笑话",
  784. cronExpr: "*/5 * * * *",
  785. prompt: "给我讲一个笑话",
  786. enabled: true,
  787. lifecycleStatus: "active" as const,
  788. runCount: 0,
  789. recurring: true,
  790. },
  791. })),
  792. sessions: new Map([
  793. [
  794. "session-1",
  795. {
  796. app: {
  797. runtime: { getSessionModelSelection: () => undefined },
  798. getModel: () => undefined,
  799. getMode: () => undefined,
  800. getThoughtLevel: () => undefined,
  801. setCustomSessionTitle,
  802. },
  803. traceContext: { traceId: "trace-session-1" },
  804. },
  805. ],
  806. ]),
  807. } as unknown as ZCodeProtocolAgentServerContext);
  808. await port.create(
  809. {
  810. cron: "*/5 * * * *",
  811. delayMinutes: null,
  812. prompt: "给我讲一个笑话",
  813. title: "每5分钟给我讲个笑话",
  814. },
  815. { sessionId: "session-1" },
  816. );
  817. expect(setCustomSessionTitle).toHaveBeenCalledWith({
  818. title: "每5分钟给我讲个笑话",
  819. traceContext: { traceId: "trace-session-1" },
  820. });
  821. });
  822. it("CronUpdate 将严格 patch 映射到 automation/update,并保留 maxRuns=null", async () => {
  823. const requestClient = vi.fn(async () => ({
  824. automation: {
  825. automationId: "automation-1",
  826. title: "updated report",
  827. cronExpr: "0 10 * * *",
  828. prompt: "write updated report",
  829. enabled: true,
  830. lifecycleStatus: "active" as const,
  831. runCount: 3,
  832. recurring: true,
  833. },
  834. }));
  835. const port = createProtocolAutomationPort({
  836. requestClient,
  837. sessions: new Map(),
  838. } as unknown as ZCodeProtocolAgentServerContext);
  839. await expect(
  840. port.update({
  841. id: "automation-1",
  842. title: "updated report",
  843. cron: "0 10 * * *",
  844. recurring: true,
  845. maxRuns: null,
  846. }),
  847. ).resolves.toMatchObject({
  848. automationId: "automation-1",
  849. title: "updated report",
  850. runCount: 3,
  851. });
  852. expect(requestClient).toHaveBeenCalledWith(
  853. zcodeProtocolMethods.automationUpdate,
  854. {
  855. automationId: "automation-1",
  856. title: "updated report",
  857. cronExpr: "0 10 * * *",
  858. recurring: true,
  859. maxRuns: null,
  860. },
  861. expect.anything(),
  862. );
  863. expect(requestClient).not.toHaveBeenCalledWith(
  864. zcodeProtocolMethods.automationDelete,
  865. expect.anything(),
  866. expect.anything(),
  867. );
  868. expect(requestClient).not.toHaveBeenCalledWith(
  869. zcodeProtocolMethods.automationCreate,
  870. expect.anything(),
  871. expect.anything(),
  872. );
  873. });
  874. it("CronDelete 返回 protocol 的真实删除结果", async () => {
  875. const requestClient = vi.fn(async () => ({ deleted: false }));
  876. const port = createProtocolAutomationPort({
  877. requestClient,
  878. sessions: new Map(),
  879. } as unknown as ZCodeProtocolAgentServerContext);
  880. await expect(port.delete({ id: "stale-id" })).resolves.toBe(false);
  881. expect(requestClient).toHaveBeenCalledWith(
  882. zcodeProtocolMethods.automationDelete,
  883. { automationId: "stale-id" },
  884. expect.anything(),
  885. );
  886. });
  887. it("会话未登记在 context.sessions 时,仍从归属会话解析器读取权限/思考等级", async () => {
  888. // Bugfix 回归:V4/desktop 会话可能不在 legacy context.sessions map 里,activeSession 命中失败
  889. // 会导致 mode/thoughtLevel 丢失(model 靠 createContext 兜底才幸存)。改为绑定归属会话解析器。
  890. const setCustomSessionTitle = vi.fn(async () => undefined);
  891. const requestClient = vi.fn(async () => ({
  892. automation: {
  893. automationId: "automation-2",
  894. title: "daily report",
  895. cronExpr: "0 9 * * *",
  896. prompt: "write daily report",
  897. model: "zai-api/GLM-5",
  898. provider: "glm",
  899. mode: "plan" as const,
  900. thoughtLevel: "think-hard",
  901. enabled: true,
  902. lifecycleStatus: "active" as const,
  903. runCount: 0,
  904. recurring: true,
  905. },
  906. }));
  907. const ownSession = {
  908. app: {
  909. runtime: {
  910. getSessionModelSelection: () => ({
  911. providerId: "zai-api",
  912. modelId: "GLM-5",
  913. options: { reasoningLevel: "think-hard" },
  914. }),
  915. },
  916. getModel: () => "zai-api/GLM-5",
  917. getMode: () => "plan",
  918. getThoughtLevel: () => "think-hard",
  919. setCustomSessionTitle,
  920. },
  921. traceContext: { traceId: "trace-session-1" },
  922. };
  923. const port = createProtocolAutomationPort(
  924. {
  925. requestClient,
  926. // 归属会话故意不在 sessions map 中,模拟 V4/desktop 场景。
  927. sessions: new Map(),
  928. } as unknown as ZCodeProtocolAgentServerContext,
  929. () => ownSession as unknown as never,
  930. );
  931. await port.create(
  932. {
  933. cron: "0 9 * * *",
  934. delayMinutes: null,
  935. prompt: "write daily report",
  936. title: "daily report",
  937. },
  938. { model: "stale-provider/stale-model", sessionId: "session-1" },
  939. );
  940. expect(requestClient).toHaveBeenCalledWith(
  941. zcodeProtocolMethods.automationCreate,
  942. {
  943. cronExpr: "0 9 * * *",
  944. prompt: "write daily report",
  945. title: "daily report",
  946. recurring: true,
  947. modelSelection: {
  948. providerId: "zai-api",
  949. modelId: "GLM-5",
  950. options: { reasoningLevel: "think-hard" },
  951. },
  952. mode: "plan",
  953. targetTaskId: "session-1",
  954. },
  955. expect.anything(),
  956. );
  957. });
  958. });