Skip to content

Commit 2883684

Browse files
authored
fix(heartbeat): let a conversation's chained command completions skip the interval wait (#164756)
A background command completion started by the conversation (user turn or conversation continuation) now skips the heartbeat not-due wait, so a chained step reports within the existing 30 s spacing instead of waiting up to the heartbeat interval. The flood guard and 30 s spacing still apply; heartbeat-owned and other event wakes keep the full cooldown.
1 parent 313e200 commit 2883684

6 files changed

Lines changed: 117 additions & 5 deletions

File tree

‎docs/gateway/heartbeat.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -343,7 +343,7 @@ Heartbeat configuration is strict: only the fields listed above are accepted. Ac
343343
<Accordion title="Session and target routing">
344344
- Heartbeats run in the agent's main session by default (`agent:<id>:main`), or `global` when `session.scope = "global"`. Set `session` to override to a specific channel session (Discord/WhatsApp/etc.).
345345
- `session` only affects the run context. Delivery is controlled by `target` and `to`, except for session-owned events (see below).
346-
- A background command completion whose captured route is still its session's own conversation (for example the Telegram topic where the agent started the command) continues that conversation. It runs in that session with its full context, ignoring `isolatedSession` and `lightContext`, and the reply goes to that conversation, regardless of `target`, `to`, `directPolicy`, and channel `heartbeatVisibility`. A command started during that completion turn belongs to the same conversation. Its completion still follows the event cooldown: when it finishes more than 30 seconds after the previous heartbeat turn, it waits for the next heartbeat interval. The model still stays silent when the result is not worth reporting. OpenClaw's own notices from that turn, such as a run-failure notice, a tool-failure warning, a status line, or a truncation label, still follow the heartbeat's `target`, `isolatedSession`, and `showAlerts` settings, so `target: "none"` or `showAlerts: false` keeps them out of the chat while the model's answer is still delivered. These settings keep governing periodic polls and heartbeat-owned work. A completion without such a route, for example from an automation with `delivery: "none"`, still follows `target`/`to`. To turn off completion turns, set `tools.exec.notifyOnExit: false`.
346+
- A background command completion whose captured route is still its session's own conversation (for example the Telegram topic where the agent started the command) continues that conversation. It runs in that session with its full context, ignoring `isolatedSession` and `lightContext`, and the reply goes to that conversation, regardless of `target`, `to`, `directPolicy`, and channel `heartbeatVisibility`. A command started during that completion turn belongs to the same conversation. These completions do not wait for the next heartbeat interval, but event turns still start at least 30 seconds apart and at most 5 per minute. The model still stays silent when the result is not worth reporting. OpenClaw's own notices from that turn, such as a run-failure notice, a tool-failure warning, a status line, or a truncation label, still follow the heartbeat's `target`, `isolatedSession`, and `showAlerts` settings, so `target: "none"` or `showAlerts: false` keeps them out of the chat while the model's answer is still delivered. These settings keep governing periodic polls and heartbeat-owned work. A completion without such a route, for example from an automation with `delivery: "none"`, still follows `target`/`to`. To turn off completion turns, set `tools.exec.notifyOnExit: false`.
347347
- A wake whose pending events are all session-owned (background exec completions, or the continuation of a turn interrupted by a Gateway restart) in an internal session (Control UI/WebChat, or another operator-owned session without an external route) publishes the reply into that session's transcript instead of the `target`/`to` channel. `target: "none"` still suppresses it. If the session write fails, the event stays queued for a later wake and does not fall back to the channel. Batches that also contain other events use `target`/`to` as usual.
348348
- The default `owner` target chooses an explicitly configured owner identity. It reuses the exact account/thread only when the session's last route is a direct chat to that owner.
349349
- A wake that carries a channel and recipient uses that named origin before owner discovery. This event destination can be a group because it is explicit, not inferred.

‎src/infra/heartbeat-cooldown.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ type ShouldDeferInput = {
2323
recentRunStarts?: readonly number[];
2424
/** Work already retained by the wake queue after a prior guard deferral. */
2525
retainedWork?: boolean;
26+
/** Every pending event is a command completion owned by a conversation turn. */
27+
conversationTurn?: boolean;
2628
};
2729

2830
export function shouldDeferWake(input: ShouldDeferInput): DeferDecision {
@@ -50,7 +52,13 @@ export function shouldDeferWake(input: ShouldDeferInput): DeferDecision {
5052
return { defer: false };
5153
}
5254

53-
if (input.intent !== "task" && !input.retainedWork && input.now < input.nextDueMs) {
55+
// A conversation's own completion is its reply, not periodic work; spacing and flood still apply.
56+
if (
57+
input.intent !== "task" &&
58+
!input.retainedWork &&
59+
!input.conversationTurn &&
60+
input.now < input.nextDueMs
61+
) {
5462
const spacingRetryAtMs = resolveMinSpacingRetryAtMs(input);
5563
return {
5664
defer: true,

‎src/infra/heartbeat-events-filter.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,14 @@ export function isExecCompletionEvent(evt: string): boolean {
186186
);
187187
}
188188

189+
/** A command completion started by a conversation turn rather than heartbeat or automation work. */
190+
export function isConversationExecCompletion(event: {
191+
text: string;
192+
fromConversationTurn?: boolean;
193+
}): boolean {
194+
return event.fromConversationTurn === true && isExecCompletionEvent(event.text);
195+
}
196+
189197
export function isHeartbeatDeliveryAwarenessEvent(event: { contextKey?: string | null }): boolean {
190198
return event.contextKey?.startsWith(HEARTBEAT_DELIVERY_CONTEXT_KEY_PREFIX) ?? false;
191199
}

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
buildCronEventPrompt,
1919
buildExecEventPrompt,
2020
isCronSystemEvent,
21+
isConversationExecCompletion,
2122
isExecCompletionEvent,
2223
isHeartbeatDeliveryAwarenessEvent,
2324
isRelayableExecCompletionEvent,
@@ -84,8 +85,7 @@ function resolveConversationCompletionRoute(
8485
return route &&
8586
events.every(
8687
(event) =>
87-
event.fromConversationTurn === true &&
88-
isExecCompletionEvent(event.text) &&
88+
isConversationExecCompletion(event) &&
8989
channelRouteTargetsMatchExact({ left: event.deliveryContext, right: route }),
9090
) &&
9191
isStoredConversationRoute({ ...route, entry })

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

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ import {
1515
type HeartbeatConfig,
1616
} from "./heartbeat-config.js";
1717
import { recordRunStart, shouldDeferWake, type DeferDecision } from "./heartbeat-cooldown.js";
18+
import {
19+
isConversationExecCompletion,
20+
isHeartbeatDeliveryAwarenessEvent,
21+
} from "./heartbeat-events-filter.js";
1822
import { heartbeatLog as log } from "./heartbeat-log.js";
1923
import type { runHeartbeatOnce } from "./heartbeat-runner-run.js";
2024
import { isConfiguredHeartbeatAgent, isTargetedUnscheduledWake } from "./heartbeat-wake-policy.js";
@@ -29,6 +33,8 @@ import {
2933
setHeartbeatWakeHandler,
3034
} from "./heartbeat-wake.js";
3135
import { isSessionEventWakePollDeferred } from "./session-event-wake.js";
36+
import { resolveSystemEventQueueKey } from "./system-event-ownership.js";
37+
import { peekSystemEventEntries } from "./system-events.js";
3238

3339
const loadHeartbeatExecution = createLazyRuntimeModule(() => import("./heartbeat-runner-run.js"));
3440

@@ -95,7 +101,11 @@ export function startHeartbeatRunner(opts: {
95101
now: number,
96102
reason?: string,
97103
intent: HeartbeatWakeIntent = "event",
98-
options: { authoritativeScheduledTick?: boolean; retainedWork?: boolean } = {},
104+
options: {
105+
authoritativeScheduledTick?: boolean;
106+
retainedWork?: boolean;
107+
conversationTurn?: boolean;
108+
} = {},
99109
): DeferDecision => {
100110
const decision = shouldDeferWake({
101111
intent,
@@ -104,6 +114,7 @@ export function startHeartbeatRunner(opts: {
104114
lastRunStartedAtMs: agent.lastRunStartedAtMs,
105115
recentRunStarts: agent.recentRunStarts,
106116
retainedWork: options.retainedWork,
117+
conversationTurn: options.conversationTurn,
107118
});
108119
if (decision.defer && decision.reason === "flood") {
109120
if (!agent.floodLoggedSinceLastRun) {
@@ -213,9 +224,16 @@ export function startHeartbeatRunner(opts: {
213224
agent.intervalMs = scheduledEveryMs;
214225
agent.heartbeat = { ...agent.heartbeat, every: `${scheduledEveryMs}ms` };
215226
}
227+
const pendingEvents = execEventWake
228+
? peekSystemEventEntries(
229+
resolveSystemEventQueueKey(requestedSessionKey ?? "global", agentId),
230+
).filter((event) => !isHeartbeatDeliveryAwarenessEvent(event))
231+
: [];
216232
const deferral = evaluateWakeDeferral(agent, now, reason, intent, {
217233
authoritativeScheduledTick,
218234
retainedWork,
235+
conversationTurn:
236+
pendingEvents.length > 0 && pendingEvents.every(isConversationExecCompletion),
219237
});
220238
if (deferral.defer) {
221239
// Retained exec work never owns cadence unless a scheduled tick joined it.

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

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
setHeartbeatsEnabled,
2020
setHeartbeatWakeHandler,
2121
} from "./heartbeat-wake.js";
22+
import { enqueueSystemEvent, resetSystemEventsForTest } from "./system-events.js";
2223

2324
type RunnerOptions = Parameters<typeof startHeartbeatRunner>[0];
2425
type RunOnce = NonNullable<RunnerOptions["runOnce"]>;
@@ -94,6 +95,7 @@ afterEach(async () => {
9495
await vi.runAllTimersAsync();
9596
dispose();
9697
setHeartbeatsEnabled(true);
98+
resetSystemEventsForTest();
9799
resetConfigRuntimeState();
98100
vi.useRealTimers();
99101
vi.restoreAllMocks();
@@ -300,6 +302,82 @@ describe("startHeartbeatRunner", () => {
300302
expect(runSpy).toHaveBeenCalledTimes(3);
301303
});
302304

305+
it.each<{
306+
owner: string;
307+
fromConversationTurn: boolean;
308+
commandMs: number;
309+
runs: number;
310+
beside?: { text: string; contextKey?: string };
311+
}>([
312+
{ owner: "conversation", fromConversationTurn: true, commandMs: 0, runs: 20 },
313+
{ owner: "conversation", fromConversationTurn: true, commandMs: 40_000, runs: 14 },
314+
{ owner: "heartbeat", fromConversationTurn: false, commandMs: 40_000, runs: 1 },
315+
{
316+
owner: "conversation beside a reminder",
317+
fromConversationTurn: true,
318+
commandMs: 40_000,
319+
runs: 1,
320+
beside: { text: "Reminder: water the plants" },
321+
},
322+
{
323+
owner: "conversation after a heartbeat delivery",
324+
fromConversationTurn: true,
325+
commandMs: 40_000,
326+
runs: 14,
327+
beside: {
328+
text: "A heartbeat delivered this message to this channel:\nAll clear",
329+
contextKey: "heartbeat-delivery:0:agent:main:main:heartbeat",
330+
},
331+
},
332+
])(
333+
"spaces a $owner command taking $commandMs ms started in every completion turn",
334+
async ({ fromConversationTurn, commandMs, runs, beside }) => {
335+
if (beside) {
336+
enqueueSystemEvent(beside.text, { sessionKey, contextKey: beside.contextKey });
337+
}
338+
const startCommand = () =>
339+
setTimeout(() => {
340+
enqueueSystemEvent("Exec completed (abcd1234, code 0) :: done", {
341+
sessionKey,
342+
fromConversationTurn,
343+
});
344+
requestHeartbeat({ ...execWake, coalesceMs: 0 });
345+
}, commandMs);
346+
const callTimes: number[] = [];
347+
runSpy.mockImplementation(async () => {
348+
callTimes.push(Date.now());
349+
startCommand();
350+
return { status: "ran", durationMs: 0 };
351+
});
352+
start();
353+
startCommand();
354+
await vi.advanceTimersByTimeAsync(10 * 60_000);
355+
356+
// Event turns keep the 30s spacing; only conversation completions skip the interval wait.
357+
expect(callTimes).toHaveLength(runs);
358+
for (const [index, time] of callTimes.slice(1).entries()) {
359+
expect(time - callTimes[index]!).toBeGreaterThanOrEqual(Math.max(30_000, commandMs));
360+
}
361+
},
362+
);
363+
364+
it("holds a conversation's completion turn behind the flood guard", async () => {
365+
start();
366+
for (let i = 0; i < 5; i++) {
367+
await wake({ source: "manual", intent: "manual", reason: "manual", sessionKey });
368+
}
369+
await vi.advanceTimersByTimeAsync(40_000);
370+
enqueueSystemEvent("Exec completed (abcd1234, code 0) :: done", {
371+
sessionKey,
372+
fromConversationTurn: true,
373+
});
374+
await wake(execWake);
375+
await vi.advanceTimersByTimeAsync(19_900);
376+
expect(runSpy).toHaveBeenCalledTimes(5);
377+
await vi.advanceTimersByTimeAsync(200);
378+
expect(runSpy).toHaveBeenCalledTimes(6);
379+
});
380+
303381
it("retains an event that collides with a task until the spacing floor", async () => {
304382
start();
305383
requestHeartbeat({ ...taskWake, coalesceMs: 0 });

0 commit comments

Comments
 (0)