Skip to content

Commit d0700b3

Browse files
fix(agents): heartbeat runs no longer block visible turns (#126853)
* fix(heartbeat): keep background runs off the main lane * docs(queue): describe heartbeat background lane * fix(agents): forward heartbeat lane to embedded fallback * test(agents): prove heartbeat and visible lane overlap * test(agents): expose heartbeat lane in embedded harnesses * refactor(agents): keep heartbeat lane choice at fallback boundary Signed-off-by: sallyom <[email protected]> --------- Signed-off-by: sallyom <[email protected]> Co-authored-by: sallyom <[email protected]>
1 parent 23854c3 commit d0700b3

5 files changed

Lines changed: 339 additions & 2 deletions

File tree

‎docs/concepts/queue.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,8 @@ not a local-mode command.
130130
## Scope and guarantees
131131

132132
- Applies to auto-reply agent runs across all inbound channels that use the gateway reply pipeline (WhatsApp web, Telegram, Slack, Discord, Signal, iMessage, webchat, etc.).
133-
- Default lane (`main`) is process-wide for inbound + main heartbeats; set `agents.defaults.maxConcurrent` to allow multiple sessions in parallel.
133+
- Default lane (`main`) is process-wide for inbound turns; set `agents.defaults.maxConcurrent` to allow multiple sessions in parallel.
134+
- Heartbeat embedded runs use the bounded `cron-nested` lane for global admission so slow background work does not block inbound replies, while their configured heartbeat session lane still serializes work for that session.
134135
- Additional lanes may exist (e.g. `cron`, `cron-nested`, `nested`, `subagent`) so background jobs can run in parallel without blocking inbound replies. Isolated cron agent turns hold a `cron` slot while their inner agent execution uses `cron-nested`. Shared non-cron `nested` flows keep their own lane behavior. These detached runs are tracked as [background tasks](/automation/tasks).
135136
- Per-session lanes guarantee that only one agent run touches a given session at a time.
136137
- No external dependencies or background worker threads; pure TypeScript + promises.

‎src/auto-reply/reply/agent-runner-embedded-candidate.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ export async function runEmbeddedFallbackCandidate(params: {
7070
sessionRuntimeOverride?: string;
7171
candidateThinkLevel?: ThinkLevel;
7272
candidateFastMode: Pick<RunEmbeddedAgentParams, "fastMode" | "fastModeAutoOnSeconds">;
73+
runLane: RunEmbeddedAgentParams["lane"];
7374
runId: string;
7475
getLifecycleGeneration: () => string;
7576
onLifecycleGeneration: (generation: string) => void;
@@ -232,6 +233,7 @@ export async function runEmbeddedFallbackCandidate(params: {
232233
...senderContext,
233234
...runBaseParams,
234235
contextWindow: turn.getActiveSessionEntry()?.contextWindow,
236+
lane: params.runLane,
235237
provider: embeddedRunProvider,
236238
agentHarnessId: embeddedRunHarnessOverride,
237239
agentHarnessRuntimeOverride: embeddedRunHarnessOverride,

‎src/auto-reply/reply/agent-runner-execution-runtime.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,7 @@ describe("executeAgentTurn: runtime selection", () => {
343343
provider: "anthropic",
344344
model: "claude-opus-4-6",
345345
trigger: "heartbeat",
346+
lane: "cron-nested",
346347
agentHarnessId: "codex",
347348
agentHarnessRuntimeOverride: "codex",
348349
});

‎src/auto-reply/reply/agent-runner-fallback-candidate.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ export async function runAgentFallbackCandidates(params: AgentFallbackCycleParam
5252
bindSourceReplyDeliveryRuntime(turn.followupRun.run, sourceReplyDeliveryRuntime);
5353
const sourceReplyDeliveryModeOrigin = sourceReplyDeliveryRuntime.origin;
5454
const preserveProgressCallbackStartOrder = turn.opts?.preserveProgressCallbackStartOrder === true;
55-
const runLane = CommandLane.Main;
55+
const runLane = turn.isHeartbeat ? CommandLane.CronNested : CommandLane.Main;
5656
let queuedUserMessagePersistedAcrossFallback = false;
5757
let assistantErrorPersistedAcrossFallback = false;
5858
const messageToolDeliveryState: MessageToolDeliveryState = {
@@ -277,6 +277,7 @@ export async function runAgentFallbackCandidates(params: AgentFallbackCycleParam
277277
}
278278
const candidate = await runEmbeddedFallbackCandidate({
279279
...common,
280+
runLane,
280281
githubPublicationAvailable: await (githubPublicationAvailability ??=
281282
turn.sessionKey && params.effectiveRun.agentId
282283
? prepareGitHubPublicationAvailability({
Lines changed: 332 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,332 @@
1+
import fs from "node:fs/promises";
2+
import { createServer, type ServerResponse } from "node:http";
3+
import path from "node:path";
4+
import { afterEach, describe, expect, it } from "vitest";
5+
import { withFastReplyConfig } from "../src/auto-reply/reply/get-reply-fast-path.test-support.js";
6+
import {
7+
clearConfigCache,
8+
clearRuntimeConfigSnapshot,
9+
getRuntimeConfigSnapshot,
10+
} from "../src/config/config.js";
11+
import { clearSessionStoreCacheForTest } from "../src/config/sessions/store-writer-state.js";
12+
import type { OpenClawConfig } from "../src/config/types.openclaw.js";
13+
import {
14+
disconnectGatewayClient,
15+
startGatewayWithClient,
16+
} from "../src/gateway/test-helpers.e2e.js";
17+
import { buildMockOpenAiResponsesProvider } from "../src/gateway/test-openai-responses-model.js";
18+
import { captureEnv, setTestEnvValue } from "../src/test-utils/env.js";
19+
import { useAutoCleanupTempDirTracker } from "./helpers/temp-dir.js";
20+
21+
const envKeys = [
22+
"HOME",
23+
"OPENCLAW_STATE_DIR",
24+
"OPENCLAW_CONFIG_PATH",
25+
"OPENCLAW_GATEWAY_TOKEN",
26+
"OPENCLAW_SKIP_CHANNELS",
27+
"OPENCLAW_SKIP_GMAIL_WATCHER",
28+
"OPENCLAW_SKIP_CRON",
29+
"OPENCLAW_SKIP_CANVAS_HOST",
30+
"OPENCLAW_SKIP_BROWSER_CONTROL_SERVER",
31+
"OPENCLAW_SKIP_PROVIDERS",
32+
"OPENCLAW_BUNDLED_PLUGINS_DIR",
33+
"OPENCLAW_DISABLE_BUNDLED_PLUGINS",
34+
] as const;
35+
36+
type LaneSnapshot = {
37+
lane: string;
38+
activeCount: number;
39+
queuedCount: number;
40+
};
41+
42+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
43+
44+
async function within<T>(promise: Promise<T>, label: string, timeoutMs = 20_000): Promise<T> {
45+
let timeout: NodeJS.Timeout | undefined;
46+
try {
47+
return await Promise.race([
48+
promise,
49+
new Promise<never>((_, reject) => {
50+
timeout = setTimeout(() => reject(new Error(`timed out while ${label}`)), timeoutMs);
51+
}),
52+
]);
53+
} finally {
54+
if (timeout) {
55+
clearTimeout(timeout);
56+
}
57+
}
58+
}
59+
60+
function writeAssistantResponse(response: ServerResponse, text: string): void {
61+
const message = {
62+
type: "message",
63+
id: `pr126853-${text.toLowerCase()}`,
64+
role: "assistant",
65+
status: "completed",
66+
content: [{ type: "output_text", text, annotations: [] }],
67+
};
68+
const events = [
69+
{
70+
type: "response.output_item.added",
71+
output_index: 0,
72+
item: { ...message, status: "in_progress", content: [] },
73+
},
74+
{ type: "response.output_item.done", output_index: 0, item: message },
75+
{
76+
type: "response.completed",
77+
response: {
78+
id: `response-${text.toLowerCase()}`,
79+
status: "completed",
80+
output: [message],
81+
usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15 },
82+
},
83+
},
84+
];
85+
response.writeHead(200, {
86+
"content-type": "text/event-stream",
87+
"cache-control": "no-store",
88+
});
89+
response.end(
90+
`${events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join("")}data: [DONE]\n\n`,
91+
);
92+
}
93+
94+
describe("PR #126853 real Gateway lane proof", () => {
95+
it(
96+
"starts a visible turn while an independent heartbeat is held",
97+
{ timeout: 90_000 },
98+
async () => {
99+
const envSnapshot = captureEnv([...envKeys]);
100+
let providerServer: ReturnType<typeof createServer> | undefined;
101+
let gateway: Awaited<ReturnType<typeof startGatewayWithClient>> | undefined;
102+
let releaseProviderResponses!: () => void;
103+
const providerResponsesReleased = new Promise<void>((resolve) => {
104+
releaseProviderResponses = resolve;
105+
});
106+
let heartbeatRequestStarted!: () => void;
107+
const heartbeatRequest = new Promise<void>((resolve) => {
108+
heartbeatRequestStarted = resolve;
109+
});
110+
let visibleRequestStarted!: () => void;
111+
const visibleRequest = new Promise<void>((resolve) => {
112+
visibleRequestStarted = resolve;
113+
});
114+
const heartbeatMarker = "PR126853_HEARTBEAT_HELD";
115+
const visibleMarker = "PR126853_VISIBLE_TURN";
116+
const providerOrder: string[] = [];
117+
let visibleTurnDispatched = false;
118+
119+
try {
120+
const tempHome = tempDirs.make("openclaw-pr126853-proof-");
121+
const stateDir = path.join(tempHome, ".openclaw");
122+
const workspaceDir = path.join(tempHome, "workspace");
123+
const configPath = path.join(stateDir, "openclaw.json");
124+
const bundledPluginsDir = path.join(tempHome, "bundled-plugins");
125+
await Promise.all([
126+
fs.mkdir(workspaceDir, { recursive: true }),
127+
fs.mkdir(bundledPluginsDir, { recursive: true }),
128+
fs.mkdir(path.dirname(configPath), { recursive: true }),
129+
]);
130+
await fs.writeFile(
131+
path.join(workspaceDir, "HEARTBEAT.md"),
132+
"Handle pending system events and reply with a concise acknowledgement.\n",
133+
);
134+
const token = "pr126853-proof-token";
135+
for (const [key, value] of Object.entries({
136+
HOME: tempHome,
137+
OPENCLAW_STATE_DIR: stateDir,
138+
OPENCLAW_CONFIG_PATH: configPath,
139+
OPENCLAW_GATEWAY_TOKEN: token,
140+
OPENCLAW_SKIP_CHANNELS: "1",
141+
OPENCLAW_SKIP_GMAIL_WATCHER: "1",
142+
OPENCLAW_SKIP_CRON: "0",
143+
OPENCLAW_SKIP_CANVAS_HOST: "1",
144+
OPENCLAW_SKIP_BROWSER_CONTROL_SERVER: "1",
145+
OPENCLAW_SKIP_PROVIDERS: "1",
146+
OPENCLAW_BUNDLED_PLUGINS_DIR: bundledPluginsDir,
147+
OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1",
148+
})) {
149+
setTestEnvValue(key, value);
150+
}
151+
152+
providerServer = createServer((request, response) => {
153+
void (async () => {
154+
const chunks: Buffer[] = [];
155+
for await (const chunk of request) {
156+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
157+
}
158+
if (request.method !== "POST" || request.url !== "/v1/responses") {
159+
response.writeHead(404).end();
160+
return;
161+
}
162+
const body = Buffer.concat(chunks).toString("utf8");
163+
const kind = !visibleTurnDispatched
164+
? "heartbeat"
165+
: body.includes(visibleMarker)
166+
? "visible"
167+
: "unexpected";
168+
providerOrder.push(kind);
169+
console.log(`PR126853_PROVIDER_REQUEST ${kind}`);
170+
if (kind === "heartbeat") {
171+
heartbeatRequestStarted();
172+
} else if (kind === "visible") {
173+
visibleRequestStarted();
174+
}
175+
await providerResponsesReleased;
176+
writeAssistantResponse(response, kind === "heartbeat" ? "HEARTBEAT_OK" : "VISIBLE_OK");
177+
})().catch((error: unknown) => {
178+
response.writeHead(500).end(error instanceof Error ? error.message : String(error));
179+
});
180+
});
181+
await new Promise<void>((resolve, reject) => {
182+
providerServer?.once("error", reject);
183+
providerServer?.listen(0, "127.0.0.1", resolve);
184+
});
185+
const providerAddress = providerServer.address();
186+
if (!providerAddress || typeof providerAddress === "string") {
187+
throw new Error("proof provider did not bind a loopback port");
188+
}
189+
const provider = buildMockOpenAiResponsesProvider(
190+
`http://127.0.0.1:${providerAddress.port}/v1`,
191+
"gpt-pr126853-proof",
192+
);
193+
const cfg = {
194+
agents: {
195+
defaults: {
196+
workspace: workspaceDir,
197+
skipBootstrap: true,
198+
maxConcurrent: 1,
199+
heartbeat: { every: "5m", target: "none" },
200+
model: { primary: provider.modelRef },
201+
models: {
202+
[provider.modelRef]: {
203+
params: { transport: "sse", openaiWsWarmup: false },
204+
},
205+
},
206+
},
207+
entries: { main: { default: true } },
208+
},
209+
models: {
210+
mode: "replace",
211+
providers: { [provider.providerId]: provider.config },
212+
},
213+
gateway: { auth: { mode: "token", token } },
214+
plugins: { slots: { memory: "none" } },
215+
} satisfies OpenClawConfig;
216+
gateway = await within(
217+
startGatewayWithClient({
218+
cfg,
219+
configPath,
220+
token,
221+
clientDisplayName: "pr126853-proof",
222+
}),
223+
"starting the proof Gateway",
224+
30_000,
225+
);
226+
const runtimeConfig = getRuntimeConfigSnapshot();
227+
if (!runtimeConfig) {
228+
throw new Error("proof Gateway did not publish its runtime config");
229+
}
230+
withFastReplyConfig(runtimeConfig);
231+
232+
const heartbeatSessionKey = "agent:main:pr126853-heartbeat";
233+
await gateway.client.request("sessions.create", {
234+
key: heartbeatSessionKey,
235+
agentId: "main",
236+
cwd: workspaceDir,
237+
});
238+
await expect(
239+
gateway.client.request<{ ok: boolean }>("wake", {
240+
mode: "now",
241+
text: heartbeatMarker,
242+
sessionKey: heartbeatSessionKey,
243+
agentId: "main",
244+
}),
245+
).resolves.toEqual({ ok: true });
246+
await within(heartbeatRequest, "waiting for the heartbeat provider request").catch(
247+
async (error: unknown) => {
248+
const lastHeartbeat = await gateway?.client
249+
.request("last-heartbeat", {})
250+
.catch((lookupError: unknown) => ({ lookupError: String(lookupError) }));
251+
throw new Error(
252+
`heartbeat did not reach provider; order=${JSON.stringify(providerOrder)} last=${JSON.stringify(lastHeartbeat)}`,
253+
{ cause: error },
254+
);
255+
},
256+
);
257+
258+
const visibleSessionKey = "agent:main:pr126853-visible";
259+
const visibleRunId = "pr126853-visible-run";
260+
visibleTurnDispatched = true;
261+
const started = await gateway.client.request<{ runId: string; status: string }>(
262+
"chat.send",
263+
{
264+
sessionKey: visibleSessionKey,
265+
message: visibleMarker,
266+
deliver: false,
267+
idempotencyKey: visibleRunId,
268+
},
269+
);
270+
expect(started).toMatchObject({ runId: visibleRunId, status: "started" });
271+
await within(visibleRequest, "waiting for the visible provider request");
272+
273+
const diagnostics = await gateway.client.request<{ lanes: LaneSnapshot[] }>(
274+
"diagnostics.lanes",
275+
{},
276+
);
277+
const main = diagnostics.lanes.find((lane) => lane.lane === "main");
278+
const heartbeat = diagnostics.lanes.find((lane) => lane.lane === "cron-nested");
279+
expect(providerOrder.slice(0, 2)).toEqual(["heartbeat", "visible"]);
280+
expect(main).toMatchObject({ lane: "main", activeCount: 1, queuedCount: 0 });
281+
expect(heartbeat).toMatchObject({
282+
lane: "cron-nested",
283+
activeCount: 1,
284+
queuedCount: 0,
285+
});
286+
console.log(
287+
`PR126853_RUNTIME_TRACE ${JSON.stringify({
288+
providerOrder: providerOrder.slice(0, 2),
289+
lanes: [main, heartbeat],
290+
heartbeatSessionKey,
291+
visibleSessionKey,
292+
})}`,
293+
);
294+
295+
releaseProviderResponses();
296+
await expect(
297+
gateway.client.request(
298+
"agent.wait",
299+
{ runId: started.runId, timeoutMs: 30_000 },
300+
{ timeoutMs: 35_000 },
301+
),
302+
).resolves.toMatchObject({ status: "ok" });
303+
await expect
304+
.poll(
305+
async () =>
306+
await gateway?.client.request<{ status: string; preview?: string }>(
307+
"last-heartbeat",
308+
{},
309+
),
310+
{ timeout: 15_000, interval: 50 },
311+
)
312+
.toMatchObject({ status: "ok-empty" });
313+
} finally {
314+
releaseProviderResponses();
315+
if (gateway) {
316+
await disconnectGatewayClient(gateway.client).catch(() => undefined);
317+
await gateway.server.close().catch(() => undefined);
318+
}
319+
if (providerServer?.listening) {
320+
providerServer.closeAllConnections();
321+
await new Promise<void>((resolve) => {
322+
providerServer?.close(() => resolve());
323+
});
324+
}
325+
envSnapshot.restore();
326+
clearRuntimeConfigSnapshot();
327+
clearConfigCache();
328+
clearSessionStoreCacheForTest();
329+
}
330+
},
331+
);
332+
});

0 commit comments

Comments
 (0)