Skip to content

Commit 04857c7

Browse files
moeedahmedsteipete
andauthored
fix: surface terminal agent run failures (#99304)
* fix: surface empty terminal run failures Co-authored-by: Moeed Ahmed <[email protected]> * docs: note terminal failure replies * fix: normalize terminal failure replies * fix: preserve terminal failure reply threading --------- Co-authored-by: Peter Steinberger <[email protected]> Co-authored-by: Moeed Ahmed <[email protected]>
1 parent a320f77 commit 04857c7

8 files changed

Lines changed: 371 additions & 43 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ Docs: https://docs.openclaw.ai
1414
### Fixes
1515

1616
- **iOS QR gateway handoff:** stop VisionKit before delivering scanned setup codes, and keep deferred auth, approval, Watch, and foreground-node work bound to its originating gateway across reconnects. (#99572) Thanks @PollyBot13.
17+
- **Agent terminal failures:** surface a safe interactive reply when an agent run ends without visible output, while preserving completed message-tool delivery and heartbeat-specific guidance. (#99304) Thanks @moeedahmed.
1718
- **iOS Voice Wake cleanup:** avoid initializing the microphone audio pipeline while disabling inactive Voice Wake, preventing simulator launch aborts and unnecessary audio setup.
1819
- **Cron duration validation:** reject positive durations that truncate below one millisecond instead of silently scheduling a zero-duration interval. (#100311) Thanks @qingminglong.
1920
- **Skill workshop proposals:** preserve the terminal newline in generated proposal Markdown while still rejecting blank raw content. (#100293) Thanks @anyech.

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

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2073,6 +2073,7 @@ describe("runAgentTurnWithFallback", () => {
20732073
fallbackExhausted: true,
20742074
fallbackProvider: probe.provider,
20752075
fallbackModel: probe.model,
2076+
runResult: exhaustedResult,
20762077
});
20772078
expect(activeSessionStore[sessionKey]).toMatchObject({
20782079
providerOverride: probe.fallbackProvider,
@@ -2140,7 +2141,7 @@ describe("runAgentTurnWithFallback", () => {
21402141
}),
21412142
);
21422143

2143-
expect(result.kind).toBe("success");
2144+
expect(result).toMatchObject({ kind: "success", runResult: terminalErrorResult });
21442145
expect(retainFailureUntilCompleteMock).toHaveBeenCalledTimes(1);
21452146
expect(failMock).toHaveBeenCalledWith("run_failed", expect.any(Error));
21462147
const lifecycleEvents = emitAgentEvent.mock.calls
@@ -2167,6 +2168,66 @@ describe("runAgentTurnWithFallback", () => {
21672168
expect(JSON.stringify(lifecycleEvents)).not.toContain("raw provider detail");
21682169
});
21692170

2171+
it.each([
2172+
{
2173+
label: "exhausted",
2174+
outcome: "exhausted" as const,
2175+
attempts: [{ error: "missing tool result" }],
2176+
isHeartbeat: false,
2177+
expectedText: GENERIC_RUN_FAILURE_TEXT,
2178+
},
2179+
{
2180+
label: "completed",
2181+
outcome: "completed" as const,
2182+
attempts: [],
2183+
isHeartbeat: false,
2184+
expectedText: GENERIC_RUN_FAILURE_TEXT,
2185+
},
2186+
{
2187+
label: "heartbeat",
2188+
outcome: "completed" as const,
2189+
attempts: [],
2190+
isHeartbeat: true,
2191+
expectedText: HEARTBEAT_EXTERNAL_RUN_FAILURE_TEXT,
2192+
},
2193+
])("surfaces an empty $label terminal result through the normal reply path", async (testCase) => {
2194+
state.runEmbeddedAgentMock.mockResolvedValueOnce({
2195+
payloads: [],
2196+
meta: {
2197+
error: {
2198+
kind: "tool_result_mismatch",
2199+
message: "Agent run reached a terminal error before reply delivery.",
2200+
},
2201+
},
2202+
});
2203+
state.runWithModelFallbackMock.mockImplementationOnce(async (params: FallbackRunnerParams) => ({
2204+
outcome: testCase.outcome,
2205+
result: await params.run("anthropic", "claude"),
2206+
provider: "anthropic",
2207+
model: "claude",
2208+
attempts: testCase.attempts,
2209+
}));
2210+
const { replyOperation, failMock } = createMockReplyOperation();
2211+
2212+
const runAgentTurnWithFallback = await getRunAgentTurnWithFallback();
2213+
const result = await runAgentTurnWithFallback({
2214+
...createMinimalRunAgentTurnParams({ replyOperation }),
2215+
isHeartbeat: testCase.isHeartbeat,
2216+
});
2217+
2218+
expect(result).toMatchObject({
2219+
kind: "success",
2220+
terminalFailurePayload: {
2221+
text: testCase.expectedText,
2222+
isError: true,
2223+
},
2224+
runResult: {
2225+
payloads: [],
2226+
},
2227+
});
2228+
expect(failMock).toHaveBeenCalledWith("run_failed", expect.any(Error));
2229+
});
2230+
21702231
it("reports exhausted CLI results without a success lifecycle terminal", async () => {
21712232
state.isCliProviderMock.mockReturnValue(true);
21722233
state.runWithModelFallbackMock.mockImplementationOnce(async (params: FallbackRunnerParams) => ({

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,8 @@ export type AgentRunLoopResult =
427427
directlySentBlockKeys?: Set<string>;
428428
/** Payloads successfully sent directly during tool flush. */
429429
directlySentBlockPayloads?: ReplyPayload[];
430+
/** Prepared terminal failure, appended only after delivery evidence settles. */
431+
terminalFailurePayload?: ReplyPayload;
430432
}
431433
| { kind: "final"; payload: ReplyPayload };
432434

@@ -1839,6 +1841,7 @@ async function runAgentTurnWithFallbackInternal(
18391841
let attemptedRuntimeModel = fallbackModel;
18401842
let fallbackAttempts: RuntimeFallbackAttempt[] = [];
18411843
let fallbackExhausted = false;
1844+
let terminalRunFailed = false;
18421845
let pendingLifecycleTerminal:
18431846
| {
18441847
provider: string;
@@ -3165,6 +3168,7 @@ async function runAgentTurnWithFallbackInternal(
31653168
const exhaustionError = new Error(
31663169
terminalErrorMessage ?? "All model fallback candidates failed",
31673170
);
3171+
terminalRunFailed = true;
31683172
emitSettledLifecycleError(exhaustionError, {
31693173
...terminalMetadata,
31703174
fallbackExhaustedFailure: true,
@@ -3173,6 +3177,7 @@ async function runAgentTurnWithFallbackInternal(
31733177
params.replyOperation?.fail("run_failed", exhaustionError);
31743178
} else if (deferredLifecycleError || embeddedError) {
31753179
const terminalError = new Error(terminalErrorMessage ?? "Agent run failed");
3180+
terminalRunFailed = true;
31763181
emitSettledLifecycleError(terminalError, terminalMetadata);
31773182
params.replyOperation?.retainFailureUntilComplete();
31783183
params.replyOperation?.fail("run_failed", terminalError);
@@ -3524,6 +3529,18 @@ async function runAgentTurnWithFallbackInternal(
35243529
}
35253530
}
35263531
}
3532+
const terminalFailurePayload = terminalRunFailed
3533+
? markAgentRunFailureReplyPayload({
3534+
text: resolveExternalRunFailureTextForConversation({
3535+
text: params.isHeartbeat
3536+
? HEARTBEAT_EXTERNAL_RUN_FAILURE_TEXT
3537+
: GENERIC_EXTERNAL_RUN_FAILURE_TEXT,
3538+
sessionCtx: params.sessionCtx,
3539+
isGenericRunnerFailure: true,
3540+
cfg: params.followupRun.run.config,
3541+
}),
3542+
})
3543+
: undefined;
35273544

35283545
return {
35293546
kind: "success",
@@ -3539,6 +3556,7 @@ async function runAgentTurnWithFallbackInternal(
35393556
directlySentBlockPayloads: directlySentBlockPayloads.filter(
35403557
(payload): payload is ReplyPayload => payload !== undefined,
35413558
),
3559+
...(terminalFailurePayload ? { terminalFailurePayload } : {}),
35423560
};
35433561
}
35443562

‎src/auto-reply/reply/agent-runner-payloads.test.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
} from "../reply-payload.js";
1414
import { buildReplyPayloads } from "./agent-runner-payloads.js";
1515
import { createBlockReplyPipeline } from "./block-reply-pipeline.js";
16+
import { createReplyToModeFilterForChannel } from "./reply-threading.js";
1617

1718
const baseParams = {
1819
isHeartbeat: false,
@@ -136,6 +137,28 @@ describe("buildReplyPayloads media filter integration", () => {
136137
);
137138
});
138139

140+
it("shares first-reply threading across staged payload builds", async () => {
141+
const applyReplyToMode = createReplyToModeFilterForChannel("first", "whatsapp");
142+
const sharedParams = {
143+
...baseParams,
144+
replyToMode: "first" as const,
145+
replyToChannel: "whatsapp" as const,
146+
currentMessageId: "msg",
147+
applyReplyToMode,
148+
};
149+
const first = await buildReplyPayloads({
150+
...sharedParams,
151+
payloads: [{ text: "internal commentary", isCommentary: true }],
152+
});
153+
const fallback = await buildReplyPayloads({
154+
...sharedParams,
155+
payloads: [{ text: "run failed", isError: true }],
156+
});
157+
158+
expect(first.replyPayloads[0]?.replyToId).toBe("msg");
159+
expect(fallback.replyPayloads[0]?.replyToId).toBeUndefined();
160+
});
161+
139162
it("records the reply policy used by dedupe and final delivery", async () => {
140163
const { replyPayloads } = await buildReplyPayloads({
141164
...baseParams,
@@ -629,6 +652,36 @@ describe("buildReplyPayloads media filter integration", () => {
629652
expect(replyPayloads.map((payload) => payload.text)).toEqual(["intro", "result"]);
630653
});
631654

655+
it("dedupes against final routes when first-reply state is shared", async () => {
656+
const applyReplyToMode = createReplyToModeFilterForChannel("first", "slack");
657+
const { replyPayloads } = await buildReplyPayloads({
658+
...baseParams,
659+
config: {},
660+
payloads: [{ text: "intro" }, { text: "result" }],
661+
replyToMode: "first",
662+
replyToChannel: "slack",
663+
currentMessageId: "111.000",
664+
applyReplyToMode,
665+
messageProvider: "slack",
666+
originatingTo: "channel:C1",
667+
messagingToolSentTexts: ["result"],
668+
messagingToolSentTargets: [
669+
{
670+
tool: "slack",
671+
provider: "slack",
672+
to: "channel:C1",
673+
threadId: "111.000",
674+
text: "result",
675+
},
676+
],
677+
});
678+
679+
expect(replyPayloads.map((payload) => [payload.text, payload.replyToId])).toEqual([
680+
["intro", "111.000"],
681+
["result", undefined],
682+
]);
683+
});
684+
632685
it("does not treat a Discord native reply id as a thread route", async () => {
633686
const { replyPayloads } = await buildReplyPayloads({
634687
...baseParams,

‎src/auto-reply/reply/agent-runner-payloads.ts‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,11 @@ import {
2828
resolveOriginMessageTo,
2929
} from "./origin-routing.js";
3030
import { normalizeReplyPayloadDirectives } from "./reply-delivery.js";
31-
import { applyReplyThreading, isRenderablePayload } from "./reply-payloads-base.js";
31+
import {
32+
applyReplyThreading,
33+
isRenderablePayload,
34+
resolveReplyThreadingPayloads,
35+
} from "./reply-payloads-base.js";
3236
import { createReplyDeliveryContext } from "./reply-threading.js";
3337

3438
const replyPayloadsDedupeRuntimeLoader = createLazyImportLoader(
@@ -179,6 +183,7 @@ export async function buildReplyPayloads(params: {
179183
replyToChannel?: OriginatingChannelType;
180184
currentMessageId?: string;
181185
replyThreading?: ReplyThreadingPolicy;
186+
applyReplyToMode?: (payload: ReplyPayload) => ReplyPayload;
182187
messageProvider?: string;
183188
messagingToolSentTexts?: string[];
184189
messagingToolSentMediaUrls?: string[];
@@ -236,8 +241,11 @@ export async function buildReplyPayloads(params: {
236241
...(accountId ? { accountId } : {}),
237242
}
238243
: undefined;
244+
const resolveThreading = params.applyReplyToMode
245+
? resolveReplyThreadingPayloads
246+
: applyReplyThreading;
239247
const replyTaggedPayloadCandidates = await Promise.all(
240-
applyReplyThreading({
248+
resolveThreading({
241249
payloads: sanitizedPayloads,
242250
replyToMode: params.replyToMode,
243251
replyToChannel: params.replyToChannel,
@@ -281,6 +289,9 @@ export async function buildReplyPayloads(params: {
281289
} else {
282290
silentFilteredPayloads.push(...replyTaggedPayloads);
283291
}
292+
const threadedPayloads = params.applyReplyToMode
293+
? silentFilteredPayloads.map(params.applyReplyToMode)
294+
: silentFilteredPayloads;
284295

285296
// Drop final payloads only when block streaming succeeded end-to-end.
286297
// If streaming aborted (e.g., timeout), fall back to final payloads.
@@ -295,14 +306,14 @@ export async function buildReplyPayloads(params: {
295306
(params.messagingToolSentMediaUrls?.length ?? 0) > 0 ||
296307
messagingToolSentTargets.length > 0;
297308
const sentMediaUrlFallback = params.messagingToolSentMediaUrls ?? [];
298-
let dedupedPayloads = silentFilteredPayloads;
309+
let dedupedPayloads = threadedPayloads;
299310
if (shouldCheckMessagingToolDedupe) {
300311
const dedupeRuntime = await loadReplyPayloadsDedupeRuntime();
301312
const originatingTo = resolveOriginMessageTo({
302313
originatingTo: params.originatingTo,
303314
});
304315
dedupedPayloads = [];
305-
for (const payload of silentFilteredPayloads) {
316+
for (const payload of threadedPayloads) {
306317
const payloadMetadata = getReplyPayloadMetadata(payload);
307318
// Source mirrors exist because an internal sink send must reach the UI and
308319
// transcript; that send is not outbound evidence for dropping the mirror.

0 commit comments

Comments
 (0)