offPeakHostDispatch.test.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. listTasks: vi.fn(async () => [{ taskId: "bound", status: "completed" }]),
  39. resumeTask: vi.fn(async () => {}),
  40. setConfigOption: vi.fn(async () => {}),
  41. createTask: vi.fn(async (_params: Record<string, unknown>) => ({
  42. taskId: "new",
  43. traceId: "trace-new",
  44. })),
  45. sendPrompt: vi.fn(async () => {}),
  46. };
  47. const runtime = {
  48. validateSelection: vi.fn(async () => true),
  49. buildRequestAuth: vi.fn(async () => ({ apiKey: "test-ticket-auth" })),
  50. };
  51. const dispose = vi.fn();
  52. const track = vi.fn();
  53. const report = vi.fn();
  54. const dispatch = createDispatch({
  55. activeServices: { getOptional: () => service },
  56. reportHostSessionCreate: report,
  57. parentPort: {},
  58. IZCodeTaskService: Symbol("task-service"),
  59. ensureOffPeakRuntime: async () => runtime,
  60. OffPeakModelUnavailableError,
  61. resolveOffPeakDispatchKind,
  62. assertBoundSessionDispatchable,
  63. randomUUID: () => "run-1",
  64. OFF_PEAK_RESUME_PROMPT: "resume prompt",
  65. offPeakRunSubscriptionKey: (taskId: string, traceId: string) => `${taskId}:${traceId}`,
  66. trackOffPeakRunOutcome: track,
  67. disposeOffPeakRunSubscription: dispose,
  68. });
  69. const modelSelection = {
  70. providerId: OFF_PEAK_PROVIDER_IDS.bigmodel,
  71. modelId: "GLM-5.2",
  72. options: { reasoningLevel: "high" },
  73. };
  74. const request = {
  75. offPeakTaskId: "idle-1",
  76. prompt: "task prompt",
  77. permissionMode: "yolo",
  78. modelSelection,
  79. sessionId: "bound",
  80. serverTicketId: "ticket-1",
  81. workspacePath: "/project",
  82. workspaceIdentity: "remote:ssh:test:/project",
  83. };
  84. return { service, runtime, dispose, track, report, dispatch, request };
  85. }
  86. describe("Host OffPeak dispatch current execution contract", () => {
  87. it.each(["bound-first-run", "resume"])(
  88. "%s keeps idle reasoning out of persisted Session config",
  89. async (kind) => {
  90. const state = setup();
  91. const request = {
  92. ...state.request,
  93. ...(kind === "resume" ? { conversationId: "bound" } : {}),
  94. };
  95. await expect(state.dispatch(request)).resolves.toEqual({
  96. conversationId: "bound",
  97. sessionId: "bound",
  98. });
  99. expect(state.service.setConfigOption.mock.calls).toHaveLength(1);
  100. expect(state.service.setConfigOption).toHaveBeenCalledWith(
  101. expect.objectContaining({ configId: "mode", value: "yolo" }),
  102. );
  103. expect(state.service.sendPrompt).toHaveBeenCalledWith(
  104. expect.objectContaining({
  105. taskId: "bound",
  106. modelSelection: state.request.modelSelection,
  107. content: kind === "resume" ? "resume prompt" : "task prompt",
  108. toolDenylist: ["CronCreate", "OffPeakCreate"],
  109. modelExecution: {
  110. memoryExtraction: "skip",
  111. selectionScope: "execution",
  112. requestAuth: { apiKey: "test-ticket-auth" },
  113. subagents: { foregroundModel: "submission", background: "deny" },
  114. },
  115. }),
  116. );
  117. expect(state.service.createTask).not.toHaveBeenCalled();
  118. expect(state.report).not.toHaveBeenCalled();
  119. expect(state.service.resumeTask).toHaveBeenCalledWith(
  120. expect.objectContaining({
  121. workspaceIdentity: request.workspaceIdentity,
  122. offPeakTaskId: "idle-1",
  123. }),
  124. );
  125. },
  126. );
  127. it.each(["busy", "deleted"])(
  128. "bound session %s fails before config writes or dispatch",
  129. async (kind) => {
  130. const state = setup();
  131. if (kind === "busy")
  132. state.service.listTasks.mockResolvedValue([{ taskId: "bound", status: "running" }]);
  133. else state.service.listDeletedTaskIds.mockResolvedValue(["bound"]);
  134. await expect(state.dispatch(state.request)).rejects.toThrow(
  135. kind === "busy" ? "is busy" : "was deleted",
  136. );
  137. expect(state.service.resumeTask).not.toHaveBeenCalled();
  138. expect(state.service.setConfigOption).not.toHaveBeenCalled();
  139. expect(state.service.sendPrompt).not.toHaveBeenCalled();
  140. },
  141. );
  142. it("new session uses its ordinary initial selection, while dispatch keeps the frozen idle selection", async () => {
  143. const state = setup();
  144. await state.dispatch({ ...state.request, sessionId: undefined });
  145. expect(state.service.createTask).toHaveBeenCalledWith(
  146. expect.objectContaining({
  147. offPeakTaskId: "idle-1",
  148. deferPersistenceUntilFirstPrompt: true,
  149. }),
  150. );
  151. expect(state.report).toHaveBeenCalledExactlyOnceWith(
  152. {},
  153. {
  154. sessionId: "new",
  155. messageId: "trace-new",
  156. source: "automation_idle",
  157. workspaceIdentity: state.request.workspaceIdentity,
  158. },
  159. );
  160. expect(state.service.createTask.mock.calls[0]?.[0]).not.toHaveProperty("modelSelection");
  161. expect(state.service.sendPrompt).toHaveBeenCalledWith(
  162. expect.objectContaining({
  163. taskId: "new",
  164. modelSelection: state.request.modelSelection,
  165. modelExecution: expect.objectContaining({ selectionScope: "execution" }),
  166. }),
  167. );
  168. });
  169. it("rejects unavailable fixed selection before requesting ticket auth", async () => {
  170. const state = setup();
  171. state.runtime.validateSelection.mockResolvedValue(false);
  172. await expect(state.dispatch(state.request)).rejects.toThrow(OffPeakModelUnavailableError);
  173. expect(state.runtime.buildRequestAuth).not.toHaveBeenCalled();
  174. expect(state.service.resumeTask).not.toHaveBeenCalled();
  175. });
  176. it("unsubscribes outcome tracking when sending fails", async () => {
  177. const state = setup();
  178. state.service.sendPrompt.mockRejectedValue(new Error("send failed"));
  179. await expect(state.dispatch(state.request)).rejects.toThrow("send failed");
  180. expect(state.track).toHaveBeenCalledOnce();
  181. expect(state.dispose).toHaveBeenCalledWith("bound:idle-1:bound:run-1");
  182. });
  183. });
  184. it("闲时新建首发被拒绝时不报 session_create", async () => {
  185. const state = setup();
  186. state.service.sendPrompt.mockRejectedValue(new Error("rejected"));
  187. await expect(state.dispatch({ ...state.request, sessionId: undefined })).rejects.toThrow(
  188. "rejected",
  189. );
  190. expect(state.report).not.toHaveBeenCalled();
  191. });