Skip to content

Commit 9d415c8

Browse files
vincentkochaishmg
andcommitted
feat(cron): include run time in failure alerts
Co-authored-by: haishmg <[email protected]>
1 parent cc48aef commit 9d415c8

10 files changed

Lines changed: 216 additions & 5 deletions

‎docs/automation/cron-jobs.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,8 @@ Failure notifications follow a separate destination path:
343343
- `failureAlert.includeSkipped: true` opts a job or global cron alert policy into repeated skipped-run alerts. Skipped runs keep a separate consecutive-skip counter, so they do not affect execution-error backoff.
344344
- `openclaw cron edit` exposes per-job alert tuning: `--failure-alert`/`--no-failure-alert`, `--failure-alert-after <n>`, `--failure-alert-channel`, `--failure-alert-to`, `--failure-alert-cooldown`, `--failure-alert-include-skipped`/`--failure-alert-exclude-skipped`, `--failure-alert-mode`, and `--failure-alert-account-id`.
345345

346+
Chat failure notifications include the run start time in the agent's configured user timezone. Webhook message text stays stable; integrations can read the same instant from the structured `runAtMs` field.
347+
346348
### Output language
347349

348350
Cron jobs do not infer a reply language from channel, locale, or previous messages. Put the language rule in the scheduled message or template:

‎docs/cli/cron.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,8 @@ Failure notifications resolve in this order:
110110
Main-session jobs may only use `delivery.failureDestination` when primary delivery mode is `webhook`. Isolated jobs accept it in all modes.
111111
</Note>
112112

113+
Chat failure notifications include the run start time in the agent's configured user timezone. Webhook message text stays stable and exposes the instant as `runAtMs`.
114+
113115
Isolated cron runs treat run-level agent failures as job errors even when no reply payload is produced, so model/provider failures still increment error counters and trigger failure notifications.
114116

115117
Command cron jobs do not start an isolated agent turn. A zero exit code records `ok`; non-zero exit, signal, timeout, or no-output timeout records `error` and can trigger the same failure notification path.

‎src/cron/service/failure-alerts.account-routing.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest";
22
import type { CronJob } from "../types.js";
33
import { resolveFailureAlert } from "./failure-alerts.js";
44
import { createCronServiceState } from "./state.js";
5+
import { applyJobResult } from "./timer.js";
56

67
describe("cron failure alert account routing", () => {
78
it.each([
@@ -79,4 +80,44 @@ describe("cron failure alert account routing", () => {
7980

8081
expect(resolveFailureAlert(state, job)).toMatchObject(expected);
8182
});
83+
84+
it("carries run start time without using it for alert cooldown", () => {
85+
const runAtMs = Date.parse("2026-07-30T00:00:00.000Z");
86+
const endedAt = runAtMs + 5 * 60_000;
87+
const sendCronFailureAlert = vi.fn(async () => undefined);
88+
const state = createCronServiceState({
89+
storePath: "/tmp/openclaw-cron-failure-alert-run-time.json",
90+
cronEnabled: true,
91+
cronConfig: { failureAlert: { enabled: true, after: 1, cooldownMs: 60_000 } },
92+
log: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
93+
nowMs: () => endedAt,
94+
enqueueSystemEvent: vi.fn(),
95+
requestHeartbeat: vi.fn(),
96+
sendCronFailureAlert,
97+
runIsolatedAgentJob: vi.fn(async () => ({ status: "ok" as const })),
98+
});
99+
const job: CronJob = {
100+
id: "failed-run",
101+
name: "Failed run",
102+
enabled: true,
103+
createdAtMs: runAtMs,
104+
updatedAtMs: runAtMs,
105+
schedule: { kind: "every", everyMs: 60_000 },
106+
sessionTarget: "isolated",
107+
wakeMode: "next-heartbeat",
108+
payload: { kind: "agentTurn", message: "report" },
109+
delivery: { mode: "announce", channel: "telegram", to: "telegram:19098680" },
110+
state: {},
111+
};
112+
113+
applyJobResult(state, job, {
114+
status: "error",
115+
error: "provider unavailable",
116+
startedAt: runAtMs,
117+
endedAt,
118+
});
119+
120+
expect(sendCronFailureAlert).toHaveBeenCalledWith(expect.objectContaining({ runAtMs }));
121+
expect(job.state.lastFailureAlertAtMs).toBe(endedAt);
122+
});
82123
});

‎src/cron/service/failure-alerts.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,7 @@ function emitFailureAlert(
137137
job: CronJob;
138138
error?: string;
139139
errorReason?: FailoverReason;
140+
runAtMs?: number;
140141
consecutiveErrors: number;
141142
channel: CronMessageChannel;
142143
to?: string;
@@ -163,6 +164,7 @@ function emitFailureAlert(
163164
.sendCronFailureAlert({
164165
job: params.job,
165166
text,
167+
runAtMs: params.runAtMs,
166168
channel: params.channel,
167169
to: params.to,
168170
mode: params.mode,
@@ -196,6 +198,7 @@ export function maybeEmitFailureAlert(
196198
status: "error" | "skipped";
197199
error?: string;
198200
errorReason?: FailoverReason;
201+
runAtMs?: number;
199202
consecutiveCount: number;
200203
delivery?: "emit" | "record-only";
201204
occurredAtMs?: number;
@@ -232,6 +235,7 @@ export function maybeEmitFailureAlert(
232235
job: params.job,
233236
error: params.error,
234237
errorReason: params.errorReason,
238+
runAtMs: params.runAtMs,
235239
consecutiveErrors: params.consecutiveCount,
236240
channel: params.alertConfig.channel,
237241
to: params.alertConfig.to,

‎src/cron/service/state.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,7 @@ export type CronServiceDeps = {
219219
sendCronFailureAlert?: (params: {
220220
job: CronJob;
221221
text: string;
222+
runAtMs?: number;
222223
channel: CronMessageChannel;
223224
to?: string;
224225
mode?: "announce" | "webhook";

‎src/cron/service/timer-outcomes.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ export function applyJobResult(
132132
status: "error",
133133
error: result.error,
134134
errorReason: job.state.lastErrorReason,
135+
runAtMs: result.startedAt,
135136
consecutiveCount: job.state.consecutiveErrors,
136137
...(opts?.replayFailureAlertAtMs !== undefined
137138
? { delivery: "record-only" as const, occurredAtMs: opts.replayFailureAlertAtMs }
@@ -146,6 +147,7 @@ export function applyJobResult(
146147
alertConfig,
147148
status: "skipped",
148149
error: result.error,
150+
runAtMs: result.startedAt,
149151
consecutiveCount: job.state.consecutiveSkipped,
150152
...(opts?.replayFailureAlertAtMs !== undefined
151153
? { delivery: "record-only" as const, occurredAtMs: opts.replayFailureAlertAtMs }

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

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,65 @@ describe("dispatchGatewayCronFinishedNotifications", () => {
261261
expect(cleanupOrder).toEqual(["cancel", "release"]);
262262
});
263263

264+
it("adds the run start time to immediate chat alerts in the agent timezone", async () => {
265+
const job = createWebhookJob({
266+
mode: "announce",
267+
channel: "telegram",
268+
to: "channel:ops",
269+
});
270+
271+
await sendGatewayCronFailureAlert({
272+
deps: {} as CliDeps,
273+
logger: { warn: vi.fn() },
274+
resolveCronAgent: () => ({
275+
agentId: "main",
276+
cfg: { agents: { defaults: { userTimezone: "America/New_York" } } },
277+
}),
278+
job,
279+
text: "cron failed",
280+
runAtMs: Date.parse("2026-01-15T15:30:00.000Z"),
281+
channel: "telegram",
282+
to: "channel:ops",
283+
mode: "announce",
284+
});
285+
286+
expect(mocks.sendCronAnnouncePayloadStrict).toHaveBeenCalledWith(
287+
expect.objectContaining({
288+
message: "cron failed\nRun started: 2026-01-15 10:30 EST",
289+
}),
290+
);
291+
});
292+
293+
it("keeps immediate failure webhook messages stable and adds structured runAtMs", async () => {
294+
const runAtMs = Date.parse("2026-01-15T15:30:00.000Z");
295+
const job = createWebhookJob({
296+
mode: "webhook",
297+
to: "https://example.invalid/cron",
298+
});
299+
300+
await sendGatewayCronFailureAlert({
301+
deps: {} as CliDeps,
302+
logger: { warn: vi.fn() },
303+
resolveCronAgent: () => ({
304+
agentId: "main",
305+
cfg: { agents: { defaults: { userTimezone: "America/New_York" } } },
306+
}),
307+
job,
308+
text: "cron failed",
309+
runAtMs,
310+
channel: "last",
311+
mode: "webhook",
312+
to: "https://example.invalid/cron",
313+
});
314+
315+
expect(webhookRequestBody()).toEqual({
316+
jobId: job.id,
317+
jobName: job.name,
318+
message: "cron failed",
319+
runAtMs,
320+
});
321+
});
322+
264323
it("delivers a failed cron webhook even when the run produced no summary", async () => {
265324
const logger = { warn: vi.fn() };
266325
const job = createWebhookJob({
@@ -519,6 +578,75 @@ describe("dispatchGatewayCronFinishedNotifications", () => {
519578
await waitForFast(() => expect(getActiveGatewayRootWorkCount()).toBe(0));
520579
});
521580

581+
it("adds the run start time to failure destination chat without changing webhook text", async () => {
582+
const runAtMs = Date.parse("2026-01-15T15:30:00.000Z");
583+
const announceJob = createWebhookJob({
584+
mode: "announce",
585+
failureDestination: {
586+
mode: "announce",
587+
channel: "telegram",
588+
to: "-1001234567890",
589+
},
590+
});
591+
592+
dispatchGatewayCronFinishedNotifications({
593+
evt: {
594+
jobId: announceJob.id,
595+
action: "finished",
596+
status: "error",
597+
error: "provider unavailable",
598+
runAtMs,
599+
},
600+
job: announceJob,
601+
deps: {} as CliDeps,
602+
logger: { warn: vi.fn() },
603+
resolveCronAgent: () => ({
604+
agentId: "main",
605+
cfg: { agents: { defaults: { userTimezone: "America/New_York" } } },
606+
}),
607+
});
608+
609+
expect(mocks.sendFailureNotificationAnnounce).toHaveBeenCalledWith(
610+
expect.anything(),
611+
expect.anything(),
612+
"main",
613+
announceJob.id,
614+
expect.anything(),
615+
'⚠️ Cron job "notification admission" failed: provider unavailable\nRun started: 2026-01-15 10:30 EST',
616+
);
617+
618+
vi.clearAllMocks();
619+
const webhookJob = createWebhookJob({
620+
mode: "announce",
621+
failureDestination: {
622+
mode: "webhook",
623+
to: "https://example.invalid/failure",
624+
},
625+
});
626+
dispatchGatewayCronFinishedNotifications({
627+
evt: {
628+
jobId: webhookJob.id,
629+
action: "finished",
630+
status: "error",
631+
error: "provider unavailable",
632+
runAtMs,
633+
},
634+
job: webhookJob,
635+
deps: {} as CliDeps,
636+
logger: { warn: vi.fn() },
637+
resolveCronAgent: () => ({
638+
agentId: "main",
639+
cfg: { agents: { defaults: { userTimezone: "America/New_York" } } },
640+
}),
641+
});
642+
643+
await waitForFast(() => expect(mocks.fetchWithSsrFGuard).toHaveBeenCalledOnce());
644+
expect(webhookRequestBody()).toMatchObject({
645+
message: 'Cron job "notification admission" failed: provider unavailable',
646+
runAtMs,
647+
});
648+
});
649+
522650
it("redacts invalid completion webhook targets in warnings", () => {
523651
const logger = {
524652
warn: vi.fn(),

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

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
normalizeOptionalLowercaseString,
55
normalizeOptionalString,
66
} from "@openclaw/normalization-core/string-coerce";
7+
import { resolveUserTimezone } from "../agents/date-time.js";
78
import type { CliDeps } from "../cli/deps.types.js";
89
import type { CronFailureDestinationConfig } from "../config/types.cron.js";
910
import type { OpenClawConfig } from "../config/types.openclaw.js";
@@ -19,6 +20,7 @@ import { resolveCronDeliverySessionKey } from "../cron/session-target.js";
1920
import type { CronJob, CronMessageChannel } from "../cron/types.js";
2021
import { normalizeHttpWebhookUrl } from "../cron/webhook-url.js";
2122
import { formatErrorMessage } from "../infra/errors.js";
23+
import { formatZonedTimestamp } from "../infra/format-time/format-datetime.js";
2224
import { fetchWithSsrFGuard } from "../infra/net/fetch-guard.js";
2325
import { SsrFBlockedError } from "../infra/net/ssrf.js";
2426
import { runWithGatewayIndependentRootWorkAdmission } from "../process/gateway-work-admission.js";
@@ -47,6 +49,7 @@ type CronFailureAlertParams = {
4749
webhookToken?: unknown;
4850
job: CronJob;
4951
text: string;
52+
runAtMs?: number;
5053
channel: CronMessageChannel;
5154
to?: string;
5255
mode?: "announce" | "webhook";
@@ -176,6 +179,20 @@ function buildCronFailureWebhookPayload(params: { evt: CronEvent; job: CronJob }
176179
};
177180
}
178181

182+
function appendCronRunStarted(
183+
message: string,
184+
runAtMs: number | undefined,
185+
config: OpenClawConfig,
186+
): string {
187+
if (typeof runAtMs !== "number" || !Number.isFinite(runAtMs)) {
188+
return message;
189+
}
190+
const timestamp = formatZonedTimestamp(new Date(runAtMs), {
191+
timeZone: resolveUserTimezone(config.agents?.defaults?.userTimezone),
192+
});
193+
return timestamp ? `${message}\nRun started: ${timestamp}` : message;
194+
}
195+
179196
function buildCronFinishedWebhookPayload(evt: CronEvent) {
180197
if (evt.status !== "error") {
181198
return evt;
@@ -299,6 +316,7 @@ async function sendGatewayCronFailureAlertUnderAdmission(
299316
jobId: params.job.id,
300317
jobName: params.job.name,
301318
message: params.text,
319+
runAtMs: params.runAtMs,
302320
},
303321
logContext: { jobId: params.job.id },
304322
blockedLog: "cron: failure alert webhook blocked by SSRF guard",
@@ -337,7 +355,7 @@ async function sendGatewayCronFailureAlertUnderAdmission(
337355
accountId: params.accountId,
338356
sessionKey: resolveCronDeliverySessionKey(params.job),
339357
},
340-
message: params.text,
358+
message: appendCronRunStarted(params.text, params.runAtMs, runtimeConfig),
341359
abortSignal: abortController.signal,
342360
}),
343361
new Promise<never>((_resolve, reject) => {
@@ -509,7 +527,7 @@ function dispatchCronFailureDestinationNotifications(params: {
509527
// session only for context, not for reattaching the primary topic.
510528
inheritSessionThread: false,
511529
},
512-
`⚠️ ${failurePayload.message}`,
530+
appendCronRunStarted(`⚠️ ${failurePayload.message}`, params.evt.runAtMs, runtimeConfig),
513531
),
514532
});
515533
}
@@ -537,7 +555,7 @@ function dispatchCronFailureDestinationNotifications(params: {
537555
accountId: primaryPlan.accountId,
538556
sessionKey: deliverySessionKey,
539557
},
540-
`⚠️ ${failurePayload.message}`,
558+
appendCronRunStarted(`⚠️ ${failurePayload.message}`, params.evt.runAtMs, runtimeConfig),
541559
),
542560
});
543561
}

‎src/gateway/server-cron.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -987,14 +987,15 @@ export function buildGatewayCronService(params: {
987987
"cron: isolated agent setup timed out before runner start; backing off job without gateway restart",
988988
);
989989
},
990-
sendCronFailureAlert: async ({ job, text, channel, to, mode, accountId }) =>
990+
sendCronFailureAlert: async ({ job, text, runAtMs, channel, to, mode, accountId }) =>
991991
await sendGatewayCronFailureAlert({
992992
deps: params.deps,
993993
logger: cronLogger,
994994
resolveCronAgent,
995995
webhookToken: params.cfg.cron?.webhookToken,
996996
job,
997997
text,
998+
runAtMs,
998999
channel,
9991000
to,
10001001
mode,

0 commit comments

Comments
 (0)