offPeakHostDispatch.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. import { readFile } from "node:fs/promises";
  2. import ts from "typescript";
  3. import { OFF_PEAK_PROVIDER_IDS } from "@zcode/shared";
  4. import { beforeAll, describe, expect, it, vi } from "vitest";
  5. import { OffPeakModelUnavailableError } from "@zcode/services/node";
  6. import {
  7. assertBoundSessionDispatchable,
  8. resolveOffPeakDispatchKind,
  9. } from "../src/host/offPeakDispatchPlan.js";
  10. let createDispatch: (
  11. dependencies: Record<string, unknown>,
  12. ) => (request: Record<string, unknown>) => Promise<unknown>;
  13. beforeAll(async () => {
  14. // 只装载真实派发函数,隔离 host/index 的进程启动副作用;不复制一份派发算法测试自己。
  15. const path = new URL("../src/host/index.ts", import.meta.url);
  16. const source = ts.createSourceFile(
  17. path.pathname,
  18. await readFile(path, "utf8"),
  19. ts.ScriptTarget.Latest,
  20. true,
  21. );
  22. const declaration = source.statements.find(
  23. (node): node is ts.FunctionDeclaration =>
  24. ts.isFunctionDeclaration(node) && node.name?.text === "dispatchOffPeakRun",
  25. );
  26. if (!declaration) throw new Error("Missing production dispatchOffPeakRun");
  27. const code = ts.transpileModule(declaration.getText(source), {
  28. compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },
  29. }).outputText;
  30. createDispatch = (dependencies) =>
  31. new Function(...Object.keys(dependencies), `${code}; return dispatchOffPeakRun;`)(
  32. ...Object.values(dependencies),
  33. );
  34. });
  35. function setup() {
  36. const service = {
  37. listDeletedTaskIds: vi.fn(async (): Promise<string[]> => []),
  38. // tasks-index 行的 status 只镜像 CLI 终态,运行中只能来自 syncer 的活动集合。
  39. listActiveTaskIds: vi.fn(async (): Promise<string[]> => []),
  40. resumeTask: vi.fn(async () => {}),
  41. setConfigOption: vi.fn(async () => {}),
  42. createTask: vi.fn(async (_params: Record<string, unknown>) => ({
  43. taskId: "new",
  44. traceId: "trace-new",
  45. })),
  46. sendPrompt: vi.fn(async () => {}),
  47. };
  48. const runtime = {
  49. service: {
  50. residentExecutions: {
  51. has: vi.fn(() => false),
  52. retakeGuard: vi.fn(() => () => true),
  53. isUserOwned: vi.fn(() => false),
  54. discardTicket: vi.fn(async () => {}),
  55. deliverTicket: vi.fn(async () => undefined as { sessionId: string } | undefined),
  56. },
  57. },
  58. validateSelection: vi.fn(async () => true),
  59. buildRequestAuth: vi.fn(async () => ({ apiKey: "test-ticket-auth" })),
  60. };
  61. const dispose = vi.fn();
  62. const admitted = vi.fn();
  63. const track = vi.fn(() => ({ admitted }));
  64. const repo = {
  65. get: vi.fn(async () => ({ status: "queued", conversationId: "bound" })),
  66. markRunning: vi.fn(async () => ({})),
  67. requeueForContinuation: vi.fn(async () => ({})),
  68. };
  69. const report = vi.fn();
  70. const dispatch = createDispatch({
  71. activeServices: { getOptional: () => service },
  72. reportHostSessionCreate: report,
  73. parentPort: {},
  74. IZCodeTaskService: Symbol("task-service"),
  75. IZCodeAgentService: Symbol("agent-service"),
  76. offPeakTaskRepo: repo,
  77. isOffPeakTerminalStatus: (status: string) =>
  78. ["completed", "failed", "cancelled"].includes(status),
  79. ensureOffPeakRuntime: async () => runtime,
  80. OffPeakModelUnavailableError,
  81. resolveOffPeakDispatchKind,
  82. assertBoundSessionDispatchable,
  83. randomUUID: () => "run-1",
  84. OFF_PEAK_RESUME_PROMPT: "resume prompt",
  85. offPeakRunSubscriptionKey: (taskId: string, traceId: string) => `${taskId}:${traceId}`,
  86. trackOffPeakRunOutcome: track,
  87. disposeOffPeakRunSubscription: dispose,
  88. });
  89. const modelSelection = {
  90. providerId: OFF_PEAK_PROVIDER_IDS.bigmodel,
  91. modelId: "GLM-5.2",
  92. options: { reasoningLevel: "high" },
  93. };
  94. const request = {
  95. offPeakTaskId: "idle-1",
  96. prompt: "task prompt",
  97. permissionMode: "yolo",
  98. modelSelection,
  99. sessionId: "bound",
  100. serverTicketId: "ticket-1",
  101. workspacePath: "/project",
  102. workspaceIdentity: "remote:ssh:test:/project",
  103. };
  104. return { service, runtime, dispose, track, report, dispatch, request, admitted, repo };
  105. }
  106. describe("Host OffPeak dispatch current execution contract", () => {
  107. it("会话准备期间任务取消,接纳前重新核对并释放票据", async () => {
  108. const state = setup();
  109. state.service.resumeTask.mockImplementation(async () => {
  110. state.repo.get.mockResolvedValue({ status: "cancelled", conversationId: "bound" });
  111. });
  112. await expect(state.dispatch(state.request)).resolves.toMatchObject({ lifecycleManaged: true });
  113. expect(state.service.sendPrompt).not.toHaveBeenCalled();
  114. expect(state.track).not.toHaveBeenCalled();
  115. expect(state.runtime.service.residentExecutions.discardTicket).toHaveBeenCalledWith("ticket-1");
  116. });
  117. it("续票交接报错期间已被用户接管,不将用户任务重新排队", async () => {
  118. const state = setup();
  119. state.runtime.service.residentExecutions.has.mockReturnValue(true);
  120. state.runtime.service.residentExecutions.retakeGuard.mockReturnValue(() => false);
  121. state.runtime.service.residentExecutions.deliverTicket.mockRejectedValue(
  122. new Error("lost reply"),
  123. );
  124. await expect(state.dispatch(state.request)).rejects.toThrow("lost reply");
  125. expect(state.repo.requeueForContinuation).not.toHaveBeenCalled();
  126. });
  127. it("任务已结束时迟到派发只释放票据,不重放原始任务", async () => {
  128. const state = setup();
  129. state.repo.get.mockResolvedValue({ status: "completed", conversationId: "bound" });
  130. await expect(state.dispatch(state.request)).resolves.toMatchObject({ lifecycleManaged: true });
  131. expect(state.service.sendPrompt).not.toHaveBeenCalled();
  132. expect(state.repo.markRunning).not.toHaveBeenCalled();
  133. });
  134. it("未创建会话的任务已删除时,不返回虚构的空会话标识", async () => {
  135. const state = setup();
  136. state.repo.get.mockResolvedValue(undefined as never);
  137. const result = await state.dispatch({ ...state.request, sessionId: undefined });
  138. expect(result).toMatchObject({ lifecycleManaged: true });
  139. expect((result as { sessionId?: string }).sessionId).toBeUndefined();
  140. expect(state.runtime.service.residentExecutions.discardTicket).toHaveBeenCalledWith("ticket-1");
  141. expect(state.service.createTask).not.toHaveBeenCalled();
  142. });
  143. it("构建续票凭据期间驻留执行结束,不落入初始派发", async () => {
  144. const state = setup();
  145. state.runtime.service.residentExecutions.has.mockReturnValue(true);
  146. await expect(state.dispatch(state.request)).resolves.toMatchObject({ lifecycleManaged: true });
  147. expect(state.service.sendPrompt).not.toHaveBeenCalled();
  148. expect(state.service.resumeTask).not.toHaveBeenCalled();
  149. });
  150. it("驻留执行收到新票只交接票据,不重复恢复或提交原始任务", async () => {
  151. const state = setup();
  152. state.runtime.service.residentExecutions.has.mockReturnValue(true);
  153. state.runtime.service.residentExecutions.deliverTicket.mockResolvedValue({
  154. sessionId: "bound",
  155. });
  156. await expect(state.dispatch({ ...state.request, conversationId: "bound" })).resolves.toEqual({
  157. conversationId: "bound",
  158. sessionId: "bound",
  159. lifecycleManaged: true,
  160. });
  161. expect(state.service.sendPrompt).not.toHaveBeenCalled();
  162. expect(state.service.resumeTask).not.toHaveBeenCalled();
  163. expect(state.track).not.toHaveBeenCalled();
  164. });
  165. it.each(["bound-first-run", "resume"])(
  166. "%s keeps idle reasoning out of persisted Session config",
  167. async (kind) => {
  168. const state = setup();
  169. const request = {
  170. ...state.request,
  171. ...(kind === "resume" ? { conversationId: "bound" } : {}),
  172. };
  173. await expect(state.dispatch(request)).resolves.toEqual({
  174. conversationId: "bound",
  175. sessionId: "bound",
  176. lifecycleManaged: true,
  177. });
  178. expect(state.service.setConfigOption.mock.calls).toHaveLength(1);
  179. expect(state.service.setConfigOption).toHaveBeenCalledWith(
  180. expect.objectContaining({ configId: "mode", value: "yolo" }),
  181. );
  182. expect(state.service.sendPrompt).toHaveBeenCalledWith(
  183. expect.objectContaining({
  184. taskId: "bound",
  185. modelSelection: state.request.modelSelection,
  186. content: kind === "resume" ? "resume prompt" : "task prompt",
  187. toolDenylist: ["CronCreate", "OffPeakCreate"],
  188. modelExecution: {
  189. memoryExtraction: "skip",
  190. selectionScope: "execution",
  191. requestAuth: { apiKey: "test-ticket-auth" },
  192. offPeak: {
  193. executionId: expect.any(String),
  194. ticketId: "ticket-1",
  195. providerErrorCode: "3102",
  196. },
  197. subagents: { foregroundModel: "submission", background: "allow" },
  198. },
  199. }),
  200. );
  201. expect(state.service.createTask).not.toHaveBeenCalled();
  202. expect(state.repo.markRunning).toHaveBeenCalled();
  203. expect(state.admitted).toHaveBeenCalledTimes(1);
  204. expect(state.report).not.toHaveBeenCalled();
  205. expect(state.service.resumeTask).toHaveBeenCalledWith(
  206. expect.objectContaining({
  207. workspaceIdentity: request.workspaceIdentity,
  208. offPeakTaskId: "idle-1",
  209. }),
  210. );
  211. },
  212. );
  213. it.each(["busy", "deleted"])(
  214. "bound session %s fails before config writes or dispatch",
  215. async (kind) => {
  216. const state = setup();
  217. if (kind === "busy") state.service.listActiveTaskIds.mockResolvedValue(["bound"]);
  218. else state.service.listDeletedTaskIds.mockResolvedValue(["bound"]);
  219. await expect(state.dispatch(state.request)).rejects.toThrow(
  220. kind === "busy" ? "is busy" : "was deleted",
  221. );
  222. expect(state.service.resumeTask).not.toHaveBeenCalled();
  223. expect(state.service.setConfigOption).not.toHaveBeenCalled();
  224. expect(state.service.sendPrompt).not.toHaveBeenCalled();
  225. },
  226. );
  227. it("new session uses its ordinary initial selection, while dispatch keeps the frozen idle selection", async () => {
  228. const state = setup();
  229. await state.dispatch({ ...state.request, sessionId: undefined });
  230. expect(state.service.createTask).toHaveBeenCalledWith(
  231. expect.objectContaining({
  232. offPeakTaskId: "idle-1",
  233. deferPersistenceUntilFirstPrompt: true,
  234. }),
  235. );
  236. expect(state.report).toHaveBeenCalledExactlyOnceWith(
  237. {},
  238. {
  239. sessionId: "new",
  240. messageId: "trace-new",
  241. source: "automation_idle",
  242. workspaceIdentity: state.request.workspaceIdentity,
  243. },
  244. );
  245. expect(state.service.createTask.mock.calls[0]?.[0]).not.toHaveProperty("modelSelection");
  246. expect(state.service.sendPrompt).toHaveBeenCalledWith(
  247. expect.objectContaining({
  248. taskId: "new",
  249. modelSelection: state.request.modelSelection,
  250. modelExecution: expect.objectContaining({ selectionScope: "execution" }),
  251. }),
  252. );
  253. });
  254. it("rejects unavailable fixed selection before requesting ticket auth", async () => {
  255. const state = setup();
  256. state.runtime.validateSelection.mockResolvedValue(false);
  257. await expect(state.dispatch(state.request)).rejects.toThrow(OffPeakModelUnavailableError);
  258. expect(state.runtime.buildRequestAuth).not.toHaveBeenCalled();
  259. expect(state.service.resumeTask).not.toHaveBeenCalled();
  260. });
  261. it("unsubscribes outcome tracking when sending fails", async () => {
  262. const state = setup();
  263. state.service.sendPrompt.mockRejectedValue(new Error("send failed"));
  264. await expect(state.dispatch(state.request)).rejects.toThrow("send failed");
  265. expect(state.track).toHaveBeenCalledOnce();
  266. expect(state.dispose).toHaveBeenCalledWith("bound:idle-1:bound:run-1");
  267. });
  268. });
  269. it("闲时新建首发被拒绝时不报 session_create", async () => {
  270. const state = setup();
  271. state.service.sendPrompt.mockRejectedValue(new Error("rejected"));
  272. await expect(state.dispatch({ ...state.request, sessionId: undefined })).rejects.toThrow(
  273. "rejected",
  274. );
  275. expect(state.report).not.toHaveBeenCalled();
  276. });