Skip to content

Commit c6cb943

Browse files
NarahariRaghavavincentkoc
authored andcommitted
fix(cron): keep silent replies from clearing tool errors
Closes #116731 Punchcard-Session: brisk-valley-timber-85
1 parent 6cde399 commit c6cb943

4 files changed

Lines changed: 156 additions & 8 deletions

File tree

‎src/cron/isolated-agent.helpers.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,33 @@ describe("resolveCronPayloadOutcome", () => {
2929
expect(result.summary).toContain("Exec failed");
3030
});
3131

32+
it.each([
33+
["token", "NO_REPLY"],
34+
["JSON string", '"NO_REPLY"'],
35+
["envelope", '{"action":"NO_REPLY"}'],
36+
["reasoning-prefixed", "<think>internal reasoning</think>\nNO_REPLY"],
37+
])("keeps tool warnings fatal when terminal output is a silent %s", (_label, text) => {
38+
const result = resolveCronPayloadOutcome({
39+
payloads: [{ text: "⚠️ 🛠️ Bash failed: mount unavailable", isError: true }],
40+
finalAssistantVisibleText: text,
41+
preferFinalAssistantVisibleText: true,
42+
});
43+
44+
expect(result.hasFatalErrorPayload).toBe(true);
45+
expect(result.embeddedRunError).toContain("Bash failed");
46+
});
47+
48+
it("keeps genuine visible terminal output as recovery proof", () => {
49+
const result = resolveCronPayloadOutcome({
50+
payloads: [{ text: "⚠️ 🛠️ Bash failed: mount unavailable", isError: true }],
51+
finalAssistantVisibleText: "Mount restored; report written.",
52+
preferFinalAssistantVisibleText: true,
53+
});
54+
55+
expect(result.hasFatalErrorPayload).toBe(false);
56+
expect(result.outputText).toBe("Mount restored; report written.");
57+
});
58+
3259
it("lets preferred final assistant text recover a plain tool warning", () => {
3360
const result = resolveCronPayloadOutcome({
3461
payloads: [

‎src/cron/isolated-agent/helpers.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -293,9 +293,9 @@ export function resolveCronPayloadOutcome(params: {
293293
.find((payload) => payload?.isError === true && Boolean(payload?.text?.trim()))
294294
?.text?.trim();
295295
const errorPayloads = params.payloads.filter((payload) => payload?.isError === true);
296-
const normalizedFinalAssistantVisibleText = normalizeOptionalString(
297-
params.finalAssistantVisibleText,
298-
);
296+
const finalText = normalizeOptionalString(params.finalAssistantVisibleText);
297+
const normalizedFinalAssistantVisibleText =
298+
finalText && !isSilentReplyPayloadText(finalText) ? finalText : undefined;
299299
const hasSuccessfulPayloadAfterLastError =
300300
!params.runLevelError &&
301301
lastErrorPayloadIndex >= 0 &&
@@ -310,8 +310,8 @@ export function resolveCronPayloadOutcome(params: {
310310
normalizedFinalAssistantVisibleText !== undefined ||
311311
hasSuccessfulPayloadAfterLastError ||
312312
hasSuccessfulPayloadBeforeLastError;
313-
// Some tools emit warning/error payloads before a final answer. Treat those
314-
// as non-terminal only when later visible output proves the run recovered.
313+
// Only genuinely visible terminal text can recover preceding tool warnings;
314+
// silent control replies must leave the error fatal for scheduler alerting.
315315
const hasNonTerminalToolErrorWarning =
316316
!params.runLevelError &&
317317
params.failureSignal?.fatalForCron !== true &&
@@ -333,7 +333,7 @@ export function resolveCronPayloadOutcome(params: {
333333
!hasStructuredDeliveryPayloads &&
334334
errorPayloads.length > 0 &&
335335
errorPayloads.every((payload) => isCronToolWarning(payload?.text));
336-
// Structured error payloads are fatal unless later successful output or a
336+
// Structured error payloads stay fatal unless later successful output or a
337337
// known non-terminal warning proves the agent recovered.
338338
const hasFatalStructuredErrorPayload =
339339
hasErrorPayload &&

‎src/cron/isolated-agent/run.meta-error-status.test.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Run meta error tests cover status reporting when cron run metadata fails.
2-
import { describe, expect, it } from "vitest";
2+
import { describe, expect, it, vi } from "vitest";
33
import { makeIsolatedAgentJobFixture, makeIsolatedAgentParamsFixture } from "./job-fixtures.js";
44
import { setupRunCronIsolatedAgentTurnSuite } from "./run.suite-helpers.js";
55
import {
@@ -173,14 +173,16 @@ describe("runCronIsolatedAgentTurn - meta.error status propagation", () => {
173173
});
174174

175175
it("keeps explicit silent replies as successful cron completions", async () => {
176+
const { resolveCronPayloadOutcome } =
177+
await vi.importActual<typeof import("./helpers.js")>("./helpers.js");
178+
resolveCronPayloadOutcomeMock.mockImplementation(resolveCronPayloadOutcome);
176179
mockAgentRun({
177180
usage: { input: 10, output: 1 },
178181
meta: {
179182
finalAssistantRawText: "NO_REPLY",
180183
finalAssistantVisibleText: "NO_REPLY",
181184
},
182185
});
183-
mockAnnounceOutcome();
184186

185187
const result = await runCronIsolatedAgentTurn(makeIsolatedAgentParamsFixture());
186188

@@ -189,6 +191,21 @@ describe("runCronIsolatedAgentTurn - meta.error status propagation", () => {
189191
expect(result.error).toBeUndefined();
190192
});
191193

194+
it("records a real tool error when the terminal assistant reply is silent", async () => {
195+
const { resolveCronPayloadOutcome } =
196+
await vi.importActual<typeof import("./helpers.js")>("./helpers.js");
197+
resolveCronPayloadOutcomeMock.mockImplementation(resolveCronPayloadOutcome);
198+
mockAgentRun({
199+
payloads: [{ text: "⚠️ 🛠️ Bash failed: mount unavailable", isError: true }],
200+
meta: { finalAssistantVisibleText: "NO_REPLY" },
201+
});
202+
203+
const result = await runCronIsolatedAgentTurn(makeIsolatedAgentParamsFixture());
204+
205+
expect(result.status).toBe("error");
206+
expect(result.error).toContain("Bash failed");
207+
});
208+
192209
it("keeps committed message-tool deliveries as successful cron completions", async () => {
193210
mockAgentRun({
194211
didSendViaMessagingTool: true,
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import { resetTaskRegistryForTests } from "../tasks/task-runtime.test-helpers.js";
3+
import { withOpenClawTestState } from "../test-utils/openclaw-test-state.js";
4+
import {
5+
loadRunCronIsolatedAgentTurn,
6+
mockRunCronFallbackPassthrough,
7+
resetRunCronIsolatedAgentTurnHarness,
8+
resolveConfiguredModelRefMock,
9+
resolveCronPayloadOutcomeMock,
10+
runEmbeddedAgentMock,
11+
} from "./isolated-agent/run.test-harness.js";
12+
import { CronService } from "./service.js";
13+
import { createNoopLogger } from "./service.test-harness.js";
14+
import { loadCronStore } from "./store.js";
15+
16+
const runCronIsolatedAgentTurn = await loadRunCronIsolatedAgentTurn();
17+
18+
type CronServiceParams = ConstructorParameters<typeof CronService>[0];
19+
type SendCronFailureAlertParams = Parameters<
20+
NonNullable<CronServiceParams["sendCronFailureAlert"]>
21+
>[0];
22+
23+
describe.sequential("CronService silent failure alerts", () => {
24+
beforeEach(() => {
25+
resetRunCronIsolatedAgentTurnHarness();
26+
});
27+
28+
it("persists a tool failure and emits the configured operator alert", async () => {
29+
const { resolveCronPayloadOutcome } = await vi.importActual<
30+
typeof import("./isolated-agent/helpers.js")
31+
>("./isolated-agent/helpers.js");
32+
resolveCronPayloadOutcomeMock.mockImplementation(resolveCronPayloadOutcome);
33+
const modelRef = { provider: "openai", model: "gpt-5.4" };
34+
resolveConfiguredModelRefMock.mockReturnValue(modelRef);
35+
mockRunCronFallbackPassthrough();
36+
runEmbeddedAgentMock.mockResolvedValue({
37+
payloads: [{ text: "⚠️ 🛠️ Bash failed: mount unavailable", isError: true }],
38+
meta: { agentMeta: {}, finalAssistantVisibleText: "NO_REPLY" },
39+
});
40+
41+
await withOpenClawTestState(
42+
{ layout: "state-only", prefix: "openclaw-cron-silent-failure-" },
43+
async (state) => {
44+
resetTaskRegistryForTests();
45+
const sendCronFailureAlert = vi.fn(
46+
async (_params: SendCronFailureAlertParams) => undefined,
47+
);
48+
const storePath = state.path("cron", "jobs.json");
49+
const cron = new CronService({
50+
storePath,
51+
cronEnabled: true,
52+
cronConfig: {
53+
triggers: { enabled: true },
54+
failureAlert: { enabled: true, after: 1, cooldownMs: 0 },
55+
},
56+
log: createNoopLogger(),
57+
enqueueSystemEvent: vi.fn(),
58+
requestHeartbeat: vi.fn(),
59+
sendCronFailureAlert,
60+
runIsolatedAgentJob: async (runParams) =>
61+
await runCronIsolatedAgentTurn({
62+
...runParams,
63+
cfg: { agents: { defaults: { model: `${modelRef.provider}/${modelRef.model}` } } },
64+
deps: {},
65+
sessionKey: `cron:${runParams.job.id}`,
66+
}),
67+
});
68+
try {
69+
await cron.start();
70+
const job = await cron.add({
71+
name: "mount check",
72+
enabled: true,
73+
schedule: { kind: "every", everyMs: 60_000 },
74+
sessionTarget: "isolated",
75+
wakeMode: "next-heartbeat",
76+
payload: {
77+
kind: "agentTurn",
78+
message: "check mount",
79+
model: `${modelRef.provider}/${modelRef.model}`,
80+
},
81+
delivery: { mode: "none" },
82+
});
83+
84+
await expect(cron.run(job.id, "force")).resolves.toEqual({ ok: true, ran: true });
85+
86+
const persisted = (await loadCronStore(storePath)).jobs.find(
87+
(candidate) => candidate.id === job.id,
88+
);
89+
expect(persisted?.state.lastRunStatus).toBe("error");
90+
expect(persisted?.state.lastError).toContain("Bash failed");
91+
expect(persisted?.state.consecutiveErrors).toBe(1);
92+
expect(persisted?.state.lastFailureAlertAtMs).toBeDefined();
93+
expect(sendCronFailureAlert).toHaveBeenCalledOnce();
94+
expect(sendCronFailureAlert.mock.calls[0]?.[0].payload.text).toContain(
95+
'Automation "mount check" failed 1 times',
96+
);
97+
} finally {
98+
cron.stop();
99+
resetTaskRegistryForTests({ persist: false });
100+
}
101+
},
102+
);
103+
});
104+
});

0 commit comments

Comments
 (0)