fix: refine cron heartbeat event detection

This commit is contained in:
Vignesh Natarajan
2026-02-12 15:50:27 -08:00
committed by Vignesh
parent c12f693c59
commit 22593a2723
4 changed files with 164 additions and 127 deletions

View File

@@ -5,12 +5,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../config/config.js";
import { telegramPlugin } from "../../extensions/telegram/src/channel.js";
import { setTelegramRuntime } from "../../extensions/telegram/src/runtime.js";
import * as replyModule from "../auto-reply/reply.js";
import { resolveMainSessionKey } from "../config/sessions.js";
import { setActivePluginRegistry } from "../plugins/runtime.js";
import { createPluginRuntime } from "../plugins/runtime/index.js";
import { createTestRegistry } from "../test-utils/channel-plugins.js";
import { enqueueSystemEvent, resetSystemEventsForTest } from "./system-events.js";
import { runHeartbeatOnce } from "./heartbeat-runner.js";
import { enqueueSystemEvent, resetSystemEventsForTest } from "./system-events.js";
// Avoid pulling optional runtime deps during isolated runs.
vi.mock("jiti", () => ({ createJiti: () => () => ({}) }));
@@ -21,63 +22,68 @@ beforeEach(() => {
setActivePluginRegistry(
createTestRegistry([{ pluginId: "telegram", plugin: telegramPlugin, source: "test" }]),
);
// Reset system events queue to avoid cross-test pollution
resetSystemEventsForTest();
});
afterEach(() => {
// Clean up after each test
resetSystemEventsForTest();
vi.restoreAllMocks();
});
describe("Ghost reminder bug (issue #13317)", () => {
it("should NOT trigger CRON_EVENT_PROMPT when only HEARTBEAT_OK is in system events", async () => {
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-ghost-"));
const createConfig = async (
tmpDir: string,
): Promise<{ cfg: OpenClawConfig; sessionKey: string }> => {
const storePath = path.join(tmpDir, "sessions.json");
try {
const cfg: OpenClawConfig = {
agents: {
defaults: {
workspace: tmpDir,
heartbeat: {
every: "5m",
target: "telegram",
},
const cfg: OpenClawConfig = {
agents: {
defaults: {
workspace: tmpDir,
heartbeat: {
every: "5m",
target: "telegram",
},
},
channels: { telegram: { allowFrom: ["*"] } },
session: { store: storePath },
};
const sessionKey = resolveMainSessionKey(cfg);
},
channels: { telegram: { allowFrom: ["*"] } },
session: { store: storePath },
};
const sessionKey = resolveMainSessionKey(cfg);
await fs.writeFile(
storePath,
JSON.stringify(
{
[sessionKey]: {
sessionId: "sid",
updatedAt: Date.now(),
lastChannel: "telegram",
lastProvider: "telegram",
lastTo: "155462274",
},
await fs.writeFile(
storePath,
JSON.stringify(
{
[sessionKey]: {
sessionId: "sid",
updatedAt: Date.now(),
lastChannel: "telegram",
lastProvider: "telegram",
lastTo: "155462274",
},
null,
2,
),
);
},
null,
2,
),
);
// Simulate leftover HEARTBEAT_OK from previous heartbeat
enqueueSystemEvent("HEARTBEAT_OK", { sessionKey });
return { cfg, sessionKey };
};
const sendTelegram = vi.fn().mockResolvedValue({
messageId: "m1",
chatId: "155462274",
});
it("does not use CRON_EVENT_PROMPT when only a HEARTBEAT_OK event is present", async () => {
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-ghost-"));
const sendTelegram = vi.fn().mockResolvedValue({
messageId: "m1",
chatId: "155462274",
});
const getReplySpy = vi
.spyOn(replyModule, "getReplyFromConfig")
.mockResolvedValue({ text: "Heartbeat check-in" });
try {
const { cfg } = await createConfig(tmpDir);
enqueueSystemEvent("HEARTBEAT_OK", { sessionKey: resolveMainSessionKey(cfg) });
// Run heartbeat with cron: reason (simulating cron job firing)
const result = await runHeartbeatOnce({
cfg,
agentId: "main",
@@ -87,73 +93,32 @@ describe("Ghost reminder bug (issue #13317)", () => {
},
});
// Check that heartbeat ran successfully
expect(result.status).toBeDefined();
// The bug: sendTelegram would be called with a message containing
// "scheduled reminder" even though no actual reminder content exists.
// The fix: should use regular heartbeat prompt, NOT CRON_EVENT_PROMPT.
// If a message was sent, verify it doesn't contain ghost reminder text
if (result.status === "sent") {
const calls = sendTelegram.mock.calls;
expect(calls.length).toBeGreaterThan(0);
const message = calls[0][0].message;
// Should NOT contain the ghost reminder prompt
expect(message).not.toContain("scheduled reminder has been triggered");
expect(message).not.toContain("relay this reminder");
}
expect(result.status).toBe("ran");
expect(getReplySpy).toHaveBeenCalledTimes(1);
const calledCtx = getReplySpy.mock.calls[0]?.[0];
expect(calledCtx?.Provider).toBe("heartbeat");
expect(calledCtx?.Body).not.toContain("scheduled reminder has been triggered");
expect(calledCtx?.Body).not.toContain("relay this reminder");
expect(sendTelegram).toHaveBeenCalled();
} finally {
await fs.rm(tmpDir, { recursive: true, force: true });
}
});
it("should trigger CRON_EVENT_PROMPT when actual cron message exists", async () => {
it("uses CRON_EVENT_PROMPT when an actionable cron event exists", async () => {
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-cron-"));
const storePath = path.join(tmpDir, "sessions.json");
const sendTelegram = vi.fn().mockResolvedValue({
messageId: "m1",
chatId: "155462274",
});
const getReplySpy = vi
.spyOn(replyModule, "getReplyFromConfig")
.mockResolvedValue({ text: "Relay this reminder now" });
try {
const cfg: OpenClawConfig = {
agents: {
defaults: {
workspace: tmpDir,
heartbeat: {
every: "5m",
target: "telegram",
},
},
},
channels: { telegram: { allowFrom: ["*"] } },
session: { store: storePath },
};
const sessionKey = resolveMainSessionKey(cfg);
await fs.writeFile(
storePath,
JSON.stringify(
{
[sessionKey]: {
sessionId: "sid",
updatedAt: Date.now(),
lastChannel: "telegram",
lastProvider: "telegram",
lastTo: "155462274",
},
},
null,
2,
),
);
// Simulate real cron message (not HEARTBEAT_OK)
enqueueSystemEvent("Reminder: Check Base Scout results", { sessionKey });
const sendTelegram = vi.fn().mockResolvedValue({
messageId: "m1",
chatId: "155462274",
const { cfg } = await createConfig(tmpDir);
enqueueSystemEvent("Reminder: Check Base Scout results", {
sessionKey: resolveMainSessionKey(cfg),
});
const result = await runHeartbeatOnce({
@@ -165,19 +130,47 @@ describe("Ghost reminder bug (issue #13317)", () => {
},
});
// Check that heartbeat ran
expect(result.status).toBeDefined();
// If a message was sent, verify it DOES contain the cron reminder prompt
if (result.status === "sent") {
const calls = sendTelegram.mock.calls;
expect(calls.length).toBeGreaterThan(0);
const message = calls[0][0].message;
// SHOULD contain the cron reminder prompt
expect(message).toContain("scheduled reminder has been triggered");
}
expect(result.status).toBe("ran");
expect(getReplySpy).toHaveBeenCalledTimes(1);
const calledCtx = getReplySpy.mock.calls[0]?.[0];
expect(calledCtx?.Provider).toBe("cron-event");
expect(calledCtx?.Body).toContain("scheduled reminder has been triggered");
expect(sendTelegram).toHaveBeenCalled();
} finally {
await fs.rm(tmpDir, { recursive: true, force: true });
}
});
it("uses CRON_EVENT_PROMPT when cron events are mixed with heartbeat noise", async () => {
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-cron-mixed-"));
const sendTelegram = vi.fn().mockResolvedValue({
messageId: "m1",
chatId: "155462274",
});
const getReplySpy = vi
.spyOn(replyModule, "getReplyFromConfig")
.mockResolvedValue({ text: "Relay this reminder now" });
try {
const { cfg, sessionKey } = await createConfig(tmpDir);
enqueueSystemEvent("HEARTBEAT_OK", { sessionKey });
enqueueSystemEvent("Reminder: Check Base Scout results", { sessionKey });
const result = await runHeartbeatOnce({
cfg,
agentId: "main",
reason: "cron:reminder-job",
deps: {
sendTelegram,
},
});
expect(result.status).toBe("ran");
expect(getReplySpy).toHaveBeenCalledTimes(1);
const calledCtx = getReplySpy.mock.calls[0]?.[0];
expect(calledCtx?.Provider).toBe("cron-event");
expect(calledCtx?.Body).toContain("scheduled reminder has been triggered");
expect(sendTelegram).toHaveBeenCalled();
} finally {
await fs.rm(tmpDir, { recursive: true, force: true });
}