cronHostSessionCreateTelemetry.test.ts 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import { readFile } from "node:fs/promises";
  2. import ts from "typescript";
  3. import { beforeAll, describe, expect, it, vi } from "vitest";
  4. let createDispatch: (
  5. deps: Record<string, unknown>,
  6. ) => (request: Record<string, unknown>) => Promise<unknown>;
  7. beforeAll(async () => {
  8. // 装载生产函数,隔离 host 启动副作用;不复制派发实现。
  9. const path = new URL("../src/host/index.ts", import.meta.url);
  10. const source = ts.createSourceFile(
  11. path.pathname,
  12. await readFile(path, "utf8"),
  13. ts.ScriptTarget.Latest,
  14. true,
  15. );
  16. const fn = source.statements.find(
  17. (node): node is ts.FunctionDeclaration =>
  18. ts.isFunctionDeclaration(node) && node.name?.text === "dispatchCronRun",
  19. );
  20. if (!fn) throw new Error("dispatchCronRun missing");
  21. const code = ts.transpileModule(fn.getText(source), {
  22. compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },
  23. }).outputText;
  24. createDispatch = (deps) =>
  25. new Function(...Object.keys(deps), `${code}; return dispatchCronRun;`)(...Object.values(deps));
  26. });
  27. function setup() {
  28. const service = {
  29. createTask: vi.fn(async () => ({ taskId: "new-session" })),
  30. resumeTask: vi.fn(async () => {}),
  31. sendPrompt: vi.fn(async () => {}),
  32. };
  33. const report = vi.fn();
  34. const taskKey = Symbol(),
  35. modelKey = Symbol(),
  36. botsKey = Symbol();
  37. const selection = { providerId: "test", modelId: "test" };
  38. const dispatch = createDispatch({
  39. IZCodeTaskService: taskKey,
  40. IModelSelectionService: modelKey,
  41. IBotsService: botsKey,
  42. resolveAutomationTargetServices: () => ({
  43. getOptional: (key: symbol) => (key === taskKey ? service : key === modelKey ? {} : undefined),
  44. }),
  45. cronAutomationRepo: { getRun: async () => null, fixRunModelSelection: async () => selection },
  46. resolveAutomationSubmissionModelSelection: async () => selection,
  47. resolveWorkspaceKey: () => "workspace",
  48. formatModelPickerValue: () => "test/test",
  49. parseCronRunScheduledAt: () => 1,
  50. applyCronRunConfigToExistingTask: async () => {},
  51. cronRunSubscriptionKey: () => "key",
  52. trackCronRunOutcome: vi.fn(),
  53. disposeCronRunSubscription: vi.fn(),
  54. markCronRunOutcome: vi.fn(),
  55. reportHostSessionCreate: report,
  56. parentPort: {},
  57. });
  58. const request = {
  59. automationId: "a1",
  60. runId: "a1:1000",
  61. workspacePath: "/private",
  62. workspaceIdentity: "remote:ssh:host:/private",
  63. prompt: "prompt",
  64. };
  65. return { service, report, dispatch, request };
  66. }
  67. describe("定时任务的 Session 创建口径", () => {
  68. it.each(["a1:1000", "a1:manual:1000"])("新建会话 %s 首发 accepted 后才报告", async (runId) => {
  69. const state = setup();
  70. let accept!: () => void;
  71. state.service.sendPrompt.mockImplementation(
  72. () =>
  73. new Promise<void>((resolve) => {
  74. accept = resolve;
  75. }),
  76. );
  77. const dispatched = state.dispatch({ ...state.request, runId });
  78. await vi.waitFor(() => expect(state.service.sendPrompt).toHaveBeenCalledOnce());
  79. expect(state.report).not.toHaveBeenCalled();
  80. accept();
  81. await dispatched;
  82. expect(state.report).toHaveBeenCalledExactlyOnceWith(
  83. {},
  84. {
  85. sessionId: "new-session",
  86. messageId: runId,
  87. source: "automation_scheduled",
  88. workspaceIdentity: state.request.workspaceIdentity,
  89. },
  90. );
  91. });
  92. it("prompt 创建的任务绑定原会话,多次追加都不报告", async () => {
  93. const state = setup();
  94. await state.dispatch({ ...state.request, targetTaskId: "existing" });
  95. await state.dispatch({ ...state.request, runId: "a1:2000", targetTaskId: "existing" });
  96. expect(state.service.createTask).not.toHaveBeenCalled();
  97. expect(state.service.resumeTask).toHaveBeenCalledTimes(2);
  98. expect(state.service.sendPrompt).toHaveBeenCalledTimes(2);
  99. expect(state.report).not.toHaveBeenCalled();
  100. });
  101. it("新建后首发拒绝不报告", async () => {
  102. const state = setup();
  103. state.service.sendPrompt.mockRejectedValue(new Error("rejected"));
  104. await expect(state.dispatch(state.request)).rejects.toThrow("rejected");
  105. expect(state.report).not.toHaveBeenCalled();
  106. });
  107. });