mirror of
https://github.com/openclaw/openclaw.git
synced 2026-05-09 00:48:27 +00:00
* refactor: update cron job wake mode and run mode handling - Changed default wake mode from 'next-heartbeat' to 'now' in CronJobEditor and related CLI commands. - Updated cron-tool tests to reflect changes in run mode, introducing 'due' and 'force' options. - Enhanced cron-tool logic to handle new run modes and ensure compatibility with existing job structures. - Added new tests for delivery plan consistency and job execution behavior under various conditions. - Improved normalization functions to handle wake mode and session target casing. This refactor aims to streamline cron job configurations and enhance the overall user experience with clearer defaults and improved functionality. * test: enhance cron job functionality and UI - Added tests to ensure the isolated agent correctly announces the final payload text when delivering messages via Telegram. - Implemented a new function to pick the last deliverable payload from a list of delivery payloads. - Enhanced the cron service to maintain legacy "every" jobs while minute cron jobs recompute schedules. - Updated the cron store migration tests to verify the addition of anchorMs to legacy every schedules. - Improved the UI for displaying cron job details, including job state and delivery information, with new styles and layout adjustments. These changes aim to improve the reliability and user experience of the cron job system. * test: enhance sessions thinking level handling - Added tests to verify that the correct thinking levels are applied during session spawning. - Updated the sessions-spawn-tool to include a new parameter for overriding thinking levels. - Enhanced the UI to support additional thinking levels, including "xhigh" and "full", and improved the handling of current options in dropdowns. These changes aim to improve the flexibility and accuracy of thinking level configurations in session management. * feat: enhance session management and cron job functionality - Introduced passthrough arguments in the test-parallel script to allow for flexible command-line options. - Updated session handling to hide cron run alias session keys from the sessions list, improving clarity. - Enhanced the cron service to accurately record job start times and durations, ensuring better tracking of job execution. - Added tests to verify the correct behavior of the cron service under various conditions, including zero-delay timers. These changes aim to improve the usability and reliability of session and cron job management. * feat: implement job running state checks in cron service - Added functionality to prevent manual job runs if a job is already in progress, enhancing job management. - Updated the `isJobDue` function to include checks for running jobs, ensuring accurate scheduling. - Enhanced the `run` function to return a specific reason when a job is already running. - Introduced a new test case to verify the behavior of forced manual runs during active job execution. These changes aim to improve the reliability and clarity of cron job execution and management. * feat: add session ID and key to CronRunLogEntry model - Introduced `sessionid` and `sessionkey` properties to the `CronRunLogEntry` struct for enhanced tracking of session-related information. - Updated the initializer and Codable conformance to accommodate the new properties, ensuring proper serialization and deserialization. These changes aim to improve the granularity of logging and session management within the cron job system. * fix: improve session display name resolution - Updated the `resolveSessionDisplayName` function to ensure that both label and displayName are trimmed and default to an empty string if not present. - Enhanced the logic to prevent returning the key if it matches the label or displayName, improving clarity in session naming. These changes aim to enhance the accuracy and usability of session display names in the UI. * perf: skip cron store persist when idle timer tick produces no changes recomputeNextRuns now returns a boolean indicating whether any job state was mutated. The idle path in onTimer only persists when the return value is true, eliminating unnecessary file writes every 60s for far-future or idle schedules. * fix: prep for merge - explicit delivery mode migration, docs + changelog (#10776) (thanks @tyler6204)
226 lines
7.0 KiB
TypeScript
226 lines
7.0 KiB
TypeScript
import fs from "node:fs/promises";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import type { CronJob } from "./types.js";
|
|
import { CronService } from "./service.js";
|
|
|
|
const noopLogger = {
|
|
debug: vi.fn(),
|
|
info: vi.fn(),
|
|
warn: vi.fn(),
|
|
error: vi.fn(),
|
|
};
|
|
|
|
async function makeStorePath() {
|
|
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-cron-"));
|
|
return {
|
|
storePath: path.join(dir, "cron", "jobs.json"),
|
|
cleanup: async () => {
|
|
await fs.rm(dir, { recursive: true, force: true });
|
|
},
|
|
};
|
|
}
|
|
|
|
async function waitForJob(
|
|
cron: CronService,
|
|
id: string,
|
|
predicate: (job: CronJob | undefined) => boolean,
|
|
) {
|
|
let latest: CronJob | undefined;
|
|
for (let i = 0; i < 30; i++) {
|
|
const jobs = await cron.list({ includeDisabled: true });
|
|
latest = jobs.find((job) => job.id === id);
|
|
if (predicate(latest)) {
|
|
return latest;
|
|
}
|
|
await vi.runOnlyPendingTimersAsync();
|
|
}
|
|
return latest;
|
|
}
|
|
|
|
describe("CronService interval/cron jobs fire on time", () => {
|
|
beforeEach(() => {
|
|
vi.useFakeTimers();
|
|
vi.setSystemTime(new Date("2025-12-13T00:00:00.000Z"));
|
|
noopLogger.debug.mockClear();
|
|
noopLogger.info.mockClear();
|
|
noopLogger.warn.mockClear();
|
|
noopLogger.error.mockClear();
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
it("fires an every-type main job when the timer fires a few ms late", async () => {
|
|
const store = await makeStorePath();
|
|
const enqueueSystemEvent = vi.fn();
|
|
const requestHeartbeatNow = vi.fn();
|
|
|
|
const cron = new CronService({
|
|
storePath: store.storePath,
|
|
cronEnabled: true,
|
|
log: noopLogger,
|
|
enqueueSystemEvent,
|
|
requestHeartbeatNow,
|
|
runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" })),
|
|
});
|
|
|
|
await cron.start();
|
|
const job = await cron.add({
|
|
name: "every 10s check",
|
|
enabled: true,
|
|
schedule: { kind: "every", everyMs: 10_000 },
|
|
sessionTarget: "main",
|
|
wakeMode: "next-heartbeat",
|
|
payload: { kind: "systemEvent", text: "tick" },
|
|
});
|
|
|
|
const firstDueAt = job.state.nextRunAtMs!;
|
|
expect(firstDueAt).toBe(Date.parse("2025-12-13T00:00:00.000Z") + 10_000);
|
|
|
|
// Simulate setTimeout firing 5ms late (the race condition).
|
|
vi.setSystemTime(new Date(firstDueAt + 5));
|
|
await vi.runOnlyPendingTimersAsync();
|
|
|
|
const updated = await waitForJob(cron, job.id, (current) => current?.state.lastStatus === "ok");
|
|
|
|
expect(enqueueSystemEvent).toHaveBeenCalledWith("tick", { agentId: undefined });
|
|
expect(updated?.state.lastStatus).toBe("ok");
|
|
// nextRunAtMs must advance by at least one full interval past the due time.
|
|
expect(updated?.state.nextRunAtMs).toBeGreaterThanOrEqual(firstDueAt + 10_000);
|
|
|
|
cron.stop();
|
|
await store.cleanup();
|
|
});
|
|
|
|
it("fires a cron-expression job when the timer fires a few ms late", async () => {
|
|
const store = await makeStorePath();
|
|
const enqueueSystemEvent = vi.fn();
|
|
const requestHeartbeatNow = vi.fn();
|
|
|
|
// Set time to just before a minute boundary.
|
|
vi.setSystemTime(new Date("2025-12-13T00:00:59.000Z"));
|
|
|
|
const cron = new CronService({
|
|
storePath: store.storePath,
|
|
cronEnabled: true,
|
|
log: noopLogger,
|
|
enqueueSystemEvent,
|
|
requestHeartbeatNow,
|
|
runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" })),
|
|
});
|
|
|
|
await cron.start();
|
|
const job = await cron.add({
|
|
name: "every minute check",
|
|
enabled: true,
|
|
schedule: { kind: "cron", expr: "* * * * *" },
|
|
sessionTarget: "main",
|
|
wakeMode: "next-heartbeat",
|
|
payload: { kind: "systemEvent", text: "cron-tick" },
|
|
});
|
|
|
|
const firstDueAt = job.state.nextRunAtMs!;
|
|
|
|
// Simulate setTimeout firing 5ms late.
|
|
vi.setSystemTime(new Date(firstDueAt + 5));
|
|
await vi.runOnlyPendingTimersAsync();
|
|
|
|
const updated = await waitForJob(cron, job.id, (current) => current?.state.lastStatus === "ok");
|
|
|
|
expect(enqueueSystemEvent).toHaveBeenCalledWith("cron-tick", { agentId: undefined });
|
|
expect(updated?.state.lastStatus).toBe("ok");
|
|
// nextRunAtMs should be the next whole-minute boundary (60s later).
|
|
expect(updated?.state.nextRunAtMs).toBe(firstDueAt + 60_000);
|
|
|
|
cron.stop();
|
|
await store.cleanup();
|
|
});
|
|
|
|
it("keeps legacy every jobs due while minute cron jobs recompute schedules", async () => {
|
|
const store = await makeStorePath();
|
|
const enqueueSystemEvent = vi.fn();
|
|
const requestHeartbeatNow = vi.fn();
|
|
const nowMs = Date.parse("2025-12-13T00:00:00.000Z");
|
|
|
|
await fs.mkdir(path.dirname(store.storePath), { recursive: true });
|
|
await fs.writeFile(
|
|
store.storePath,
|
|
JSON.stringify(
|
|
{
|
|
version: 1,
|
|
jobs: [
|
|
{
|
|
id: "legacy-every",
|
|
name: "legacy every",
|
|
enabled: true,
|
|
createdAtMs: nowMs,
|
|
updatedAtMs: nowMs,
|
|
schedule: { kind: "every", everyMs: 120_000 },
|
|
sessionTarget: "main",
|
|
wakeMode: "now",
|
|
payload: { kind: "systemEvent", text: "sf-tick" },
|
|
state: { nextRunAtMs: nowMs + 120_000 },
|
|
},
|
|
{
|
|
id: "minute-cron",
|
|
name: "minute cron",
|
|
enabled: true,
|
|
createdAtMs: nowMs,
|
|
updatedAtMs: nowMs,
|
|
schedule: { kind: "cron", expr: "* * * * *", tz: "UTC" },
|
|
sessionTarget: "main",
|
|
wakeMode: "now",
|
|
payload: { kind: "systemEvent", text: "minute-tick" },
|
|
state: { nextRunAtMs: nowMs + 60_000 },
|
|
},
|
|
],
|
|
},
|
|
null,
|
|
2,
|
|
),
|
|
"utf-8",
|
|
);
|
|
|
|
const cron = new CronService({
|
|
storePath: store.storePath,
|
|
cronEnabled: true,
|
|
log: noopLogger,
|
|
enqueueSystemEvent,
|
|
requestHeartbeatNow,
|
|
runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" })),
|
|
});
|
|
|
|
await cron.start();
|
|
for (let minute = 1; minute <= 6; minute++) {
|
|
vi.setSystemTime(new Date(nowMs + minute * 60_000));
|
|
const minuteRun = await cron.run("minute-cron", "force");
|
|
expect(minuteRun).toEqual({ ok: true, ran: true });
|
|
}
|
|
|
|
vi.setSystemTime(new Date(nowMs + 6 * 60_000));
|
|
const sfRun = await cron.run("legacy-every", "due");
|
|
expect(sfRun).toEqual({ ok: true, ran: true });
|
|
|
|
const sfRuns = enqueueSystemEvent.mock.calls.filter((args) => args[0] === "sf-tick").length;
|
|
const minuteRuns = enqueueSystemEvent.mock.calls.filter(
|
|
(args) => args[0] === "minute-tick",
|
|
).length;
|
|
expect(minuteRuns).toBeGreaterThan(0);
|
|
expect(sfRuns).toBeGreaterThan(0);
|
|
|
|
const jobs = await cron.list({ includeDisabled: true });
|
|
const sfJob = jobs.find((job) => job.id === "legacy-every");
|
|
expect(sfJob?.state.lastStatus).toBe("ok");
|
|
expect(sfJob?.schedule.kind).toBe("every");
|
|
if (sfJob?.schedule.kind === "every") {
|
|
expect(sfJob.schedule.anchorMs).toBe(nowMs);
|
|
}
|
|
|
|
cron.stop();
|
|
await store.cleanup();
|
|
});
|
|
});
|