automation-port.test.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. import { describe, expect, it, vi } from "vitest";
  2. import { AutomationCreateLimitError, isAutomationCreateLimitError } from "@zcode/contracts";
  3. import { AUTOMATION_CREATE_LIMIT_ERROR_CODE, 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("CronUpdate 将严格 patch 映射到 automation/update,并保留 maxRuns=null", async () => {
  716. const requestClient = vi.fn(async () => ({
  717. automation: {
  718. automationId: "automation-1",
  719. title: "updated report",
  720. cronExpr: "0 10 * * *",
  721. prompt: "write updated report",
  722. enabled: true,
  723. lifecycleStatus: "active" as const,
  724. runCount: 3,
  725. recurring: true,
  726. },
  727. }));
  728. const port = createProtocolAutomationPort({
  729. requestClient,
  730. sessions: new Map(),
  731. } as unknown as ZCodeProtocolAgentServerContext);
  732. await expect(
  733. port.update({
  734. id: "automation-1",
  735. title: "updated report",
  736. cron: "0 10 * * *",
  737. recurring: true,
  738. maxRuns: null,
  739. }),
  740. ).resolves.toMatchObject({
  741. automationId: "automation-1",
  742. title: "updated report",
  743. runCount: 3,
  744. });
  745. expect(requestClient).toHaveBeenCalledWith(
  746. zcodeProtocolMethods.automationUpdate,
  747. {
  748. automationId: "automation-1",
  749. title: "updated report",
  750. cronExpr: "0 10 * * *",
  751. recurring: true,
  752. maxRuns: null,
  753. },
  754. expect.anything(),
  755. );
  756. expect(requestClient).not.toHaveBeenCalledWith(
  757. zcodeProtocolMethods.automationDelete,
  758. expect.anything(),
  759. expect.anything(),
  760. );
  761. expect(requestClient).not.toHaveBeenCalledWith(
  762. zcodeProtocolMethods.automationCreate,
  763. expect.anything(),
  764. expect.anything(),
  765. );
  766. });
  767. it("CronDelete 返回 protocol 的真实删除结果", async () => {
  768. const requestClient = vi.fn(async () => ({ deleted: false }));
  769. const port = createProtocolAutomationPort({
  770. requestClient,
  771. sessions: new Map(),
  772. } as unknown as ZCodeProtocolAgentServerContext);
  773. await expect(port.delete({ id: "stale-id" })).resolves.toBe(false);
  774. expect(requestClient).toHaveBeenCalledWith(
  775. zcodeProtocolMethods.automationDelete,
  776. { automationId: "stale-id" },
  777. expect.anything(),
  778. );
  779. });
  780. it("CronPauseSelf 通过 automation/pause 透传执行器注入的本轮 automationId 并返回真实暂停结果", async () => {
  781. const requestClient = vi.fn(async () => ({ paused: true }));
  782. const port = createProtocolAutomationPort({
  783. requestClient,
  784. sessions: new Map(),
  785. } as unknown as ZCodeProtocolAgentServerContext);
  786. await expect(port.pause({ id: "automation-1" })).resolves.toBe(true);
  787. expect(requestClient).toHaveBeenCalledWith(
  788. zcodeProtocolMethods.automationPause,
  789. { automationId: "automation-1" },
  790. expect.anything(),
  791. );
  792. });
  793. it("会话未登记在 context.sessions 时,仍从归属会话解析器读取权限/思考等级", async () => {
  794. // Bugfix 回归:V4/desktop 会话可能不在 legacy context.sessions map 里,activeSession 命中失败
  795. // 会导致 mode/thoughtLevel 丢失(model 靠 createContext 兜底才幸存)。改为绑定归属会话解析器。
  796. const setCustomSessionTitle = vi.fn(async () => undefined);
  797. const requestClient = vi.fn(async () => ({
  798. automation: {
  799. automationId: "automation-2",
  800. title: "daily report",
  801. cronExpr: "0 9 * * *",
  802. prompt: "write daily report",
  803. model: "zai-api/GLM-5",
  804. provider: "glm",
  805. mode: "plan" as const,
  806. thoughtLevel: "think-hard",
  807. enabled: true,
  808. lifecycleStatus: "active" as const,
  809. runCount: 0,
  810. recurring: true,
  811. },
  812. }));
  813. const ownSession = {
  814. app: {
  815. runtime: {
  816. getSessionModelSelection: () => ({
  817. providerId: "zai-api",
  818. modelId: "GLM-5",
  819. options: { reasoningLevel: "think-hard" },
  820. }),
  821. },
  822. getModel: () => "zai-api/GLM-5",
  823. getMode: () => "plan",
  824. getThoughtLevel: () => "think-hard",
  825. setCustomSessionTitle,
  826. },
  827. traceContext: { traceId: "trace-session-1" },
  828. };
  829. const port = createProtocolAutomationPort(
  830. {
  831. requestClient,
  832. // 归属会话故意不在 sessions map 中,模拟 V4/desktop 场景。
  833. sessions: new Map(),
  834. } as unknown as ZCodeProtocolAgentServerContext,
  835. () => ownSession as unknown as never,
  836. );
  837. await port.create(
  838. {
  839. cron: "0 9 * * *",
  840. delayMinutes: null,
  841. prompt: "write daily report",
  842. title: "daily report",
  843. },
  844. { model: "stale-provider/stale-model", sessionId: "session-1" },
  845. );
  846. expect(requestClient).toHaveBeenCalledWith(
  847. zcodeProtocolMethods.automationCreate,
  848. {
  849. cronExpr: "0 9 * * *",
  850. prompt: "write daily report",
  851. title: "daily report",
  852. recurring: true,
  853. modelSelection: {
  854. providerId: "zai-api",
  855. modelId: "GLM-5",
  856. options: { reasoningLevel: "think-hard" },
  857. },
  858. mode: "plan",
  859. targetTaskId: "session-1",
  860. },
  861. expect.anything(),
  862. );
  863. });
  864. });
  865. it.each([false, true])("定时任务列表按协商能力携带自身工作区:%s", async (enabled) => {
  866. const workspace = { workspaceKey: "/tasks/b", workspacePath: "/tasks/b" };
  867. const requestClient = vi.fn(async () => ({ automations: [] }));
  868. const port = createProtocolAutomationPort(
  869. {
  870. requestClient,
  871. sessionWorkspaceRoutingEnabled: enabled,
  872. } as unknown as ZCodeProtocolAgentServerContext,
  873. () =>
  874. ({ workspace }) as import("../src/zcode-protocol/server-types.js").ZCodeProtocolSessionRecord,
  875. );
  876. await port.list({ sessionId: "session-b" });
  877. expect(requestClient).toHaveBeenCalledWith(
  878. zcodeProtocolMethods.automationList,
  879. enabled ? { workspace } : {},
  880. expect.anything(),
  881. );
  882. });