Skip to content

Commit fb9a62e

Browse files
authored
fix(heartbeat): suppress silent exec acknowledgements (#73785)
Punchcard-Session: golden-meadow-orchard-ng
1 parent bdc595d commit fb9a62e

4 files changed

Lines changed: 118 additions & 33 deletions

‎src/infra/heartbeat-delivery-normalization.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
type HeartbeatToolResponse,
66
} from "../auto-reply/heartbeat-tool-response.js";
77
import { stripHeartbeatToken } from "../auto-reply/heartbeat.js";
8+
import { isSilentReplyPayloadText } from "../auto-reply/tokens.js";
89
import type { ReplyPayload } from "../auto-reply/types.js";
910
import { escapeRegExp } from "../utils.js";
1011

@@ -44,7 +45,7 @@ function isStreamErrorFallbackPlaceholderOnly(text: string): boolean {
4445

4546
const TRAILING_HEARTBEAT_NOTIFY_FALSE_RE = /(?:^|[\r\n])[ \t]*notify=false[ \t]*(?:\r?\n[ \t]*)*$/i;
4647

47-
export function stripTrailingHeartbeatNotifyFalse(text: string): {
48+
function stripTrailingHeartbeatNotifyFalse(text: string): {
4849
text: string;
4950
silent: boolean;
5051
} {
@@ -58,15 +59,18 @@ export function normalizeHeartbeatReply(
5859
payload: ReplyPayload,
5960
responsePrefix: string | undefined,
6061
ackMaxChars: number,
62+
mode: "heartbeat" | "message" = "heartbeat",
6163
): NormalizedHeartbeatDelivery {
6264
const rawText = typeof payload.text === "string" ? payload.text : "";
6365
const textForStrip = stripLeadingHeartbeatResponsePrefix(rawText, responsePrefix);
64-
const stripped = stripHeartbeatToken(textForStrip, {
65-
mode: "heartbeat",
66+
const isSilentReply = isSilentReplyPayloadText(textForStrip);
67+
const stripped = stripHeartbeatToken(isSilentReply ? "" : textForStrip, {
68+
mode,
6669
maxAckChars: ackMaxChars,
6770
});
6871
const hasMedia = resolveSendableOutboundReplyParts(payload).hasMedia;
6972
const notifyFalse = stripTrailingHeartbeatNotifyFalse(stripped.text);
73+
notifyFalse.silent ||= isSilentReply;
7074
const isInternalPlaceholderOnly = isStreamErrorFallbackPlaceholderOnly(notifyFalse.text);
7175
if ((stripped.shouldSkip || isInternalPlaceholderOnly) && !hasMedia) {
7276
return {

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

Lines changed: 4 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import { formatErrorMessage } from "./errors.js";
1212
import {
1313
normalizeHeartbeatReply,
1414
normalizeHeartbeatToolNotification,
15-
stripTrailingHeartbeatNotifyFalse,
1615
} from "./heartbeat-delivery-normalization.js";
1716
import { emitHeartbeatEvent, resolveIndicatorType } from "./heartbeat-events.js";
1817
import { handleHeartbeatFailureNotice } from "./heartbeat-failure-notice.js";
@@ -94,6 +93,7 @@ export function classifyHeartbeatAgentOutcome(params: {
9493
) {
9594
return { kind: "ack", eventStatus: "ok-empty" } as const;
9695
}
96+
const mode = params.hasRelayableExecCompletion ? "message" : "heartbeat";
9797
const normalized = shouldSuppressSourceReply
9898
? {
9999
shouldSkip: true,
@@ -102,37 +102,17 @@ export function classifyHeartbeatAgentOutcome(params: {
102102
isInternalPlaceholderOnly: false,
103103
}
104104
: hasExplicitFailure && replyPayload
105-
? normalizeHeartbeatReply(replyPayload, params.responsePrefix, params.ackMaxChars)
105+
? normalizeHeartbeatReply(replyPayload, params.responsePrefix, params.ackMaxChars, mode)
106106
: heartbeatToolResponse
107107
? normalizeHeartbeatToolNotification(heartbeatToolResponse, params.responsePrefix)
108108
: replyPayload
109-
? normalizeHeartbeatReply(replyPayload, params.responsePrefix, params.ackMaxChars)
109+
? normalizeHeartbeatReply(replyPayload, params.responsePrefix, params.ackMaxChars, mode)
110110
: {
111111
shouldSkip: true,
112112
text: "",
113113
hasMedia: false,
114114
isInternalPlaceholderOnly: false,
115115
};
116-
// For exec completion events, don't skip even if the response looks like HEARTBEAT_OK.
117-
// The model should be responding with exec results, not ack tokens.
118-
// Also, if normalized.text is empty due to token stripping but we have exec completion,
119-
// fall back to the original reply text.
120-
const execFallbackText =
121-
!heartbeatToolResponse &&
122-
params.hasRelayableExecCompletion &&
123-
!normalized.text.trim() &&
124-
!normalized.isInternalPlaceholderOnly &&
125-
replyPayload?.text?.trim()
126-
? replyPayload.text.trim()
127-
: null;
128-
if (execFallbackText) {
129-
const execNotifyFalse = stripTrailingHeartbeatNotifyFalse(execFallbackText);
130-
normalized.text = execNotifyFalse.text;
131-
normalized.shouldSkip = !normalized.hasMedia && !normalized.text.trim();
132-
if (execNotifyFalse.silent) {
133-
normalized.silent = true;
134-
}
135-
}
136116
if (agentRunFailed) {
137117
const replacement = replaceGenericExternalRunFailureText(normalized.text);
138118
if (replacement.replaced) {
@@ -153,8 +133,7 @@ export function classifyHeartbeatAgentOutcome(params: {
153133
const shouldSkipMain =
154134
normalized.shouldSkip &&
155135
!normalized.hasMedia &&
156-
(!hasStructuredReplyContent || normalized.isInternalPlaceholderOnly) &&
157-
(!params.hasRelayableExecCompletion || normalized.isInternalPlaceholderOnly);
136+
(!hasStructuredReplyContent || normalized.isInternalPlaceholderOnly);
158137
if (hasExplicitFailure) {
159138
return {
160139
kind: "failure",

‎src/infra/heartbeat-runner.ack-token-heartbeat-acks.test.ts‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
withTempHeartbeatSandbox,
2020
withTempTelegramHeartbeatSandbox,
2121
} from "./heartbeat-runner.test-utils.js";
22+
import { enqueueSystemEvent, peekSystemEvents } from "./system-events.js";
2223

2324
installHeartbeatRunnerTestRuntime();
2425

@@ -219,6 +220,40 @@ describe("runHeartbeatOnce ack handling", () => {
219220
return cfg;
220221
}
221222

223+
async function runRelayableExecHeartbeat(params: {
224+
tmpDir: string;
225+
storePath: string;
226+
replySpy: HeartbeatReplySpy;
227+
reply: Record<string, unknown>;
228+
}) {
229+
const cfg = createWhatsAppHeartbeatConfig({
230+
tmpDir: params.tmpDir,
231+
storePath: params.storePath,
232+
});
233+
const sessionKey = await seedMainSessionStore(params.storePath, cfg, {
234+
lastChannel: "whatsapp",
235+
lastProvider: "whatsapp",
236+
lastTo: WHATSAPP_GROUP,
237+
});
238+
enqueueSystemEvent("Exec completed (heartbeat-test, code 0) :: uploaded report.txt", {
239+
sessionKey,
240+
contextKey: "exec:heartbeat-test",
241+
});
242+
params.replySpy.mockResolvedValue(params.reply as never);
243+
const sendWhatsApp = createMessageSendSpy();
244+
245+
const result = await runHeartbeatOnce({
246+
cfg,
247+
reason: "exec-event",
248+
deps: {
249+
...makeWhatsAppDeps({ sendWhatsApp }),
250+
getReplyFromConfig: params.replySpy,
251+
},
252+
});
253+
254+
return { cfg, result, sendWhatsApp, sessionKey };
255+
}
256+
222257
it("uses the fixed ack budget to suppress short heartbeat acknowledgements", async () => {
223258
await withTempHeartbeatSandbox(async ({ tmpDir, storePath, replySpy }) => {
224259
const cfg = createWhatsAppHeartbeatConfig({
@@ -513,6 +548,67 @@ describe("runHeartbeatOnce ack handling", () => {
513548
});
514549
});
515550

551+
it.each(["HEARTBEAT_OK", "NO_REPLY"])(
552+
"keeps relayable exec reply %s silent and consumes the event",
553+
async (replyText) => {
554+
await withTempHeartbeatSandbox(async ({ tmpDir, storePath, replySpy }) => {
555+
const { result, sendWhatsApp, sessionKey } = await runRelayableExecHeartbeat({
556+
tmpDir,
557+
storePath,
558+
replySpy,
559+
reply: { text: replyText },
560+
});
561+
562+
expect(result.status).toBe("ran");
563+
expect(sendWhatsApp).not.toHaveBeenCalled();
564+
expect(peekSystemEvents(sessionKey)).toEqual([]);
565+
});
566+
},
567+
);
568+
569+
it.each([
570+
["Command completed: uploaded report.txt", "Command completed: uploaded report.txt"],
571+
[
572+
"Command completed: uploaded report.txt\nHEARTBEAT_OK",
573+
"Command completed: uploaded report.txt",
574+
],
575+
])("delivers one relayable exec summary from %j", async (replyText, expectedText) => {
576+
await withTempHeartbeatSandbox(async ({ tmpDir, storePath, replySpy }) => {
577+
const { cfg, sendWhatsApp } = await runRelayableExecHeartbeat({
578+
tmpDir,
579+
storePath,
580+
replySpy,
581+
reply: { text: replyText },
582+
});
583+
584+
expectWhatsAppMessageSend(sendWhatsApp, {
585+
to: WHATSAPP_GROUP,
586+
text: expectedText,
587+
cfg,
588+
});
589+
});
590+
});
591+
592+
it("keeps relayable exec media and structured reply content deliverable", async () => {
593+
await withTempHeartbeatSandbox(async ({ tmpDir, storePath, replySpy }) => {
594+
const { result, sendWhatsApp } = await runRelayableExecHeartbeat({
595+
tmpDir,
596+
storePath,
597+
replySpy,
598+
reply: {
599+
text: "HEARTBEAT_OK",
600+
mediaUrl: "https://example.test/report.png",
601+
presentation: {
602+
blocks: [{ type: "text", text: "Report uploaded." }],
603+
},
604+
},
605+
});
606+
607+
expect(result.status).toBe("ran");
608+
expect(sendWhatsApp).toHaveBeenCalledOnce();
609+
});
610+
});
611+
516612
it("does not regress updatedAt when restoring heartbeat sessions", async () => {
517613
await withTempHeartbeatSandbox(async ({ tmpDir, storePath, replySpy }) => {
518614
const originalUpdatedAt = 1000;

‎src/infra/heartbeat-runner.tool-response.test.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ import {
2727
import { resolveCronJobsStorePath, saveCronJobsStore } from "../cron/store.js";
2828
import { closeOpenClawAgentDatabasesForTest } from "../state/openclaw-agent-db.js";
2929
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
30-
import { stripTrailingHeartbeatNotifyFalse } from "./heartbeat-delivery-normalization.js";
3130
import { getLastHeartbeatEvent, resetHeartbeatEventsForTest } from "./heartbeat-events.js";
3231
import { claimHeartbeatOutcomeForRun } from "./heartbeat-outcome-store.js";
3332
import { truncateHeartbeatPreview } from "./heartbeat-runner-prompt.js";
@@ -658,10 +657,17 @@ describe("runHeartbeatOnce heartbeat response tool", () => {
658657

659658
it.each(["\n", "\r\n"])(
660659
"strips trailing notify=false with suffix %j without rerunning a heartbeat",
661-
(suffix) => {
662-
expect(
663-
stripTrailingHeartbeatNotifyFalse(`No interruption needed.\n\nnotify=false${suffix}`),
664-
).toEqual({ text: "No interruption needed.", silent: true });
660+
async (suffix) => {
661+
const { result, sendTelegram, cfg } = await runPlainFallbackReply(
662+
`No interruption needed.\n\nnotify=false${suffix}`,
663+
);
664+
665+
expect(result.status).toBe("ran");
666+
expectTelegramSend(sendTelegram, {
667+
text: "No interruption needed.",
668+
cfg,
669+
silent: true,
670+
});
665671
},
666672
);
667673

0 commit comments

Comments
 (0)