Skip to content

Commit efde610

Browse files
authored
fix(auto-reply): report failed queued replies after status delivery (#125325)
* fix(auto-reply): report partial followup delivery failure * fix(auto-reply): classify followup batch failures * fix(auto-reply): preserve followup delivery ownership * test(auto-reply): consolidate followup delivery coverage
1 parent 49af98c commit efde610

16 files changed

Lines changed: 304 additions & 81 deletions

‎src/auto-reply/reply-payload.test.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Reply payload tests cover internal reply metadata contracts.
22
import { describe, expect, it } from "vitest";
3-
import { readPairingQrReplyChannelData } from "./reply-payload.js";
3+
import { isReplyPayloadTerminalContent, readPairingQrReplyChannelData } from "./reply-payload.js";
44

55
describe("pairing QR reply channel data", () => {
66
it("reads the private pairing QR payload metadata", () => {
@@ -30,3 +30,23 @@ describe("pairing QR reply channel data", () => {
3030
).toBeUndefined();
3131
});
3232
});
33+
34+
describe("reply payload terminal content", () => {
35+
it.each([
36+
["text", { text: "answer" }, true],
37+
["media", { mediaUrl: "file:///tmp/answer.png" }, true],
38+
["reasoning", { text: "thinking", isReasoning: true }, false],
39+
["commentary", { text: "working", isCommentary: true }, false],
40+
["status", { text: "compacting", isStatusNotice: true }, false],
41+
[
42+
"TTS supplement",
43+
{
44+
mediaUrl: "file:///tmp/answer.mp3",
45+
ttsSupplement: { spokenText: "answer", visibleTextAlreadyDelivered: true },
46+
},
47+
false,
48+
],
49+
] as const)("classifies %s payloads", (_name, payload, expected) => {
50+
expect(isReplyPayloadTerminalContent(payload)).toBe(expected);
51+
});
52+
});

‎src/auto-reply/reply-payload.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,3 +357,10 @@ export function isReplyPayloadStatusNotice(
357357
): boolean {
358358
return Boolean(payload.isCompactionNotice || payload.isFallbackNotice || payload.isStatusNotice);
359359
}
360+
361+
/** Returns whether a payload carries terminal assistant content rather than a supplemental lane. */
362+
export const isReplyPayloadTerminalContent = (payload: ReplyPayload): boolean =>
363+
payload.isReasoning !== true &&
364+
payload.isCommentary !== true &&
365+
!isReplyPayloadStatusNotice(payload) &&
366+
!isReplyPayloadTtsSupplement(payload);

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

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import {
2020
} from "../../utils/delivery-context.shared.js";
2121
import { resolveFallbackTransition } from "../fallback-state.js";
2222
import {
23-
isReplyPayloadStatusNotice,
23+
isReplyPayloadTerminalContent,
2424
markReplyPayloadForSourceSuppressionDelivery,
2525
setReplyPayloadMetadata,
2626
} from "../reply-payload.js";
@@ -182,9 +182,7 @@ export function hasSuccessfulTerminalSourceReplyDelivery(params: {
182182
}): boolean {
183183
const sentTerminalBlock = params.directlySentBlockPayloads?.some(
184184
(payload) =>
185-
payload.isReasoning !== true &&
186-
payload.isCommentary !== true &&
187-
!isReplyPayloadStatusNotice(payload) &&
185+
isReplyPayloadTerminalContent(payload) &&
188186
normalizeReplyPayload(payload, { applyChannelTransforms: false }) !== null,
189187
);
190188
return (

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

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { estimateUsageCost, resolveModelCostConfig } from "../../utils/usage-for
1818
import { buildFallbackClearedNotice, buildFallbackNotice } from "../fallback-state.js";
1919
import {
2020
isReplyPayloadStatusNotice,
21+
isReplyPayloadTerminalContent,
2122
markReplyPayloadForSourceSuppressionDelivery,
2223
} from "../reply-payload.js";
2324
import type { ReplyPayload } from "../types.js";
@@ -404,9 +405,7 @@ export async function prepareReplyAgentPayloads(state: {
404405
didLogHeartbeatStrip = payloadResult.didLogHeartbeatStrip;
405406
const hasTerminalReplyPayload = replyPayloads.some(
406407
(payload) =>
407-
!payload.isReasoning &&
408-
!payload.isCommentary &&
409-
!isReplyPayloadStatusNotice(payload) &&
408+
isReplyPayloadTerminalContent(payload) &&
410409
normalizeReplyPayload(payload, { applyChannelTransforms: false }) !== null,
411410
);
412411
if (shouldDeliverTerminalFailure && !hasTerminalReplyPayload && terminalFailurePayload) {

‎src/auto-reply/reply/agent-runner-usage-line.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,15 @@ import { getReplyPayloadMetadata, setReplyPayloadMetadata } from "../reply-paylo
66
import { appendUsageLine, resolveResponseUsageLine } from "./agent-runner-usage-line.js";
77

88
describe("appendUsageLine", () => {
9+
it("marks a standalone usage footer as non-terminal status", () => {
10+
expect(
11+
appendUsageLine([{ mediaUrl: "file:///tmp/result.png" }], "Usage: 12 in / 3 out"),
12+
).toEqual([
13+
{ mediaUrl: "file:///tmp/result.png" },
14+
{ text: "Usage: 12 in / 3 out", isStatusNotice: true },
15+
]);
16+
});
17+
918
it("prices response usage for the selected agent in an explicit fleet", () => {
1019
const line = resolveResponseUsageLine({
1120
config: {

‎src/auto-reply/reply/agent-runner-usage-line.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ export const appendUsageLine = (payloads: ReplyPayload[], line: string): ReplyPa
122122
}
123123
}
124124
if (index === -1) {
125-
return [...payloads, { text: line }];
125+
return [...payloads, { text: line, isStatusNotice: true }];
126126
}
127127
const existing = expectDefined(payloads[index], "payloads entry at index");
128128
const existingText = existing.text ?? "";

‎src/auto-reply/reply/block-reply-pipeline.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,11 @@ import {
66
} from "openclaw/plugin-sdk/reply-payload";
77
import { logVerbose } from "../../globals.js";
88
import { runAbortableTimeout } from "../../node-host/with-timeout.js";
9-
import { getReplyPayloadMetadata, isReplyPayloadStatusNotice } from "../reply-payload.js";
9+
import {
10+
getReplyPayloadMetadata,
11+
isReplyPayloadStatusNotice,
12+
isReplyPayloadTerminalContent,
13+
} from "../reply-payload.js";
1014
import type { ReplyPayload } from "../types.js";
1115
import { createBlockReplyCoalescer } from "./block-reply-coalescer.js";
1216
import type { BlockStreamingCoalescing } from "./block-streaming.js";
@@ -180,8 +184,7 @@ export function createBlockReplyPipeline(params: {
180184
if (!isStatusNotice) {
181185
didStream = true;
182186
if (
183-
payload.isReasoning !== true &&
184-
payload.isCommentary !== true &&
187+
isReplyPayloadTerminalContent(payload) &&
185188
hasOutboundReplyContent(payload, { trimText: true })
186189
) {
187190
didStreamTerminalReply = true;

‎src/auto-reply/reply/dispatch-from-config.finalize.ts‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { resolveConfiguredTtsMode } from "../../tts/tts-config.js";
77
import { registerReplyDispatcherSettledTask } from "../dispatch-dispatcher.js";
88
import {
99
getReplyPayloadMetadata,
10-
isReplyPayloadStatusNotice,
10+
isReplyPayloadTerminalContent,
1111
markReplyPayloadAsTtsSupplement,
1212
type ReplyPayload,
1313
} from "../reply-payload.js";
@@ -123,11 +123,7 @@ export async function finalizeDispatchAndAudit(state: ExecuteDispatchReadyState)
123123
continue;
124124
}
125125
sentFinalPayloadDedupeKeys.add(finalPayloadDedupeKey);
126-
const shouldAttachDeferredText =
127-
deferFinalTtsText &&
128-
reply.isReasoning !== true &&
129-
reply.isCommentary !== true &&
130-
!isReplyPayloadStatusNotice(reply);
126+
const shouldAttachDeferredText = deferFinalTtsText && isReplyPayloadTerminalContent(reply);
131127
const finalReply = await state.sendFinalPayload(reply, {
132128
deliveryId: String(replyIndex),
133129
...(shouldAttachDeferredText
Lines changed: 218 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,218 @@
1+
// Proves follow-up batch ownership through the real channel route and durable-send boundary.
2+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3+
import type { ChannelPlugin } from "../../channels/plugins/types.public.js";
4+
import type { OpenClawConfig } from "../../config/config.js";
5+
import { setActivePluginRegistry } from "../../plugins/runtime.js";
6+
import {
7+
createChannelTestPluginBase,
8+
createTestRegistry,
9+
} from "../../test-utils/channel-plugins.js";
10+
import { setReplyPayloadMetadata } from "../reply-payload.js";
11+
import type { ReplyPayload } from "../types.js";
12+
import { deliverFollowupDecision } from "./followup-delivery.js";
13+
import type { AdmittedFollowupTurn } from "./followup-turn-admission.js";
14+
15+
const channelState = vi.hoisted(() => ({
16+
outcomes: [] as Array<"delivered" | "failed">,
17+
deliver: vi.fn(),
18+
}));
19+
20+
vi.mock("../../agents/runtime-plan/build.js", () => ({
21+
buildAgentRuntimeDeliveryPlan: () => ({
22+
isSilentPayload: () => false,
23+
resolveFollowupRoute: () => undefined,
24+
}),
25+
}));
26+
27+
vi.mock("../../infra/outbound/deliver.js", () => ({
28+
deliverOutboundPayloadsInternal: (...args: unknown[]) => channelState.deliver(...args),
29+
}));
30+
31+
function createChannelPlugin(id: ChannelPlugin["id"]): ChannelPlugin {
32+
return createChannelTestPluginBase({
33+
id,
34+
label: String(id),
35+
config: { listAccountIds: () => [], resolveAccount: () => ({}) },
36+
});
37+
}
38+
39+
function createTurn(params: {
40+
messageProvider: string;
41+
originatingChannel: string;
42+
}): AdmittedFollowupTurn {
43+
return {
44+
runId: "run-1",
45+
queued: {
46+
prompt: "queued",
47+
enqueuedAt: 1,
48+
originatingChannel: params.originatingChannel,
49+
originatingTo: "channel:C1",
50+
run: {
51+
agentId: "agent",
52+
agentDir: "/tmp/agent",
53+
sessionId: "session",
54+
sessionKey: "main",
55+
sessionFile: "/tmp/session.jsonl",
56+
workspaceDir: "/tmp",
57+
config: {},
58+
provider: "anthropic",
59+
model: "claude",
60+
messageProvider: params.messageProvider,
61+
timeoutMs: 1_000,
62+
blockReplyBreak: "message_end",
63+
},
64+
},
65+
operation: {} as AdmittedFollowupTurn["operation"],
66+
config: {} as OpenClawConfig,
67+
session: {
68+
kind: "session",
69+
key: "main",
70+
current: () => undefined,
71+
publish: () => undefined,
72+
adopt: () => undefined,
73+
},
74+
sendPolicy: "allow",
75+
preflightCompactionApplied: false,
76+
};
77+
}
78+
79+
function createDefaults(onBlockReply: (payload: ReplyPayload) => Promise<void>) {
80+
return {
81+
defaultModel: "claude",
82+
typingMode: "never" as const,
83+
typing: {
84+
onReplyStart: vi.fn(async () => {}),
85+
startTypingLoop: vi.fn(async () => {}),
86+
startTypingOnText: vi.fn(async () => {}),
87+
refreshTypingTtl: vi.fn(),
88+
isActive: vi.fn(() => false),
89+
markRunComplete: vi.fn(),
90+
markDispatchIdle: vi.fn(),
91+
cleanup: vi.fn(),
92+
},
93+
opts: { onBlockReply },
94+
};
95+
}
96+
97+
async function deliverBatch(params: {
98+
messageProvider: string;
99+
originatingChannel: string;
100+
outcomes: Array<"delivered" | "failed">;
101+
payloads: ReplyPayload[];
102+
}) {
103+
channelState.outcomes = [...params.outcomes];
104+
const onBlockReply = vi.fn(async (_payload: ReplyPayload) => {});
105+
await deliverFollowupDecision({
106+
decision: { kind: "deliver", payloads: params.payloads },
107+
turn: createTurn(params),
108+
defaults: createDefaults(onBlockReply),
109+
runId: "run-1",
110+
runFollowup: vi.fn(async () => {}),
111+
});
112+
return onBlockReply;
113+
}
114+
115+
beforeEach(() => {
116+
setActivePluginRegistry(
117+
createTestRegistry(
118+
(["discord", "imessage", "slack"] as const).map((id) => ({
119+
pluginId: id,
120+
plugin: createChannelPlugin(id),
121+
source: "test",
122+
})),
123+
),
124+
);
125+
channelState.outcomes = [];
126+
channelState.deliver.mockReset();
127+
channelState.deliver.mockImplementation(async (params: { channel: string }) => {
128+
const outcome = channelState.outcomes.shift();
129+
if (outcome === "delivered") {
130+
return [{ channel: params.channel, messageId: `message-${channelState.outcomes.length}` }];
131+
}
132+
throw new Error("simulated channel delivery failure");
133+
});
134+
});
135+
136+
afterEach(() => {
137+
setActivePluginRegistry(createTestRegistry());
138+
});
139+
140+
describe("follow-up delivery channel boundary", () => {
141+
it("emits one safe cross-channel error when a terminal payload fails after status delivery", async () => {
142+
const onBlockReply = await deliverBatch({
143+
messageProvider: "discord",
144+
originatingChannel: "slack",
145+
outcomes: ["delivered", "failed"],
146+
payloads: [
147+
{ text: "status delivered", isStatusNotice: true },
148+
setReplyPayloadMetadata(
149+
{ text: "private terminal reply" },
150+
{ assistantTranscriptOwned: true },
151+
),
152+
],
153+
});
154+
155+
expect(onBlockReply).toHaveBeenCalledOnce();
156+
expect(onBlockReply.mock.calls[0]?.[0]).toMatchObject({ isError: true });
157+
expect(onBlockReply.mock.calls[0]?.[0]?.text).toContain("could not deliver");
158+
expect(onBlockReply.mock.calls[0]?.[0]?.text).not.toContain("private terminal reply");
159+
});
160+
161+
it("keeps a delivered terminal valid when a later TTS supplement fails", async () => {
162+
const onBlockReply = await deliverBatch({
163+
messageProvider: "discord",
164+
originatingChannel: "slack",
165+
outcomes: ["delivered", "failed"],
166+
payloads: [
167+
{ text: "terminal reply" },
168+
{
169+
mediaUrl: "file:///tmp/terminal.mp3",
170+
ttsSupplement: { spokenText: "terminal reply", visibleTextAlreadyDelivered: true },
171+
},
172+
],
173+
});
174+
175+
expect(onBlockReply).not.toHaveBeenCalled();
176+
});
177+
178+
it("emits one safe error when every supplemental origin delivery fails", async () => {
179+
const onBlockReply = await deliverBatch({
180+
messageProvider: "discord",
181+
originatingChannel: "slack",
182+
outcomes: ["failed", "failed"],
183+
payloads: [
184+
{ text: "status one", isStatusNotice: true },
185+
{ text: "status two", isFallbackNotice: true },
186+
],
187+
});
188+
189+
expect(onBlockReply).toHaveBeenCalledOnce();
190+
expect(onBlockReply.mock.calls[0]?.[0]?.text).toContain("could not deliver");
191+
});
192+
193+
it("returns only the failed payload through same-channel recovery", async () => {
194+
const failedFinal = { text: "same-channel final" };
195+
const onBlockReply = await deliverBatch({
196+
messageProvider: "slack",
197+
originatingChannel: "slack",
198+
outcomes: ["delivered", "failed"],
199+
payloads: [{ text: "status", isStatusNotice: true }, failedFinal],
200+
});
201+
202+
expect(onBlockReply).toHaveBeenCalledOnce();
203+
expect(onBlockReply).toHaveBeenCalledWith(failedFinal);
204+
});
205+
206+
it("keeps alias-equivalent built-in channels on same-channel recovery", async () => {
207+
const failedFinal = { text: "alias same-channel final" };
208+
const onBlockReply = await deliverBatch({
209+
messageProvider: "imessage",
210+
originatingChannel: "imsg",
211+
outcomes: ["failed"],
212+
payloads: [failedFinal],
213+
});
214+
215+
expect(onBlockReply).toHaveBeenCalledOnce();
216+
expect(onBlockReply).toHaveBeenCalledWith(failedFinal);
217+
});
218+
});

0 commit comments

Comments
 (0)