offpeak-port.test.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. import { describe, expect, it, vi } from "vitest";
  2. import { zcodeProtocolMethods } from "@zcode/shared";
  3. import {
  4. createProtocolOffPeakPort,
  5. OFF_PEAK_CREATE_BOUND_SESSION_CHECK_ERROR,
  6. OFF_PEAK_CREATE_FROM_OFF_PEAK_RUN_ERROR,
  7. OFF_PEAK_CREATE_IN_BOUND_SESSION_ERROR,
  8. } from "../src/zcode-protocol/offpeak-port.js";
  9. import type { ZCodeProtocolAgentServerContext } from "../src/zcode-protocol/server-types.js";
  10. import { ZCodeProtocolAgentServer } from "../src/zcode-protocol/server.js";
  11. import { createSessionRecordForV4, closeSession } from "../src/zcode-protocol/server-operations.js";
  12. import type { ZCodeAppOptions } from "../src/app/types.js";
  13. import { createFakeApp } from "./helpers/fake-zcode-app.js";
  14. it.each([
  15. { enabled: true, preference: false, expected: true },
  16. { enabled: false, preference: true, expected: true },
  17. { enabled: false, preference: false, expected: false },
  18. ])("协议工厂保留闲时能力装配门禁:%j", async ({ enabled, preference, expected }) => {
  19. let appOptions: ZCodeAppOptions | undefined;
  20. const server = new ZCodeProtocolAgentServer({
  21. createZCodeApp: (options) => {
  22. appOptions = options;
  23. return createFakeApp(options);
  24. },
  25. });
  26. const context = (server as unknown as { context: ZCodeProtocolAgentServerContext }).context;
  27. context.appRuntimePreferences.offPeakToolEnabled = preference;
  28. const result = await createSessionRecordForV4(context, {
  29. workspace: { workspacePath: "/fixture", workspaceKey: "/fixture" },
  30. offPeakToolEnabled: enabled,
  31. });
  32. try {
  33. expect(Boolean(appOptions?.offPeakPort)).toBe(expected);
  34. if (expected) {
  35. const requestClient = vi.spyOn(context, "requestClient").mockResolvedValue({ tasks: [] });
  36. await expect(appOptions!.offPeakPort!.list({ sessionId: result.sessionId })).resolves.toEqual(
  37. [],
  38. );
  39. expect(requestClient).toHaveBeenCalledWith(
  40. zcodeProtocolMethods.offPeakList,
  41. {},
  42. expect.anything(),
  43. );
  44. }
  45. } finally {
  46. await closeSession(context, { sessionId: result.sessionId });
  47. }
  48. });
  49. const protocolTask = {
  50. offPeakTaskId: "offpeak-1",
  51. title: "重构 utils",
  52. status: "queued" as const,
  53. queuePosition: 3,
  54. createdAt: 1_700_000_000_000,
  55. };
  56. function contextOf(params: {
  57. requestClient: ReturnType<typeof vi.fn>;
  58. session?: Record<string, unknown>;
  59. }): ZCodeProtocolAgentServerContext {
  60. return {
  61. requestClient: params.requestClient,
  62. sessions: new Map(params.session ? [["session-1", params.session]] : []),
  63. } as unknown as ZCodeProtocolAgentServerContext;
  64. }
  65. /** 绑定守卫先走 offPeak/list;缺省返回空列表,让 create 路径直通。 */
  66. function requestClientWith(
  67. handlers: Partial<Record<string, (params: unknown) => unknown>>,
  68. listed: Array<Record<string, unknown>> = [],
  69. ) {
  70. return vi.fn(async (method: string, params?: unknown) => {
  71. if (method === zcodeProtocolMethods.offPeakList) return { tasks: listed };
  72. const handler = handlers[method];
  73. if (!handler) throw new Error(`unexpected method ${method}`);
  74. return handler(params);
  75. });
  76. }
  77. describe("createProtocolOffPeakPort", () => {
  78. it("拒绝闲时派发 turn 里再次 OffPeakCreate(D49-2),且不调用 offPeak/create", async () => {
  79. const requestClient = vi.fn();
  80. const port = createProtocolOffPeakPort(
  81. contextOf({
  82. requestClient,
  83. session: { activeOffPeakTaskId: "offpeak-parent", app: {} },
  84. }),
  85. );
  86. await expect(
  87. port.create({ title: "nested", prompt: "nested" }, { sessionId: "session-1" }),
  88. ).rejects.toThrow(OFF_PEAK_CREATE_FROM_OFF_PEAK_RUN_ERROR);
  89. expect(requestClient).not.toHaveBeenCalled();
  90. });
  91. it("automation 执行 turn 放行 OffPeakCreate(D49-3:不查 activeAutomationId、不查 cron 绑定)", async () => {
  92. const requestClient = requestClientWith({
  93. [zcodeProtocolMethods.offPeakCreate]: () => ({ ok: true, task: protocolTask }),
  94. });
  95. const port = createProtocolOffPeakPort(
  96. contextOf({
  97. requestClient,
  98. session: { activeAutomationId: "automation-parent", app: {} },
  99. }),
  100. );
  101. await expect(
  102. port.create({ title: "定时派生", prompt: "nightly digest" }, { sessionId: "session-1" }),
  103. ).resolves.toEqual({ ok: true, task: protocolTask });
  104. // 与 automation-port 相反:不查 cron 绑定(cron 轮派生闲时任务是 D49-3 组合玩法),
  105. // 放大防护的唯一权威是服务端取号额度。
  106. expect(requestClient).not.toHaveBeenCalledWith(
  107. zcodeProtocolMethods.automationCheckTaskBinding,
  108. expect.anything(),
  109. expect.anything(),
  110. );
  111. });
  112. it("create 透传显式入参 + 绑定当前会话(D50),不注入会话运行态,也不冻结会话标题(D49-4/5)", async () => {
  113. const setCustomSessionTitle = vi.fn(async () => undefined);
  114. const requestClient = requestClientWith({
  115. [zcodeProtocolMethods.offPeakCreate]: () => ({ ok: true, task: protocolTask }),
  116. });
  117. const port = createProtocolOffPeakPort(
  118. contextOf({
  119. requestClient,
  120. session: {
  121. app: {
  122. getModel: () => "builtin:zai/GLM-5",
  123. getMode: () => "yolo",
  124. getThoughtLevel: () => "nothink",
  125. setCustomSessionTitle,
  126. },
  127. traceContext: { traceId: "trace-1" },
  128. },
  129. }),
  130. );
  131. await port.create({ title: "重构 utils", prompt: "do it" }, { sessionId: "session-1" });
  132. expect(requestClient).toHaveBeenCalledWith(
  133. zcodeProtocolMethods.offPeakCreate,
  134. { title: "重构 utils", prompt: "do it", boundSessionId: "session-1" },
  135. expect.anything(),
  136. );
  137. expect(setCustomSessionTitle).not.toHaveBeenCalled();
  138. });
  139. it("本会话已绑定未终态闲时任务时拒绝再建,且不调用 offPeak/create(D50)", async () => {
  140. const requestClient = requestClientWith(
  141. { [zcodeProtocolMethods.offPeakCreate]: () => ({ ok: true, task: protocolTask }) },
  142. [{ ...protocolTask, status: "running", sessionId: "session-1" }],
  143. );
  144. const port = createProtocolOffPeakPort(contextOf({ requestClient, session: { app: {} } }));
  145. await expect(
  146. port.create({ title: "again", prompt: "again" }, { sessionId: "session-1" }),
  147. ).rejects.toThrow(OFF_PEAK_CREATE_IN_BOUND_SESSION_ERROR);
  148. expect(requestClient).not.toHaveBeenCalledWith(
  149. zcodeProtocolMethods.offPeakCreate,
  150. expect.anything(),
  151. expect.anything(),
  152. );
  153. });
  154. it("绑定任务已终态或属于其他会话时放行(D50:一次性任务,跑完可再建)", async () => {
  155. const requestClient = requestClientWith(
  156. { [zcodeProtocolMethods.offPeakCreate]: () => ({ ok: true, task: protocolTask }) },
  157. [
  158. {
  159. ...protocolTask,
  160. offPeakTaskId: "offpeak-done",
  161. status: "completed",
  162. sessionId: "session-1",
  163. },
  164. {
  165. ...protocolTask,
  166. offPeakTaskId: "offpeak-other",
  167. status: "queued",
  168. sessionId: "session-2",
  169. },
  170. ],
  171. );
  172. const port = createProtocolOffPeakPort(contextOf({ requestClient, session: { app: {} } }));
  173. await expect(
  174. port.create({ title: "again", prompt: "again" }, { sessionId: "session-1" }),
  175. ).resolves.toEqual({ ok: true, task: protocolTask });
  176. });
  177. it("绑定查询失败 fail-closed,不放行创建", async () => {
  178. const requestClient = vi.fn(async (method: string) => {
  179. if (method === zcodeProtocolMethods.offPeakList) throw new Error("db locked");
  180. return { ok: true, task: protocolTask };
  181. });
  182. const port = createProtocolOffPeakPort(contextOf({ requestClient, session: { app: {} } }));
  183. await expect(
  184. port.create({ title: "t", prompt: "p" }, { sessionId: "session-1" }),
  185. ).rejects.toThrow(OFF_PEAK_CREATE_BOUND_SESSION_CHECK_ERROR);
  186. expect(requestClient).not.toHaveBeenCalledWith(
  187. zcodeProtocolMethods.offPeakCreate,
  188. expect.anything(),
  189. expect.anything(),
  190. );
  191. });
  192. it("ok:false 判别联合原样透传分类,不降级为异常", async () => {
  193. const failure = {
  194. ok: false,
  195. failureStage: "ticket_request",
  196. errorCategory: "quota_3103",
  197. errorCode: "3103",
  198. };
  199. const requestClient = requestClientWith({
  200. [zcodeProtocolMethods.offPeakCreate]: () => failure,
  201. });
  202. const port = createProtocolOffPeakPort(contextOf({ requestClient }));
  203. await expect(port.create({ title: "t", prompt: "p" })).resolves.toEqual(failure);
  204. });
  205. it("list 直通 offPeak/list 并映射最小快照", async () => {
  206. const requestClient = vi.fn(async () => ({ tasks: [protocolTask] }));
  207. const port = createProtocolOffPeakPort(contextOf({ requestClient }));
  208. await expect(port.list()).resolves.toEqual([
  209. {
  210. offPeakTaskId: "offpeak-1",
  211. title: "重构 utils",
  212. status: "queued",
  213. queuePosition: 3,
  214. sessionId: undefined,
  215. createdAt: 1_700_000_000_000,
  216. },
  217. ]);
  218. expect(requestClient).toHaveBeenCalledWith(
  219. zcodeProtocolMethods.offPeakList,
  220. {},
  221. expect.anything(),
  222. );
  223. });
  224. });
  225. it.each([false, true])("闲时任务列表按协商能力携带自身工作区:%s", async (enabled) => {
  226. const workspace = { workspaceKey: "/tasks/b", workspacePath: "/tasks/b" };
  227. const requestClient = vi.fn(async () => ({ tasks: [] }));
  228. const port = createProtocolOffPeakPort(
  229. {
  230. requestClient,
  231. sessionWorkspaceRoutingEnabled: enabled,
  232. } as unknown as ZCodeProtocolAgentServerContext,
  233. () =>
  234. ({ workspace }) as import("../src/zcode-protocol/server-types.js").ZCodeProtocolSessionRecord,
  235. );
  236. await port.list({ sessionId: "session-b" });
  237. expect(requestClient).toHaveBeenCalledWith(
  238. zcodeProtocolMethods.offPeakList,
  239. enabled ? { workspace } : {},
  240. expect.anything(),
  241. );
  242. });