Skip to content

Commit 98c0d9d

Browse files
clawsweeper[bot]Peter Steinberger
andauthored
fix(heartbeat): retain configured account for accountless commitments (#117521)
* fix(heartbeat): retain configured account for accountless commitments * fix(heartbeat): retain configured account for accountless commitments * fix(heartbeat): retain configured account for accountless commitments --------- Co-authored-by: clawsweeper <274271284+clawsweeper[bot]@users.noreply.github.com> Co-authored-by: Peter Steinberger <[email protected]>
1 parent b300a0c commit 98c0d9d

3 files changed

Lines changed: 292 additions & 6 deletions

File tree

‎src/infra/heartbeat-runner-execution.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ import { CommandLane } from "../process/lanes.js";
5252
import { normalizeAgentId, parseAgentSessionKey } from "../routing/session-key.js";
5353
import type { RuntimeEnv } from "../runtime.js";
5454
import { createLazyRuntimeModule } from "../shared/lazy-runtime.js";
55+
import { deliveryContextFromSession } from "../utils/delivery-context.shared.js";
5556
import { getAgentEventLifecycleGeneration } from "./agent-events.js";
5657
import { formatErrorMessage } from "./errors.js";
5758
import { isWithinActiveHours } from "./heartbeat-active-hours.js";
@@ -92,6 +93,7 @@ import {
9293
type HeartbeatWakeIntent,
9394
type HeartbeatWakeSource,
9495
} from "./heartbeat-wake.js";
96+
import { normalizeDeliverableOutboundChannel } from "./outbound/channel-resolution.js";
9597
import type { OutboundSendDeps } from "./outbound/deliver.js";
9698
import {
9799
resolveHeartbeatDeliveryTargetWithSessionRoute,
@@ -390,16 +392,32 @@ export async function prepareHeartbeatRunStage(wake: ReadyHeartbeatWake) {
390392
canHeartbeatDeliverCommitments(heartbeat) && scheduledTasks.length === 0
391393
? preflight.dueCommitments[0]
392394
: undefined;
395+
const heartbeatDeliveryChannel =
396+
heartbeat?.target === "last"
397+
? deliveryContextFromSession(entry)?.channel
398+
: normalizeDeliverableOutboundChannel(heartbeat?.target);
399+
// A configured heartbeat account belongs only to its normal route. Do not
400+
// carry it into an accountless commitment that owns a different channel.
401+
const commitmentAccountId =
402+
firstDueCommitment?.accountId ??
403+
(firstDueCommitment && heartbeatDeliveryChannel === firstDueCommitment.channel
404+
? heartbeat?.accountId
405+
: undefined);
393406
const commitmentDeliveryContext = firstDueCommitment
394407
? {
395408
channel: firstDueCommitment.channel,
396409
to: firstDueCommitment.to,
397-
accountId: firstDueCommitment.accountId,
410+
accountId: commitmentAccountId,
398411
threadId: firstDueCommitment.threadId,
399412
}
400413
: undefined;
401414
const heartbeatForDelivery = commitmentDeliveryContext
402-
? { ...heartbeat, target: "last", to: undefined, accountId: undefined }
415+
? {
416+
...heartbeat,
417+
target: "last",
418+
to: undefined,
419+
accountId: commitmentDeliveryContext.accountId,
420+
}
403421
: heartbeat;
404422
const delivery = await resolveHeartbeatDeliveryTargetWithSessionRoute({
405423
cfg,

‎src/infra/heartbeat-runner.commitments.test.ts‎

Lines changed: 48 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -77,14 +77,15 @@ describe("runHeartbeatOnce commitments", () => {
7777
id: string;
7878
sessionKey: string;
7979
to: string;
80+
accountId?: string | null;
8081
dueWindow?: CommitmentRecord["dueWindow"];
8182
}): CommitmentRecord {
8283
return {
8384
id: params.id,
8485
agentId: "main",
8586
sessionKey: params.sessionKey,
8687
channel: "telegram",
87-
accountId: "primary",
88+
...(params.accountId === null ? {} : { accountId: params.accountId ?? "primary" }),
8889
to: params.to,
8990
kind: "event_check_in",
9091
sensitivity: "routine",
@@ -120,6 +121,8 @@ describe("runHeartbeatOnce commitments", () => {
120121
async function setupCommitmentCase(params?: {
121122
replyText?: string;
122123
target?: "last" | "none";
124+
heartbeatAccountId?: string;
125+
commitmentAccountId?: string | null;
123126
dueWindow?: CommitmentRecord["dueWindow"];
124127
visibleReplies?: "automatic" | "message_tool";
125128
isolatedSession?: boolean;
@@ -135,12 +138,25 @@ describe("runHeartbeatOnce commitments", () => {
135138
heartbeat: {
136139
every: "5m",
137140
target: params?.target ?? "last",
141+
...(params?.heartbeatAccountId ? { accountId: params.heartbeatAccountId } : {}),
138142
...(params?.isolatedSession ? { isolatedSession: true } : {}),
139143
},
140144
},
141145
},
142146
...(params?.visibleReplies ? { messages: { visibleReplies: params.visibleReplies } } : {}),
143-
channels: { telegram: { allowFrom: ["*"] } },
147+
channels: {
148+
telegram: {
149+
allowFrom: ["*"],
150+
...(params?.heartbeatAccountId
151+
? {
152+
accounts: {
153+
primary: { botToken: "primary-token" },
154+
[params.heartbeatAccountId]: { botToken: "heartbeat-token" },
155+
},
156+
}
157+
: {}),
158+
},
159+
},
144160
session: { store: storePath },
145161
};
146162
await seedSessionStore(storePath, sessionKey, {
@@ -155,6 +171,7 @@ describe("runHeartbeatOnce commitments", () => {
155171
id: "cm_interview",
156172
sessionKey,
157173
to: "155462274",
174+
accountId: params?.commitmentAccountId,
158175
dueWindow: params?.dueWindow,
159176
}),
160177
],
@@ -640,10 +657,37 @@ describe("runHeartbeatOnce commitments", () => {
640657
});
641658

642659
it("delivers due commitments to the original scope when heartbeat target is last", async () => {
643-
const { result, sendTelegram, store } = await setupCommitmentCase();
660+
const { result, sendTelegram, store } = await setupCommitmentCase({
661+
heartbeatAccountId: "configured",
662+
commitmentAccountId: "primary",
663+
});
644664

645665
expect(result.status).toBe("ran");
646-
expect(sendTelegram).toHaveBeenCalled();
666+
expect(sendTelegram).toHaveBeenCalledWith(
667+
"155462274",
668+
"How did the interview go?",
669+
expect.objectContaining({ accountId: "primary" }),
670+
);
671+
expectCommitmentFields(store.commitments[0], {
672+
id: "cm_interview",
673+
status: "sent",
674+
attempts: 1,
675+
sentAtMs: nowMs,
676+
});
677+
});
678+
679+
it("uses the configured heartbeat account when a due commitment has no account", async () => {
680+
const { result, sendTelegram, store } = await setupCommitmentCase({
681+
heartbeatAccountId: "configured",
682+
commitmentAccountId: null,
683+
});
684+
685+
expect(result.status).toBe("ran");
686+
expect(sendTelegram).toHaveBeenCalledWith(
687+
"155462274",
688+
"How did the interview go?",
689+
expect.objectContaining({ accountId: "configured" }),
690+
);
647691
expectCommitmentFields(store.commitments[0], {
648692
id: "cm_interview",
649693
status: "sent",
Lines changed: 224 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
1+
import { afterEach, describe, expect, it, vi } from "vitest";
2+
import { HEARTBEAT_TOKEN } from "../auto-reply/tokens.js";
3+
import { readCommitmentsForTest, seedCommitmentsForTest } from "../commitments/store.test-utils.js";
4+
import type { CommitmentRecord } from "../commitments/types.js";
5+
import type { OpenClawConfig } from "../config/config.js";
6+
import { setActivePluginRegistry } from "../plugins/runtime.js";
7+
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
8+
import { createOutboundTestPlugin, createTestRegistry } from "../test-utils/channel-plugins.js";
9+
import { captureEnv, setTestEnvValue } from "../test-utils/env.js";
10+
import { runHeartbeatOnce, setHeartbeatsEnabled } from "./heartbeat-runner.js";
11+
import { installHeartbeatRunnerTestRuntime } from "./heartbeat-runner.test-harness.js";
12+
import { seedSessionStore, withTempHeartbeatSandbox } from "./heartbeat-runner.test-utils.js";
13+
14+
vi.mock("../commitments/config.js", async (importOriginal) => ({
15+
...(await importOriginal<typeof import("../commitments/config.js")>()),
16+
resolveCommitmentsConfig: () => ({
17+
enabled: true,
18+
maxPerDay: 3,
19+
extraction: {
20+
debounceMs: 15_000,
21+
batchMaxItems: 8,
22+
queueMaxItems: 64,
23+
confidenceThreshold: 0.72,
24+
careConfidenceThreshold: 0.86,
25+
timeoutSeconds: 45,
26+
},
27+
}),
28+
}));
29+
30+
installHeartbeatRunnerTestRuntime({ includeSlack: true });
31+
32+
describe("runHeartbeatOnce cross-channel commitments", () => {
33+
const nowMs = Date.parse("2026-04-29T17:00:00.000Z");
34+
const envSnapshot = captureEnv(["OPENCLAW_STATE_DIR"]);
35+
36+
afterEach(() => {
37+
closeOpenClawStateDatabaseForTest();
38+
setHeartbeatsEnabled(true);
39+
vi.unstubAllEnvs();
40+
envSnapshot.restore();
41+
});
42+
43+
it.each(["gchat", "google-chat", " GCHAT "])(
44+
"retains the configured account for a same-channel heartbeat alias (%s)",
45+
async (heartbeatTarget) => {
46+
await withTempHeartbeatSandbox(async ({ tmpDir, storePath, replySpy }) => {
47+
setTestEnvValue("OPENCLAW_STATE_DIR", tmpDir);
48+
const sessionKey = "agent:main:googlechat:spaces-room";
49+
const sendGoogleChat = vi.fn();
50+
const plugin = createOutboundTestPlugin({
51+
id: "googlechat",
52+
outbound: {
53+
deliveryMode: "direct",
54+
sendText: async ({ to, text, accountId }) => {
55+
sendGoogleChat(to, text, { accountId });
56+
return { channel: "googlechat", messageId: "m1" };
57+
},
58+
},
59+
});
60+
setActivePluginRegistry(
61+
createTestRegistry([{ pluginId: "googlechat", plugin, source: "test" }]),
62+
);
63+
const cfg: OpenClawConfig = {
64+
agents: {
65+
defaults: {
66+
workspace: tmpDir,
67+
heartbeat: {
68+
every: "5m",
69+
target: heartbeatTarget,
70+
accountId: "configured",
71+
},
72+
},
73+
},
74+
channels: {
75+
googlechat: {
76+
accounts: { default: {}, configured: {} },
77+
},
78+
},
79+
session: { store: storePath },
80+
};
81+
await seedSessionStore(storePath, sessionKey, {
82+
lastChannel: "googlechat",
83+
lastProvider: "googlechat",
84+
lastTo: "spaces/room",
85+
});
86+
const commitment: CommitmentRecord = {
87+
id: "cm_same_channel_alias",
88+
agentId: "main",
89+
sessionKey,
90+
channel: "googlechat",
91+
to: "spaces/room",
92+
kind: "event_check_in",
93+
sensitivity: "routine",
94+
source: "inferred_user_context",
95+
status: "pending",
96+
reason: "The user asked for a follow-up.",
97+
suggestedText: "How did the interview go?",
98+
dedupeKey: "same-channel-alias-account",
99+
confidence: 0.92,
100+
dueWindow: { earliestMs: nowMs - 60_000, latestMs: nowMs + 60_000, timezone: "UTC" },
101+
createdAtMs: nowMs - 120_000,
102+
updatedAtMs: nowMs - 120_000,
103+
attempts: 0,
104+
};
105+
seedCommitmentsForTest([commitment]);
106+
replySpy.mockImplementation(async (ctx) => {
107+
expect(ctx.Body).toContain(HEARTBEAT_TOKEN);
108+
expect(ctx.OriginatingChannel).toBe("googlechat");
109+
expect(ctx.OriginatingTo).toBe("spaces/room");
110+
return { text: "How did the interview go?" };
111+
});
112+
113+
const result = await runHeartbeatOnce({
114+
cfg,
115+
agentId: "main",
116+
sessionKey,
117+
deps: {
118+
getReplyFromConfig: replySpy,
119+
getQueueSize: () => 0,
120+
nowMs: () => nowMs,
121+
},
122+
});
123+
124+
expect(result.status).toBe("ran");
125+
expect(sendGoogleChat).toHaveBeenCalledWith("spaces/room", "How did the interview go?", {
126+
accountId: "configured",
127+
});
128+
expect(readCommitmentsForTest()[0]).toMatchObject({
129+
id: commitment.id,
130+
status: "sent",
131+
attempts: 1,
132+
sentAtMs: nowMs,
133+
});
134+
});
135+
},
136+
);
137+
138+
it("does not apply a configured heartbeat account to an accountless commitment on another channel", async () => {
139+
await withTempHeartbeatSandbox(async ({ tmpDir, storePath, replySpy }) => {
140+
setTestEnvValue("OPENCLAW_STATE_DIR", tmpDir);
141+
const sessionKey = "agent:main:telegram:user-155462274";
142+
const cfg: OpenClawConfig = {
143+
agents: {
144+
defaults: {
145+
workspace: tmpDir,
146+
heartbeat: { every: "5m", target: "last", accountId: "configured" },
147+
},
148+
},
149+
channels: {
150+
slack: { allowFrom: ["*"] },
151+
telegram: {
152+
allowFrom: ["*"],
153+
accounts: {
154+
configured: { botToken: "heartbeat-token" },
155+
primary: { botToken: "primary-token" },
156+
},
157+
},
158+
},
159+
session: { store: storePath },
160+
};
161+
await seedSessionStore(storePath, sessionKey, {
162+
lastChannel: "telegram",
163+
lastProvider: "telegram",
164+
lastTo: "155462274",
165+
});
166+
const commitment: CommitmentRecord = {
167+
id: "cm_cross_channel",
168+
agentId: "main",
169+
sessionKey,
170+
channel: "slack",
171+
to: "C123",
172+
kind: "event_check_in",
173+
sensitivity: "routine",
174+
source: "inferred_user_context",
175+
status: "pending",
176+
reason: "The user asked for a follow-up.",
177+
suggestedText: "How did the interview go?",
178+
dedupeKey: "cross-channel-account",
179+
confidence: 0.92,
180+
dueWindow: { earliestMs: nowMs - 60_000, latestMs: nowMs + 60_000, timezone: "UTC" },
181+
createdAtMs: nowMs - 120_000,
182+
updatedAtMs: nowMs - 120_000,
183+
attempts: 0,
184+
};
185+
seedCommitmentsForTest([commitment]);
186+
187+
const sendSlack = vi.fn().mockResolvedValue({ messageId: "m1", channelId: "C123" });
188+
const sendTelegram = vi.fn();
189+
replySpy.mockImplementation(async (ctx) => {
190+
expect(ctx.Body).toContain(HEARTBEAT_TOKEN);
191+
expect(ctx.OriginatingChannel).toBe("slack");
192+
expect(ctx.OriginatingTo).toBe("C123");
193+
return { text: "How did the interview go?" };
194+
});
195+
196+
const result = await runHeartbeatOnce({
197+
cfg,
198+
agentId: "main",
199+
sessionKey,
200+
deps: {
201+
getReplyFromConfig: replySpy,
202+
slack: sendSlack,
203+
telegram: sendTelegram,
204+
getQueueSize: () => 0,
205+
nowMs: () => nowMs,
206+
},
207+
});
208+
209+
expect(result.status).toBe("ran");
210+
expect(sendTelegram).not.toHaveBeenCalled();
211+
expect(sendSlack).toHaveBeenCalledWith(
212+
"C123",
213+
"How did the interview go?",
214+
expect.objectContaining({ accountId: undefined }),
215+
);
216+
expect(readCommitmentsForTest()[0]).toMatchObject({
217+
id: commitment.id,
218+
status: "sent",
219+
attempts: 1,
220+
sentAtMs: nowMs,
221+
});
222+
});
223+
});
224+
});

0 commit comments

Comments
 (0)