Skip to content

Commit 641a4bf

Browse files
steipetePeter Steinberger
andauthored
fix(whatsapp): reject unaccepted provider deliveries (#118114)
Co-authored-by: Peter Steinberger <[email protected]>
1 parent dc16b14 commit 641a4bf

10 files changed

Lines changed: 1888 additions & 211 deletions

File tree

‎extensions/whatsapp/src/auto-reply/deliver-reply.test.ts‎

Lines changed: 203 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
11
// Whatsapp tests cover deliver reply plugin behavior.
2-
import { createChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
2+
import type { WAMessage } from "baileys";
33
import {
4-
createMessageReceiptFromOutboundResults,
5-
listMessageReceiptPlatformIds,
6-
} from "openclaw/plugin-sdk/channel-outbound";
4+
createChannelPartialDeliveryError,
5+
isChannelPartialDeliveryError,
6+
} from "openclaw/plugin-sdk/channel-inbound";
7+
import { listMessageReceiptPlatformIds } from "openclaw/plugin-sdk/channel-outbound";
8+
import { PlatformMessageNotDispatchedError } from "openclaw/plugin-sdk/error-runtime";
79
import { MEDIA_FFMPEG_MAX_AUDIO_DURATION_SECS } from "openclaw/plugin-sdk/media-runtime";
810
import { logVerbose } from "openclaw/plugin-sdk/runtime-env";
911
import { beforeAll, describe, expect, it, vi } from "vitest";
12+
import { createWebSendApi } from "../inbound/send-api.js";
13+
import { normalizeWhatsAppSendResult } from "../inbound/send-result.js";
1014
import { createAcceptedWhatsAppSendResult } from "../inbound/send-result.test-helper.js";
1115
import { createTestWebInboundMessage } from "../inbound/test-message.test-helper.js";
1216
import type { AdmittedWebInboundMessage } from "../inbound/types.js";
@@ -15,9 +19,20 @@ import { cacheInboundMessageMeta } from "../quoted-message.js";
1519
import { withWhatsAppSocketOperationTimeout } from "../socket-timing.js";
1620

1721
const hoisted = vi.hoisted(() => ({
22+
recordChannelActivity: vi.fn(),
1823
transcodeAudioBufferToOpus: vi.fn(),
1924
}));
2025

26+
vi.mock("openclaw/plugin-sdk/channel-activity-runtime", async () => {
27+
const actual = await vi.importActual<
28+
typeof import("openclaw/plugin-sdk/channel-activity-runtime")
29+
>("openclaw/plugin-sdk/channel-activity-runtime");
30+
return {
31+
...actual,
32+
recordChannelActivity: (...args: unknown[]) => hoisted.recordChannelActivity(...args),
33+
};
34+
});
35+
2136
vi.mock("openclaw/plugin-sdk/media-runtime", async () => {
2237
const actual = await vi.importActual<typeof import("openclaw/plugin-sdk/media-runtime")>(
2338
"openclaw/plugin-sdk/media-runtime",
@@ -214,7 +229,8 @@ describe("deliverWebReply", () => {
214229

215230
it("does not resend an accepted reply when its transport reports a disconnect afterward", async () => {
216231
const { msg, params } = createDelivery({ text: "already delivered" });
217-
const acceptedFailure = createChannelPartialDeliveryError(new Error("connection closed"), {
232+
const disconnect = new Error("connection closed");
233+
const acceptedFailure = createChannelPartialDeliveryError(disconnect, {
218234
messageIds: ["reply-already-accepted"],
219235
visibleReplySent: true,
220236
});
@@ -224,7 +240,15 @@ describe("deliverWebReply", () => {
224240
deliverWebReply(params).catch((caught: unknown) => caught),
225241
);
226242

227-
expect(failure).toBe(acceptedFailure);
243+
expect(isChannelPartialDeliveryError(failure)).toBe(true);
244+
if (!isChannelPartialDeliveryError(failure)) {
245+
throw new Error("accepted reply was not promoted to a receipt-backed partial delivery");
246+
}
247+
expect(failure).not.toBe(acceptedFailure);
248+
expect(failure.deliveryResult.messageIds).toEqual(["reply-already-accepted"]);
249+
expect(failure.deliveryResult.receipt?.platformMessageIds).toEqual(["reply-already-accepted"]);
250+
expect(failure).toHaveProperty("cause", disconnect);
251+
expect(failure).toMatchObject({ sentBeforeError: true, visibleReplySent: true });
228252
expect(msg.platform.reply).toHaveBeenCalledOnce();
229253
});
230254

@@ -255,6 +279,7 @@ describe("deliverWebReply", () => {
255279
});
256280

257281
it("sends chunked text replies and logs a summary", async () => {
282+
hoisted.recordChannelActivity.mockClear();
258283
const { msg, params } = createDelivery({ text: "aaaaaa" }, { textLimit: 3 });
259284

260285
const delivery = await deliverWebReply(params);
@@ -270,27 +295,91 @@ describe("deliverWebReply", () => {
270295
expect(delivery.receipt.platformMessageIds).toEqual(["reply-sent-1"]);
271296
expect(delivery.receipt.parts[0]?.platformMessageId).toBe("reply-sent-1");
272297
expect(delivery.receipt.parts[0]?.kind).toBe("text");
298+
expect(hoisted.recordChannelActivity).toHaveBeenCalledExactlyOnceWith({
299+
channel: "whatsapp",
300+
accountId: "work",
301+
direction: "outbound",
302+
});
273303
});
274304

275-
it("reports text replies that Baileys did not accept", async () => {
305+
it("retains an accepted auto-reply receipt when outbound activity bookkeeping fails", async () => {
306+
hoisted.recordChannelActivity.mockClear();
307+
const activityError = new Error("auto-reply activity bookkeeping disconnected");
308+
hoisted.recordChannelActivity.mockImplementationOnce(() => {
309+
throw activityError;
310+
});
311+
const { msg, params } = createDelivery({ text: "already accepted" });
312+
313+
const failure = await deliverWebReply(params).catch((caught: unknown) => caught);
314+
315+
expect(isChannelPartialDeliveryError(failure)).toBe(true);
316+
if (!isChannelPartialDeliveryError(failure)) {
317+
throw new Error("accepted auto-reply receipt was discarded during activity bookkeeping");
318+
}
319+
expect(failure.deliveryResult.messageIds).toEqual(["reply-sent-1"]);
320+
expect(failure.deliveryResult.receipt?.platformMessageIds).toEqual(["reply-sent-1"]);
321+
expect(failure).toHaveProperty("cause", activityError);
322+
expect(msg.platform.reply).toHaveBeenCalledOnce();
323+
expect(hoisted.recordChannelActivity).toHaveBeenCalledOnce();
324+
});
325+
326+
it("merges earlier accepted chunks with a nested accepted-chunk bookkeeping failure", async () => {
327+
hoisted.recordChannelActivity.mockClear();
328+
const bookkeepingError = new Error("second accepted chunk bookkeeping failed");
329+
const firstChunk = normalizeWhatsAppSendResult(
330+
{ key: { id: "auto-reply-first-chunk" } } as WAMessage,
331+
"text",
332+
);
333+
const secondChunk = normalizeWhatsAppSendResult(
334+
{ key: { id: "auto-reply-second-chunk" } } as WAMessage,
335+
"text",
336+
);
337+
const { msg, params } = createDelivery({ text: "aaaaaa" }, { textLimit: 3 });
338+
vi.mocked(msg.platform.reply)
339+
.mockResolvedValueOnce(firstChunk)
340+
.mockRejectedValueOnce(
341+
createChannelPartialDeliveryError(bookkeepingError, {
342+
messageIds: [secondChunk.messageId],
343+
receipt: secondChunk.receipt,
344+
visibleReplySent: true,
345+
}),
346+
);
347+
348+
const failure = await deliverWebReply(params).catch((caught: unknown) => caught);
349+
350+
expect(isChannelPartialDeliveryError(failure)).toBe(true);
351+
if (!isChannelPartialDeliveryError(failure)) {
352+
throw new Error(
353+
"accepted auto-reply chunks were not composed after nested bookkeeping failed",
354+
);
355+
}
356+
expect(failure.deliveryResult.messageIds).toEqual([
357+
"auto-reply-first-chunk",
358+
"auto-reply-second-chunk",
359+
]);
360+
expect(failure.deliveryResult.receipt?.platformMessageIds).toEqual([
361+
"auto-reply-first-chunk",
362+
"auto-reply-second-chunk",
363+
]);
364+
expect(failure).toHaveProperty("cause", bookkeepingError);
365+
expect(msg.platform.reply).toHaveBeenCalledTimes(2);
366+
expect(hoisted.recordChannelActivity).toHaveBeenCalledOnce();
367+
});
368+
369+
it("rejects text replies that Baileys did not accept without recording outbound activity", async () => {
370+
hoisted.recordChannelActivity.mockClear();
276371
const { msg, params } = createDelivery({ text: "hello" });
277372
vi.mocked(msg.platform.reply).mockResolvedValueOnce({
278373
...createAcceptedWhatsAppSendResult("text", "unknown"),
279-
receipt: createMessageReceiptFromOutboundResults({ kind: "text", results: [] }),
374+
receipt: undefined,
280375
keys: [],
281376
providerAccepted: false,
282377
});
283378

284-
const delivery = await deliverWebReply(params);
379+
await expect(deliverWebReply(params)).rejects.toBeInstanceOf(PlatformMessageNotDispatchedError);
285380

286-
expect(msg.platform.reply).toHaveBeenCalledTimes(1);
287-
expect(delivery.receipt.platformMessageIds).toEqual([]);
288-
expect(delivery.receipt.parts).toEqual([]);
289-
expect(delivery.providerAccepted).toBe(false);
290-
expect(typeof mockCallArg(replyLogger.warn, 0, 0, "replyLogger.warn")).toBe("object");
291-
expect(mockCallArg(replyLogger.warn, 0, 1, "replyLogger.warn")).toBe(
292-
"auto-reply text was not accepted by WhatsApp provider",
293-
);
381+
expect(msg.platform.reply).toHaveBeenCalledOnce();
382+
expect(hoisted.recordChannelActivity).not.toHaveBeenCalled();
294383
});
295384

296385
it("strips raw XML tool-call blocks before WhatsApp text delivery", async () => {
@@ -632,13 +721,24 @@ describe("deliverWebReply", () => {
632721
);
633722
vi.mocked(msg.platform.sendMedia).mockRejectedValueOnce(new Error("upload failed"));
634723

635-
await deliverWebReply(params);
724+
const delivery = await deliverWebReply(params);
636725

637726
// First media succeeded — no text reply for it.
638727
// Second media failed — user must be notified, not silently dropped.
728+
expect(msg.platform.sendMedia).toHaveBeenCalledTimes(2);
639729
expect(msg.platform.reply).toHaveBeenCalledTimes(1);
640730
expect(replyText(msg)).toContain("⚠️ Media unavailable");
641731
expect(replyText(msg)).not.toContain("upload failed");
732+
expect(delivery.receipt.platformMessageIds).toEqual(["media-first-ok", "reply-sent-1"]);
733+
expect(hoisted.recordChannelActivity).toHaveBeenCalledExactlyOnceWith({
734+
channel: "whatsapp",
735+
accountId: "work",
736+
direction: "outbound",
737+
});
738+
expect(replyLogger.warn).toHaveBeenCalledWith(
739+
expect.objectContaining({ mediaUrl: "http://example.com/img2.jpg" }),
740+
"failed to send web media reply",
741+
);
642742
});
643743

644744
it("sanitizes XML tool-call blocks for outbound sendPayload delivery", async () => {
@@ -731,6 +831,91 @@ describe("deliverWebReply", () => {
731831
expect(msg.platform.reply).toHaveBeenCalledWith("cap", undefined);
732832
});
733833

834+
it("preserves accepted voice receipts without false media fallback after caption rejection", async () => {
835+
hoisted.recordChannelActivity.mockClear();
836+
const { msg, params } = createDelivery({
837+
text: "caption",
838+
mediaUrl: "http://example.com/accepted-voice.ogg",
839+
});
840+
mockLoadedMedia("aud", "audio/ogg", "audio");
841+
vi.mocked(msg.platform.sendMedia).mockImplementationOnce(async () =>
842+
normalizeWhatsAppSendResult(
843+
{ key: { id: "auto-reply-voice-accepted" } } as WAMessage,
844+
"media",
845+
),
846+
);
847+
vi.mocked(msg.platform.reply).mockImplementationOnce(async () =>
848+
normalizeWhatsAppSendResult(undefined, "text"),
849+
);
850+
851+
const failure = await deliverWebReply(params).catch((caught: unknown) => caught);
852+
853+
expect(isChannelPartialDeliveryError(failure)).toBe(true);
854+
if (!isChannelPartialDeliveryError(failure)) {
855+
throw new Error("accepted auto-reply voice receipt was discarded after caption rejection");
856+
}
857+
expect(failure.deliveryResult.visibleReplySent).toBe(true);
858+
expect(failure.deliveryResult.messageIds).toEqual(["auto-reply-voice-accepted"]);
859+
expect(failure.deliveryResult.receipt?.platformMessageIds).toEqual([
860+
"auto-reply-voice-accepted",
861+
]);
862+
expect(failure).toHaveProperty("cause", expect.any(PlatformMessageNotDispatchedError));
863+
expect(msg.platform.sendMedia).toHaveBeenCalledOnce();
864+
expect(msg.platform.reply).toHaveBeenCalledOnce();
865+
expect(msg.platform.reply).toHaveBeenCalledWith("caption", undefined);
866+
expect(hoisted.recordChannelActivity).toHaveBeenCalledOnce();
867+
expect(hoisted.recordChannelActivity).toHaveBeenCalledWith({
868+
channel: "whatsapp",
869+
accountId: "work",
870+
direction: "outbound",
871+
});
872+
});
873+
874+
it("keeps accepted media receipts when the inner sender throws during activity bookkeeping", async () => {
875+
hoisted.recordChannelActivity.mockClear();
876+
replyLogger.warn.mockClear();
877+
const bookkeepingError = new Error("accepted media bookkeeping failed");
878+
hoisted.recordChannelActivity.mockImplementationOnce(() => {
879+
throw bookkeepingError;
880+
});
881+
const sendMessage = vi.fn(
882+
async () => ({ key: { id: "auto-reply-nested-media" } }) as WAMessage,
883+
);
884+
const sendApi = createWebSendApi({
885+
sock: {
886+
sendMessage,
887+
sendPresenceUpdate: vi.fn(async () => undefined),
888+
},
889+
defaultAccountId: "work",
890+
});
891+
const { msg, params } = createDelivery({
892+
text: "caption",
893+
mediaUrl: "http://example.com/nested-voice.ogg",
894+
});
895+
mockLoadedMedia("aud", "audio/ogg", "audio");
896+
vi.mocked(msg.platform.sendMedia).mockImplementationOnce(async () =>
897+
sendApi.sendMessage("+1555", "", Buffer.from("aud"), "audio/ogg"),
898+
);
899+
900+
const failure = await deliverWebReply(params).catch((caught: unknown) => caught);
901+
902+
expect(isChannelPartialDeliveryError(failure)).toBe(true);
903+
if (!isChannelPartialDeliveryError(failure)) {
904+
throw new Error("nested accepted media delivery was treated as a failed upload");
905+
}
906+
expect(failure.deliveryResult.messageIds).toEqual(["auto-reply-nested-media"]);
907+
expect(failure.deliveryResult.receipt?.platformMessageIds).toEqual(["auto-reply-nested-media"]);
908+
expect(failure).toHaveProperty("cause", bookkeepingError);
909+
expect(msg.platform.sendMedia).toHaveBeenCalledOnce();
910+
expect(msg.platform.reply).not.toHaveBeenCalled();
911+
expect(replyLogger.warn).not.toHaveBeenCalled();
912+
expect(hoisted.recordChannelActivity).toHaveBeenCalledExactlyOnceWith({
913+
channel: "whatsapp",
914+
accountId: "work",
915+
direction: "outbound",
916+
});
917+
});
918+
734919
it("transcodes mp3 audio media before sending a ptt voice note", async () => {
735920
vi.clearAllMocks();
736921
hoisted.transcodeAudioBufferToOpus.mockResolvedValue(Buffer.from("opus-output"));

0 commit comments

Comments
 (0)