Skip to content

Commit 121a862

Browse files
steipetePeter Steinberger
andauthored
fix(whatsapp): preserve accepted delivery across failures (#117198)
Co-authored-by: Peter Steinberger <[email protected]>
1 parent cb16d73 commit 121a862

5 files changed

Lines changed: 192 additions & 21 deletions

File tree

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Whatsapp tests cover deliver reply plugin behavior.
2+
import { createChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
23
import {
34
createMessageReceiptFromOutboundResults,
45
listMessageReceiptPlatformIds,
@@ -234,6 +235,29 @@ describe("deliverWebReply", () => {
234235
({ whatsappOutbound } = await import("../outbound-adapter.js"));
235236
});
236237

238+
it("does not resend an accepted reply when its transport reports a disconnect afterward", async () => {
239+
const msg = makeMsg();
240+
const acceptedFailure = createChannelPartialDeliveryError(new Error("connection closed"), {
241+
messageIds: ["reply-already-accepted"],
242+
visibleReplySent: true,
243+
});
244+
vi.mocked(msg.platform.reply).mockRejectedValue(acceptedFailure);
245+
246+
const failure = await runWithFakeTimers(() =>
247+
deliverWebReply({
248+
replyResult: { text: "already delivered" },
249+
transport: createWhatsAppReplyTransportContext(msg),
250+
maxMediaBytes: 1024 * 1024,
251+
textLimit: 200,
252+
replyLogger,
253+
skipLog: true,
254+
}).catch((caught: unknown) => caught),
255+
);
256+
257+
expect(failure).toBe(acceptedFailure);
258+
expect(msg.platform.reply).toHaveBeenCalledOnce();
259+
});
260+
237261
it("suppresses payloads flagged as reasoning", async () => {
238262
await expectReplySuppressed({ text: "hidden", isReasoning: true });
239263
});

‎extensions/whatsapp/src/inbound/send-api.test.ts‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import fs from "node:fs";
33
import os from "node:os";
44
import path from "node:path";
55
import type { AnyMessageContent, MiscMessageGenerationOptions, WAMessage } from "baileys";
6+
import { isChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
67
import { listMessageReceiptPlatformIds } from "openclaw/plugin-sdk/channel-outbound";
78
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
89
import { prepareWhatsAppOutboundMedia } from "../outbound-media-contract.js";
@@ -472,6 +473,104 @@ describe("createWebSendApi", () => {
472473
]);
473474
});
474475

476+
it("preserves the accepted voice receipt when its visible caption send disconnects", async () => {
477+
const captionError = new Error("connection closed while sending the voice caption");
478+
sendMessage
479+
.mockResolvedValueOnce({ key: { id: "voice-accepted-1" } })
480+
.mockRejectedValueOnce(captionError);
481+
482+
const failure = await api
483+
.sendMessage("+1555", "voice text", Buffer.from("voice"), "audio/ogg")
484+
.catch((caught: unknown) => caught);
485+
486+
expect(sendMessage).toHaveBeenCalledTimes(2);
487+
expect(isChannelPartialDeliveryError(failure)).toBe(true);
488+
if (!isChannelPartialDeliveryError(failure)) {
489+
throw new Error("accepted voice delivery did not preserve its partial receipt");
490+
}
491+
expect(failure.deliveryResult.visibleReplySent).toBe(true);
492+
expect(failure.deliveryResult.messageIds).toEqual(["voice-accepted-1"]);
493+
expect(failure.deliveryResult.receipt?.platformMessageIds).toEqual(["voice-accepted-1"]);
494+
expect(failure).toHaveProperty("cause", captionError);
495+
});
496+
497+
it("preserves the accepted voice receipt when caption mention resolution fails", async () => {
498+
const mentionError = new Error("group metadata lookup disconnected");
499+
api = createWebSendApi({
500+
sock: { sendMessage, sendPresenceUpdate },
501+
defaultAccountId: "main",
502+
resolveOutboundMentions: vi.fn().mockRejectedValue(mentionError),
503+
});
504+
sendMessage.mockResolvedValueOnce({ key: { id: "voice-accepted-2" } });
505+
506+
const failure = await api
507+
.sendMessage("+1555", "voice text", Buffer.from("voice"), "audio/ogg")
508+
.catch((caught: unknown) => caught);
509+
510+
expect(sendMessage).toHaveBeenCalledOnce();
511+
expect(isChannelPartialDeliveryError(failure)).toBe(true);
512+
if (!isChannelPartialDeliveryError(failure)) {
513+
throw new Error("accepted voice delivery was lost during mention resolution");
514+
}
515+
expect(failure.deliveryResult.messageIds).toEqual(["voice-accepted-2"]);
516+
expect(failure).toHaveProperty("cause", mentionError);
517+
});
518+
519+
it.each([
520+
{
521+
kind: "text",
522+
send: (sendApi: ReturnType<typeof createWebSendApi>) => sendApi.sendMessage("+1555", "hello"),
523+
},
524+
{
525+
kind: "poll",
526+
send: (sendApi: ReturnType<typeof createWebSendApi>) =>
527+
sendApi.sendPoll("+1555", { question: "Q?", options: ["a", "b"] }),
528+
},
529+
])("retains the accepted $kind receipt when activity recording fails", async ({ kind, send }) => {
530+
const activityError = new Error("channel activity bookkeeping disconnected");
531+
sendMessage.mockResolvedValueOnce({ key: { id: `${kind}-accepted` } });
532+
recordChannelActivity.mockImplementationOnce(() => {
533+
throw activityError;
534+
});
535+
536+
const failure = await send(api).catch((caught: unknown) => caught);
537+
538+
expect(sendMessage).toHaveBeenCalledOnce();
539+
expect(isChannelPartialDeliveryError(failure)).toBe(true);
540+
if (!isChannelPartialDeliveryError(failure)) {
541+
throw new Error("accepted provider delivery was lost during activity bookkeeping");
542+
}
543+
expect(failure.deliveryResult.messageIds).toEqual([`${kind}-accepted`]);
544+
expect(failure.deliveryResult.receipt?.platformMessageIds).toEqual([`${kind}-accepted`]);
545+
expect(failure).toHaveProperty("cause", activityError);
546+
});
547+
548+
it("retains both accepted voice receipts when later activity recording fails", async () => {
549+
const activityError = new Error("channel activity bookkeeping disconnected");
550+
sendMessage
551+
.mockResolvedValueOnce({ key: { id: "voice-accepted-3" } })
552+
.mockResolvedValueOnce({ key: { id: "caption-accepted-3" } });
553+
recordChannelActivity.mockImplementationOnce(() => {
554+
throw activityError;
555+
});
556+
557+
const failure = await api
558+
.sendMessage("+1555", "voice text", Buffer.from("voice"), "audio/ogg")
559+
.catch((caught: unknown) => caught);
560+
561+
expect(sendMessage).toHaveBeenCalledTimes(2);
562+
expect(isChannelPartialDeliveryError(failure)).toBe(true);
563+
if (!isChannelPartialDeliveryError(failure)) {
564+
throw new Error("accepted voice and caption deliveries were lost");
565+
}
566+
expect(failure.deliveryResult.messageIds).toEqual(["voice-accepted-3", "caption-accepted-3"]);
567+
expect(failure.deliveryResult.receipt?.platformMessageIds).toEqual([
568+
"voice-accepted-3",
569+
"caption-accepted-3",
570+
]);
571+
expect(failure).toHaveProperty("cause", activityError);
572+
});
573+
475574
it("supports video media and gifPlayback option", async () => {
476575
const payload = Buffer.from("vid");
477576
await api.sendMessage("+1555", "cap", payload, "video/mp4", { gifPlayback: true });

‎extensions/whatsapp/src/inbound/send-api.ts‎

Lines changed: 49 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type {
66
WAPresence,
77
} from "baileys";
88
import { recordChannelActivity } from "openclaw/plugin-sdk/channel-activity-runtime";
9+
import { createChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
910
import { resolveWhatsAppDocumentFileName } from "../document-filename.js";
1011
import { addWhatsAppImagePreviewFields } from "../image-preview.js";
1112
import { isWhatsAppNewsletterJid } from "../normalize.js";
@@ -17,6 +18,7 @@ import {
1718
} from "./outbound-mentions.js";
1819
import {
1920
combineWhatsAppSendResults,
21+
listWhatsAppSendResultMessageIds,
2022
normalizeWhatsAppSendResult,
2123
type WhatsAppSendKind,
2224
type WhatsAppSendResult,
@@ -82,15 +84,43 @@ export function createWebSendApi(params: {
8284
params.resolveOutboundMentions
8385
? await params.resolveOutboundMentions({ jid, text })
8486
: { text, mentionedJids: [] };
87+
const runAcceptedSend = async (
88+
kind: WhatsAppSendKind,
89+
accountId: string,
90+
send: (
91+
capture: (result: WAMessage | undefined, kind: WhatsAppSendKind) => void,
92+
) => Promise<void>,
93+
): Promise<WhatsAppSendResult> => {
94+
const results: WhatsAppSendResult[] = [];
95+
try {
96+
// Baileys resolves only after relay acceptance; capture that fact before any later work.
97+
await send((result, sendKind) => {
98+
results.push(normalizeWhatsAppSendResult(result, sendKind));
99+
});
100+
recordWhatsAppOutbound(accountId);
101+
return combineWhatsAppSendResults(kind, results);
102+
} catch (error) {
103+
const accepted = results.filter((result) => result.providerAccepted);
104+
if (accepted.length === 0) {
105+
throw error;
106+
}
107+
const delivered = combineWhatsAppSendResults(kind, accepted);
108+
throw createChannelPartialDeliveryError(error, {
109+
messageIds: listWhatsAppSendResultMessageIds(delivered),
110+
receipt: delivered.receipt,
111+
visibleReplySent: true,
112+
});
113+
}
114+
};
85115
const sendStructuredMessage = async (
86116
to: string,
87117
content: AnyMessageContent,
88118
kind: WhatsAppSendKind,
89119
): Promise<WhatsAppSendResult> => {
90120
const jid = resolveOutboundJid(to);
91-
const result = await params.sock.sendMessage(jid, content);
92-
recordWhatsAppOutbound(params.defaultAccountId);
93-
return normalizeWhatsAppSendResult(result, kind);
121+
return await runAcceptedSend(kind, params.defaultAccountId, async (capture) => {
122+
capture(await params.sock.sendMessage(jid, content), kind);
123+
});
94124
};
95125

96126
return {
@@ -165,24 +195,23 @@ export function createWebSendApi(params: {
165195
messageText: sendOptions?.quotedMessageKey?.messageText,
166196
media: sendOptions?.quotedMessageKey?.media,
167197
});
168-
const result = quotedOpts
169-
? await params.sock.sendMessage(jid, payload, quotedOpts)
170-
: await params.sock.sendMessage(jid, payload);
171-
const results = [normalizeWhatsAppSendResult(result, mediaBuffer ? "media" : "text")];
172-
if (shouldSendAudioText) {
173-
const resolvedAudioText = await resolveMentions(jid, text);
174-
const textPayload = addWhatsAppOutboundMentionsToContent(
175-
{ text: resolvedAudioText.text },
176-
resolvedAudioText.mentionedJids,
177-
);
178-
const textResult = quotedOpts
179-
? await params.sock.sendMessage(jid, textPayload, quotedOpts)
180-
: await params.sock.sendMessage(jid, textPayload);
181-
results.push(normalizeWhatsAppSendResult(textResult, "text"));
182-
}
198+
const kind = mediaBuffer ? "media" : "text";
183199
const accountId = sendOptions?.accountId ?? params.defaultAccountId;
184-
recordWhatsAppOutbound(accountId);
185-
return combineWhatsAppSendResults(mediaBuffer ? "media" : "text", results);
200+
return await runAcceptedSend(kind, accountId, async (capture) => {
201+
const sendPayload = async (content: AnyMessageContent) =>
202+
quotedOpts
203+
? await params.sock.sendMessage(jid, content, quotedOpts)
204+
: await params.sock.sendMessage(jid, content);
205+
capture(await sendPayload(payload), kind);
206+
if (shouldSendAudioText) {
207+
const resolvedAudioText = await resolveMentions(jid, text);
208+
const textPayload = addWhatsAppOutboundMentionsToContent(
209+
{ text: resolvedAudioText.text },
210+
resolvedAudioText.mentionedJids,
211+
);
212+
capture(await sendPayload(textPayload), "text");
213+
}
214+
});
186215
},
187216
sendPoll: async (
188217
to: string,

‎extensions/whatsapp/src/outbound-retry.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// WhatsApp tests cover outbound retry behavior.
2+
import { createChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
23
import { describe, expect, it, vi } from "vitest";
34
import { sendWhatsAppOutboundWithRetry } from "./outbound-retry.js";
45
import { withWhatsAppSocketOperationTimeout } from "./socket-timing.js";
@@ -76,6 +77,23 @@ describe("sendWhatsAppOutboundWithRetry", () => {
7677
expect(onRetry).not.toHaveBeenCalled();
7778
});
7879

80+
it("never replays a send whose disconnect error already carries an accepted receipt", async () => {
81+
const acceptedFailure = createChannelPartialDeliveryError(new Error("connection closed"), {
82+
messageIds: ["accepted-1"],
83+
visibleReplySent: true,
84+
});
85+
const send = vi.fn<() => Promise<string>>().mockRejectedValue(acceptedFailure);
86+
const onRetry = vi.fn();
87+
88+
const failure = await runWithFakeTimers(() =>
89+
sendWhatsAppOutboundWithRetry({ send, onRetry }).catch((caught: unknown) => caught),
90+
);
91+
92+
expect(failure).toBe(acceptedFailure);
93+
expect(send).toHaveBeenCalledOnce();
94+
expect(onRetry).not.toHaveBeenCalled();
95+
});
96+
7997
it("preserves attempts, delays, callback fields, and terminal error identity", async () => {
8098
const firstError = {
8199
output: {

‎extensions/whatsapp/src/outbound-retry.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// WhatsApp plugin module implements outbound retry behavior.
2+
import { isChannelPartialDeliveryError } from "openclaw/plugin-sdk/channel-inbound";
23
import { createChannelApiRetryRunner } from "openclaw/plugin-sdk/retry-runtime";
34
import { formatError } from "./session-errors.js";
45
import { isWhatsAppSocketOperationTimeoutError } from "./socket-timing.js";
@@ -17,7 +18,7 @@ class WhatsAppOutboundRetryError extends Error {
1718
function isRetryableWhatsAppOutboundError(error: unknown): boolean {
1819
// Outbound sends surface direct failures; inspecting wrappers or causes can
1920
// replay a non-idempotent send. A direct local timeout may have delivered it.
20-
if (isWhatsAppSocketOperationTimeoutError(error)) {
21+
if (isChannelPartialDeliveryError(error) || isWhatsAppSocketOperationTimeoutError(error)) {
2122
return false;
2223
}
2324
return WHATSAPP_RETRYABLE_OUTBOUND_ERROR_PATTERN.test(formatError(error));

0 commit comments

Comments
 (0)