desktopCronScheduler.test.ts 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. import { EventEmitter } from "node:events";
  2. import { describe, expect, it, vi } from "vitest";
  3. import { utilityProcess as electronUtilityProcess } from "electron";
  4. import { hostCronRunMessageSchema, hostOffPeakRunMessageSchema } from "@zcode/shared";
  5. import { spawnCronScheduler } from "../src/main/desktopCronScheduler.js";
  6. vi.mock("electron", () => ({
  7. utilityProcess: {
  8. fork: vi.fn(),
  9. },
  10. }));
  11. vi.mock("../src/main/desktopRuntimeEnv.js", () => ({
  12. buildHostProcessEnv: vi.fn(() => ({})),
  13. schedulerModulePath: "/tmp/zcode-scheduler.js",
  14. }));
  15. class MockSchedulerProcess extends EventEmitter {
  16. pid: number | undefined = 12345;
  17. postMessage = vi.fn();
  18. kill = vi.fn(() => true);
  19. }
  20. describe("desktopCronScheduler", () => {
  21. it.each(["cron", "offpeak"] as const)(
  22. "forwards and validates the saved %s project directory snapshot",
  23. async (kind) => {
  24. const child = new MockSchedulerProcess();
  25. const host = { postMessage: vi.fn() };
  26. vi.mocked(electronUtilityProcess.fork).mockReturnValue(child as never);
  27. const scheduler = spawnCronScheduler({
  28. hostProcessLocalEnv: {},
  29. logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
  30. resolveDispatchHost: () => host as never,
  31. });
  32. const execution = {
  33. workspacePath: "/frozen",
  34. workspaceIdentity: "remote:server:s:/frozen",
  35. projectId: "p",
  36. hostId: "remote:server:s",
  37. additionalDirectories: [],
  38. };
  39. child.emit("message", {
  40. ...execution,
  41. type: `${kind}-dispatch-request`,
  42. prompt: "run",
  43. ...(kind === "cron"
  44. ? { automationId: "a", runId: "r" }
  45. : {
  46. offPeakTaskId: "o",
  47. permissionMode: "default",
  48. modelSelection: { providerId: "p", modelId: "m" },
  49. }),
  50. });
  51. const frame = host.postMessage.mock.calls[0]?.[0];
  52. expect(frame).toMatchObject(execution);
  53. expect(
  54. (kind === "cron" ? hostCronRunMessageSchema : hostOffPeakRunMessageSchema).parse(frame),
  55. ).toMatchObject(execution);
  56. const disposing = scheduler.dispose();
  57. child.emit("exit", 0);
  58. await disposing;
  59. },
  60. );
  61. it("立即执行时直接向 scheduler 发送 wake 消息", () => {
  62. const child = new MockSchedulerProcess();
  63. vi.mocked(electronUtilityProcess.fork).mockReturnValue(child as never);
  64. const scheduler = spawnCronScheduler({
  65. hostProcessLocalEnv: {},
  66. logger: {
  67. info: vi.fn(),
  68. warn: vi.fn(),
  69. error: vi.fn(),
  70. },
  71. resolveDispatchHost: () => null,
  72. });
  73. scheduler.wake("automation-1");
  74. expect(child.postMessage).toHaveBeenCalledWith({
  75. type: "scheduler-wake",
  76. automationId: "automation-1",
  77. });
  78. });
  79. it("进入退出状态后停止向 Host 派发新任务", async () => {
  80. const child = new MockSchedulerProcess();
  81. const host = { postMessage: vi.fn() };
  82. vi.mocked(electronUtilityProcess.fork).mockReturnValue(child as never);
  83. const scheduler = spawnCronScheduler({
  84. hostProcessLocalEnv: {},
  85. logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
  86. resolveDispatchHost: () => host as never,
  87. });
  88. const disposing = scheduler.dispose();
  89. child.emit("message", {
  90. type: "cron-dispatch-request",
  91. runId: "run-after-dispose",
  92. automationId: "automation-1",
  93. prompt: "test",
  94. workspacePath: "C:/repo",
  95. });
  96. expect(host.postMessage).not.toHaveBeenCalled();
  97. expect(child.postMessage).toHaveBeenCalledWith({
  98. type: "cron-dispatch-result",
  99. runId: "run-after-dispose",
  100. ok: false,
  101. failureKind: "transient",
  102. error: "app is shutting down",
  103. });
  104. child.emit("exit", 0);
  105. await disposing;
  106. });
  107. it("把 scheduler 自采样本交给资源遥测来源,非法样本丢弃", async () => {
  108. const { selfHeapProcessResourceSampleSource } =
  109. await import("../src/main/processResourceSelfHeapSource.js");
  110. selfHeapProcessResourceSampleSource.reset?.();
  111. const child = new MockSchedulerProcess();
  112. vi.mocked(electronUtilityProcess.fork).mockReturnValue(child as never);
  113. spawnCronScheduler({
  114. hostProcessLocalEnv: {},
  115. logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
  116. resolveDispatchHost: () => null,
  117. });
  118. // 字段缺失的样本在 main 入口丢弃,不抛错。
  119. expect(() =>
  120. child.emit("message", {
  121. type: "scheduler-resource-sample",
  122. sample: { cpuPercent: 1, rssKb: 122_880 },
  123. }),
  124. ).not.toThrow();
  125. child.emit("message", {
  126. type: "scheduler-resource-sample",
  127. sample: { cpuPercent: 1, rssKb: 122_880, heapUsedKb: 24_576 },
  128. });
  129. const heapSamples: Array<[string, number]> = [];
  130. selfHeapProcessResourceSampleSource.sample?.({
  131. now: 0,
  132. addRoleSample: () => {},
  133. addRoleHeapSample: (role, heapUsedKb) => heapSamples.push([role, heapUsedKb]),
  134. addAppProcessTotals: () => {},
  135. });
  136. expect(heapSamples).toEqual([["scheduler", 24_576]]);
  137. });
  138. });