Skip to content

Commit f155a5f

Browse files
authored
Add cron changed plugin hook (#72773)
* feat: add cron changed plugin hook * fix: improve cron_changed hook correctness and code quality - Fix PluginHookGatewayCronDeliveryStatus: replace 'error' with 'unknown' to match internal CronDeliveryStatus enum - Add job snapshot to CronEvent so removed events carry the deleted job - Extract pickDefined helper, replace 14-field verbose spread mapping - Add toPluginCronJob mapper for explicit internal→public type boundary - Fix schedule union: use literal-only kind discriminants for TS narrowing - Use loadConfig() (runtime) instead of params.cfg (startup) in hook ctx - Use formatErrorMessage instead of String(err) for stack preservation - Fix pre-existing getCron TS2322 with explicit cast (matches gateway_start) - Re-export supporting types from hooks.ts for plugin consumers - Add tests: removed events with job, finished with full fields, runtime cfg
1 parent e84ebea commit f155a5f

10 files changed

Lines changed: 391 additions & 14 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,7 @@ Docs: https://docs.openclaw.ai
299299

300300
- Control UI/Talk: add a generic browser realtime transport contract, Google Live browser Talk sessions with constrained ephemeral tokens, and a Gateway relay for backend-only realtime voice plugins. Thanks @VACInc.
301301
- CLI/models: route provider-filtered model listing through an explicit source plan so user config, installed manifest rows, Provider Index previews, and scoped runtime fallbacks keep a stable authority order without adding another catalog cache. Thanks @shakkernerd.
302+
- Plugins/cron: add a typed `cron_changed` hook for observing gateway-owned cron lifecycle updates without depending on internal cron events. Thanks @amknight.
302303
- Providers: add Cerebras as a bundled plugin with onboarding, static model catalog, docs, and manifest-owned endpoint metadata.
303304
- Memory/OpenAI-compatible: add optional `memorySearch.inputType`, `queryInputType`, and `documentInputType` config for asymmetric embedding endpoints, including direct query embeddings and provider batch indexing. Carries forward #63313 and #60727. Thanks @HOYALIM and @prospect1314521.
304305
- Ollama/memory: add model-specific retrieval query prefixes for `nomic-embed-text`, `qwen3-embedding`, and `mxbai-embed-large` memory-search queries while leaving document batches unchanged. Carries forward #45013. Thanks @laolin5564.

‎docs/plugins/sdk-overview.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,7 @@ semantics.
300300
- `message_received`: use the typed `threadId` field when you need inbound thread/topic routing. Keep `metadata` for channel-specific extras.
301301
- `message_sending`: use typed `replyToId` / `threadId` routing fields before falling back to channel-specific `metadata`.
302302
- `gateway_start`: use `ctx.config`, `ctx.workspaceDir`, and `ctx.getCron?.()` for gateway-owned startup state instead of relying on internal `gateway:startup` hooks.
303+
- `cron_changed`: observe gateway-owned cron lifecycle changes. Use `event.job?.state?.nextRunAtMs` and `ctx.getCron?.()` when syncing external wake schedulers, and keep OpenClaw as the source of truth for due checks and execution.
303304

304305
### API object fields
305306

‎src/cron/service/ops.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,7 @@ export async function start(state: CronServiceState) {
183183
emit(state, {
184184
jobId: interrupted.jobId,
185185
action: "finished",
186+
job,
186187
status: "error",
187188
error: STARTUP_INTERRUPTED_ERROR,
188189
delivered: false,
@@ -338,6 +339,7 @@ export async function add(state: CronServiceState, input: CronJobCreate) {
338339
emit(state, {
339340
jobId: job.id,
340341
action: "added",
342+
job,
341343
nextRunAtMs: job.state.nextRunAtMs,
342344
});
343345
return job;
@@ -387,6 +389,7 @@ export async function update(state: CronServiceState, id: string, patch: CronJob
387389
emit(state, {
388390
jobId: id,
389391
action: "updated",
392+
job,
390393
nextRunAtMs: job.state.nextRunAtMs,
391394
});
392395
return job;
@@ -401,12 +404,13 @@ export async function remove(state: CronServiceState, id: string) {
401404
if (!state.store) {
402405
return { ok: false, removed: false } as const;
403406
}
407+
const removedJob = state.store.jobs.find((j) => j.id === id);
404408
state.store.jobs = state.store.jobs.filter((j) => j.id !== id);
405409
const removed = (state.store.jobs.length ?? 0) !== before;
406410
await persist(state);
407411
armTimer(state);
408412
if (removed) {
409-
emit(state, { jobId: id, action: "removed" });
413+
emit(state, { jobId: id, action: "removed", job: removedJob });
410414
}
411415
return { ok: true, removed } as const;
412416
});
@@ -637,7 +641,7 @@ async function prepareManualRun(
637641
// Persist the running marker before releasing lock so timer ticks that
638642
// force-reload from disk cannot start the same job concurrently.
639643
await persist(state);
640-
emit(state, { jobId: job.id, action: "started", runAtMs: preflight.now });
644+
emit(state, { jobId: job.id, action: "started", job, runAtMs: preflight.now });
641645
const taskRunId = tryCreateManualTaskRun({
642646
state,
643647
job,
@@ -701,6 +705,7 @@ async function finishPreparedManualRun(
701705
emit(state, {
702706
jobId: job.id,
703707
action: "finished",
708+
job,
704709
status: coreResult.status,
705710
error: coreResult.error,
706711
summary: coreResult.summary,
@@ -720,7 +725,7 @@ async function finishPreparedManualRun(
720725

721726
if (shouldDelete && state.store) {
722727
state.store.jobs = state.store.jobs.filter((entry) => entry.id !== job.id);
723-
emit(state, { jobId: job.id, action: "removed" });
728+
emit(state, { jobId: job.id, action: "removed", job });
724729
}
725730

726731
// Manual runs should not advance other due jobs without executing them.

‎src/cron/service/state.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ import type {
1616
export type CronEvent = {
1717
jobId: string;
1818
action: "added" | "updated" | "removed" | "started" | "finished";
19+
/** Snapshot of the job at the time of the event. Present for all actions where the job is accessible. */
20+
job?: CronJob;
1921
runAtMs?: number;
2022
durationMs?: number;
2123
status?: CronRunStatus;

‎src/cron/service/timer.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -670,7 +670,7 @@ function applyOutcomeToStoredJob(state: CronServiceState, result: TimedCronRunOu
670670

671671
if (shouldDelete) {
672672
store.jobs = jobs.filter((entry) => entry.id !== job.id);
673-
emit(state, { jobId: job.id, action: "removed" });
673+
emit(state, { jobId: job.id, action: "removed", job });
674674
}
675675
}
676676

@@ -803,7 +803,7 @@ export async function onTimer(state: CronServiceState) {
803803
const startedAt = state.deps.nowMs();
804804
job.state.runningAtMs = startedAt;
805805
markCronJobActive(job.id);
806-
emit(state, { jobId: job.id, action: "started", runAtMs: startedAt });
806+
emit(state, { jobId: job.id, action: "started", job, runAtMs: startedAt });
807807
const jobTimeoutMs = resolveCronJobTimeoutMs(job);
808808
const taskRunId = tryCreateCronTaskRun({ state, job, startedAt });
809809

@@ -1109,7 +1109,12 @@ async function runStartupCatchupCandidate(
11091109
job: candidate.job,
11101110
startedAt,
11111111
});
1112-
emit(state, { jobId: candidate.job.id, action: "started", runAtMs: startedAt });
1112+
emit(state, {
1113+
jobId: candidate.job.id,
1114+
action: "started",
1115+
job: candidate.job,
1116+
runAtMs: startedAt,
1117+
});
11131118
try {
11141119
const result = await executeJobCoreWithTimeout(state, candidate.job);
11151120
return {
@@ -1408,7 +1413,7 @@ export async function executeJob(
14081413
job.state.runningAtMs = startedAt;
14091414
job.state.lastError = undefined;
14101415
markCronJobActive(job.id);
1411-
emit(state, { jobId: job.id, action: "started", runAtMs: startedAt });
1416+
emit(state, { jobId: job.id, action: "started", job, runAtMs: startedAt });
14121417

14131418
let coreResult: {
14141419
status: CronRunStatus;
@@ -1435,7 +1440,7 @@ export async function executeJob(
14351440

14361441
if (shouldDelete && state.store) {
14371442
state.store.jobs = state.store.jobs.filter((j) => j.id !== job.id);
1438-
emit(state, { jobId: job.id, action: "removed" });
1443+
emit(state, { jobId: job.id, action: "removed", job });
14391444
}
14401445
clearCronJobActive(job.id);
14411446
}
@@ -1454,6 +1459,7 @@ function emitJobFinished(
14541459
emit(state, {
14551460
jobId: job.id,
14561461
action: "finished",
1462+
job,
14571463
status: result.status,
14581464
error: result.error,
14591465
summary: result.summary,

‎src/gateway/server-cron.test.ts‎

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ const {
1414
fetchWithSsrFGuardMock,
1515
runCronIsolatedAgentTurnMock,
1616
cleanupBrowserSessionsForLifecycleEndMock,
17+
getGlobalHookRunnerMock,
18+
runCronChangedMock,
1719
} = vi.hoisted(() => ({
1820
enqueueSystemEventMock: vi.fn(),
1921
requestHeartbeatNowMock: vi.fn(),
@@ -24,6 +26,11 @@ const {
2426
fetchWithSsrFGuardMock: vi.fn(),
2527
runCronIsolatedAgentTurnMock: vi.fn(async () => ({ status: "ok" as const, summary: "ok" })),
2628
cleanupBrowserSessionsForLifecycleEndMock: vi.fn(async () => {}),
29+
runCronChangedMock: vi.fn(async () => {}),
30+
getGlobalHookRunnerMock: vi.fn(() => ({
31+
hasHooks: (hookName: string) => hookName === "cron_changed",
32+
runCronChanged: runCronChangedMock,
33+
})),
2734
}));
2835

2936
function enqueueSystemEvent(...args: unknown[]) {
@@ -65,6 +72,14 @@ vi.mock("../config/config.js", async () => {
6572
};
6673
});
6774

75+
vi.mock("../config/io.js", async () => {
76+
const actual = await vi.importActual<typeof import("../config/io.js")>("../config/io.js");
77+
return {
78+
...actual,
79+
getRuntimeConfig: () => loadConfigMock(),
80+
};
81+
});
82+
6883
vi.mock("../infra/net/fetch-guard.js", () => ({
6984
fetchWithSsrFGuard: fetchWithSsrFGuardMock,
7085
}));
@@ -77,6 +92,10 @@ vi.mock("../browser-lifecycle-cleanup.js", () => ({
7792
cleanupBrowserSessionsForLifecycleEnd: cleanupBrowserSessionsForLifecycleEndMock,
7893
}));
7994

95+
vi.mock("../plugins/hook-runner-global.js", () => ({
96+
getGlobalHookRunner: getGlobalHookRunnerMock,
97+
}));
98+
8099
import { buildGatewayCronService } from "./server-cron.js";
81100

82101
function createCronConfig(name: string): OpenClawConfig {
@@ -100,6 +119,121 @@ describe("buildGatewayCronService", () => {
100119
fetchWithSsrFGuardMock.mockClear();
101120
runCronIsolatedAgentTurnMock.mockClear();
102121
cleanupBrowserSessionsForLifecycleEndMock.mockClear();
122+
runCronChangedMock.mockClear();
123+
getGlobalHookRunnerMock.mockClear();
124+
getGlobalHookRunnerMock.mockReturnValue({
125+
hasHooks: (hookName: string) => hookName === "cron_changed",
126+
runCronChanged: runCronChangedMock,
127+
});
128+
});
129+
130+
it("emits cron_changed hooks with computed next run state", async () => {
131+
const cfg = createCronConfig("server-cron-hook");
132+
loadConfigMock.mockReturnValue(cfg);
133+
134+
const state = buildGatewayCronService({
135+
cfg,
136+
deps: {} as CliDeps,
137+
broadcast: () => {},
138+
});
139+
try {
140+
const job = await state.cron.add({
141+
name: "scheduler-hook",
142+
enabled: true,
143+
schedule: { kind: "every", everyMs: 60_000, anchorMs: 1_000 },
144+
sessionTarget: "main",
145+
wakeMode: "next-heartbeat",
146+
payload: { kind: "systemEvent", text: "sync external wake" },
147+
});
148+
149+
expect(runCronChangedMock).toHaveBeenCalledWith(
150+
expect.objectContaining({
151+
action: "added",
152+
jobId: job.id,
153+
job: expect.objectContaining({
154+
id: job.id,
155+
state: expect.objectContaining({ nextRunAtMs: job.state.nextRunAtMs }),
156+
}),
157+
}),
158+
expect.objectContaining({
159+
config: cfg,
160+
getCron: expect.any(Function),
161+
}),
162+
);
163+
} finally {
164+
state.cron.stop();
165+
}
166+
});
167+
168+
it("cron_changed removed events include the deleted job snapshot", async () => {
169+
const cfg = createCronConfig("server-cron-hook-removed");
170+
loadConfigMock.mockReturnValue(cfg);
171+
172+
const state = buildGatewayCronService({
173+
cfg,
174+
deps: {} as CliDeps,
175+
broadcast: () => {},
176+
});
177+
try {
178+
const job = await state.cron.add({
179+
name: "to-be-removed",
180+
enabled: true,
181+
schedule: { kind: "every", everyMs: 60_000, anchorMs: 1_000 },
182+
sessionTarget: "main",
183+
wakeMode: "next-heartbeat",
184+
payload: { kind: "systemEvent", text: "will be removed" },
185+
});
186+
187+
runCronChangedMock.mockClear();
188+
await state.cron.remove(job.id);
189+
190+
expect(runCronChangedMock).toHaveBeenCalledWith(
191+
expect.objectContaining({
192+
action: "removed",
193+
jobId: job.id,
194+
job: expect.objectContaining({
195+
id: job.id,
196+
name: "to-be-removed",
197+
}),
198+
}),
199+
expect.objectContaining({
200+
getCron: expect.any(Function),
201+
}),
202+
);
203+
} finally {
204+
state.cron.stop();
205+
}
206+
});
207+
208+
it("cron_changed hook context uses runtime config from getRuntimeConfig()", async () => {
209+
const startupCfg = createCronConfig("server-cron-hook-runtime-cfg");
210+
const runtimeCfg = { ...startupCfg, _marker: "runtime" };
211+
loadConfigMock.mockReturnValue(runtimeCfg);
212+
213+
const state = buildGatewayCronService({
214+
cfg: startupCfg,
215+
deps: {} as CliDeps,
216+
broadcast: () => {},
217+
});
218+
try {
219+
await state.cron.add({
220+
name: "runtime-cfg-check",
221+
enabled: true,
222+
schedule: { kind: "every", everyMs: 60_000, anchorMs: 1_000 },
223+
sessionTarget: "main",
224+
wakeMode: "next-heartbeat",
225+
payload: { kind: "systemEvent", text: "cfg check" },
226+
});
227+
228+
// The hook context should use getRuntimeConfig() (runtimeCfg), not startupCfg
229+
expect(runCronChangedMock).toHaveBeenCalledTimes(1);
230+
const calls = runCronChangedMock.mock.calls as unknown[][];
231+
const hookCtx = calls[0]?.[1] as { config?: unknown } | undefined;
232+
expect(hookCtx?.config).toBe(runtimeCfg);
233+
expect(hookCtx?.config).not.toBe(startupCfg);
234+
} finally {
235+
state.cron.stop();
236+
}
103237
});
104238

105239
it("routes main-target jobs to the scoped session for enqueue + wake", async () => {

0 commit comments

Comments
 (0)