Skip to content

Commit 652c0ea

Browse files
committed
fix(whatsapp): retain unmatched attachments across captioned replacement
Track WhatsApp acceptance per media URL so captioned replacements supersede only delivered attachments. Keep unmatched media under the original deferred finalization, preserve hook vetoes and partial-send errors, and share one ordered media-send branch.
1 parent 4bc4ad3 commit 652c0ea

5 files changed

Lines changed: 275 additions & 149 deletions

File tree

‎docs/channels/whatsapp.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,7 @@ When the linked self number is also present in `allowFrom`, self-chat safeguards
410410
- `gifPlayback: true` on video sends enables animated GIF playback
411411
- `forceDocument`/`asDocument` routes outbound images, GIFs, and videos through the Baileys document payload to avoid WhatsApp's media compression, preserving the resolved filename and MIME type
412412
- captions apply to the first media item in a multi-media reply, except PTT voice notes: the audio sends first with no caption, then the caption sends as a separate text message (WhatsApp clients do not render voice-note captions consistently)
413+
- when a later captioned reply repeats pending attachments, only attachments accepted by WhatsApp replace their pending copies; unmatched attachments remain queued for delivery
413414
- media source can be HTTP(S), `file://`, or a local path
414415

415416
</Accordion>

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

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -626,7 +626,8 @@ describe("deliverWebReply", () => {
626626
});
627627

628628
it("falls back to text-only when the first media send fails", async () => {
629-
const { msg, params } = createImageDelivery("caption", { textLimit: 20 });
629+
const onMediaAccepted = vi.fn();
630+
const { msg, params } = createImageDelivery("caption", { textLimit: 20, onMediaAccepted });
630631
vi.mocked(msg.platform.sendMedia).mockRejectedValueOnce(new Error("boom"));
631632

632633
await deliverWebReply(params);
@@ -640,6 +641,7 @@ describe("deliverWebReply", () => {
640641
"replyLogger.warn",
641642
);
642643
expect(warnContext.mediaUrl).toBe("http://example.com/img.jpg");
644+
expect(onMediaAccepted).not.toHaveBeenCalled();
643645
});
644646

645647
it("delivers the opening text chunk when the first media fails on a multi-chunk reply", async () => {
@@ -778,10 +780,11 @@ describe("deliverWebReply", () => {
778780

779781
it("preserves accepted voice receipts without false media fallback after caption rejection", async () => {
780782
hoisted.recordChannelActivity.mockClear();
781-
const { msg, params } = createDelivery({
782-
text: "caption",
783-
mediaUrl: "http://example.com/accepted-voice.ogg",
784-
});
783+
const onMediaAccepted = vi.fn();
784+
const { msg, params } = createDelivery(
785+
{ text: "caption", mediaUrl: "http://example.com/accepted-voice.ogg" },
786+
{ onMediaAccepted },
787+
);
785788
mockLoadedMedia("aud", "audio/ogg", "audio");
786789
vi.mocked(msg.platform.sendMedia).mockImplementationOnce(async () =>
787790
normalizeWhatsAppSendResult(
@@ -808,6 +811,9 @@ describe("deliverWebReply", () => {
808811
expect(msg.platform.sendMedia).toHaveBeenCalledOnce();
809812
expect(msg.platform.reply).toHaveBeenCalledOnce();
810813
expect(msg.platform.reply).toHaveBeenCalledWith("caption", undefined);
814+
expect(onMediaAccepted).toHaveBeenCalledExactlyOnceWith(
815+
"http://example.com/accepted-voice.ogg",
816+
);
811817
expect(hoisted.recordChannelActivity).toHaveBeenCalledOnce();
812818
expect(hoisted.recordChannelActivity).toHaveBeenCalledWith({
813819
channel: "whatsapp",
@@ -833,10 +839,11 @@ describe("deliverWebReply", () => {
833839
},
834840
defaultAccountId: "work",
835841
});
836-
const { msg, params } = createDelivery({
837-
text: "caption",
838-
mediaUrl: "http://example.com/nested-voice.ogg",
839-
});
842+
const onMediaAccepted = vi.fn();
843+
const { msg, params } = createDelivery(
844+
{ text: "caption", mediaUrl: "http://example.com/nested-voice.ogg" },
845+
{ onMediaAccepted },
846+
);
840847
mockLoadedMedia("aud", "audio/ogg", "audio");
841848
vi.mocked(msg.platform.sendMedia).mockImplementationOnce(async () =>
842849
sendApi.sendMessage("+1555", "", Buffer.from("aud"), "audio/ogg"),
@@ -854,6 +861,7 @@ describe("deliverWebReply", () => {
854861
expect(msg.platform.sendMedia).toHaveBeenCalledOnce();
855862
expect(msg.platform.reply).not.toHaveBeenCalled();
856863
expect(replyLogger.warn).not.toHaveBeenCalled();
864+
expect(onMediaAccepted).toHaveBeenCalledExactlyOnceWith("http://example.com/nested-voice.ogg");
857865
expect(hoisted.recordChannelActivity).toHaveBeenCalledExactlyOnceWith({
858866
channel: "whatsapp",
859867
accountId: "work",

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

Lines changed: 49 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@ type WhatsAppReplyDeliveryParams = {
136136
connectionId?: string;
137137
skipLog?: boolean;
138138
tableMode?: MarkdownTableMode;
139+
onMediaAccepted?: (mediaUrl: string) => void;
139140
};
140141

141142
export async function deliverWebReply(
@@ -153,6 +154,11 @@ async function deliverWebReplyInActivityScope(
153154
const isGroupConversation = transport.conversationKind === "group";
154155
const replyStarted = Date.now();
155156
const sendResults: WhatsAppSendResult[] = [];
157+
const acceptedMediaUrls = new Set<string>();
158+
const recordMediaAccepted = (mediaUrl: string) => {
159+
acceptedMediaUrls.add(mediaUrl);
160+
params.onMediaAccepted?.(mediaUrl);
161+
};
156162
const finishDelivery = (): WhatsAppReplyDeliveryResult => {
157163
const receipt = createWhatsAppReplyDeliveryReceipt(sendResults);
158164
return {
@@ -161,22 +167,29 @@ async function deliverWebReplyInActivityScope(
161167
providerAccepted: sendResults.some((result) => result.providerAccepted),
162168
};
163169
};
164-
const preserveAcceptedDeliveryError = (error: unknown, kind?: WhatsAppSendKind) => {
170+
const preserveAcceptedDeliveryError = (
171+
error: unknown,
172+
kind?: WhatsAppSendKind,
173+
mediaUrl?: string,
174+
) => {
165175
const sendKind = kind ?? sendResults[0]?.kind ?? "text";
166176
if (isChannelPartialDeliveryError(error)) {
167-
rememberWhatsAppPartialSend({
177+
const accepted = rememberWhatsAppPartialSend({
168178
error,
169179
kind: sendKind,
170180
results: sendResults,
171181
});
182+
if (accepted && mediaUrl) {
183+
recordMediaAccepted(mediaUrl);
184+
}
172185
}
173186
return mergeWhatsAppAcceptedSendError({
174187
error,
175188
kind: sendKind,
176189
results: sendResults,
177190
});
178191
};
179-
const rememberSendResult = (result: WhatsAppSendResult | undefined) => {
192+
const rememberSendResult = (result: WhatsAppSendResult | undefined, mediaUrl?: string) => {
180193
if (!result) {
181194
return;
182195
}
@@ -191,6 +204,11 @@ async function deliverWebReplyInActivityScope(
191204
throw preserveAcceptedDeliveryError(error, result.kind);
192205
}
193206
throw error;
207+
} finally {
208+
// The owner appends the validated result before activity bookkeeping can throw.
209+
if (mediaUrl && sendResults.includes(result)) {
210+
recordMediaAccepted(mediaUrl);
211+
}
194212
}
195213
};
196214
if (isReasoningReplyPayload(replyResult)) {
@@ -233,7 +251,12 @@ async function deliverWebReplyInActivityScope(
233251
});
234252
};
235253

236-
const sendWithRetry = async <T>(fn: () => Promise<T>, label: string, kind: WhatsAppSendKind) => {
254+
const sendWithRetry = async <T>(
255+
fn: () => Promise<T>,
256+
label: string,
257+
kind: WhatsAppSendKind,
258+
mediaUrl?: string,
259+
) => {
237260
try {
238261
return await sendWhatsAppOutboundWithRetry({
239262
send: fn,
@@ -248,7 +271,7 @@ async function deliverWebReplyInActivityScope(
248271
isChannelPartialDeliveryError(error) ||
249272
sendResults.some((result) => result.providerAccepted)
250273
) {
251-
throw preserveAcceptedDeliveryError(error, kind);
274+
throw preserveAcceptedDeliveryError(error, kind, mediaUrl);
252275
}
253276
throw error;
254277
}
@@ -292,14 +315,10 @@ async function deliverWebReplyInActivityScope(
292315

293316
// Media (with optional caption on first item)
294317
const leadingCaption = remainingText.shift() || "";
295-
let acceptedIdsBeforeCurrentMedia = new Set<string>();
296318
await sendMediaWithLeadingCaption({
297319
mediaUrls: mediaList,
298320
caption: leadingCaption,
299321
send: async ({ mediaUrl, caption }) => {
300-
acceptedIdsBeforeCurrentMedia = new Set(
301-
sendResults.flatMap(listWhatsAppSendResultMessageIds),
302-
);
303322
const media = await prepareWhatsAppOutboundMedia(
304323
await loadWebMedia(mediaUrl, {
305324
maxBytes: maxMediaBytes,
@@ -313,79 +332,27 @@ async function deliverWebReplyInActivityScope(
313332
);
314333
logVerbose(`Web auto-reply media source: ${mediaUrl} (kind ${media.kind})`);
315334
}
316-
if (media.kind === "image") {
317-
const quote = getQuote();
318-
rememberSendResult(
319-
await sendWithRetry(
320-
() =>
321-
transport.sendMedia(
322-
{
323-
image: media.buffer,
324-
caption,
325-
mimetype: media.mimetype,
326-
},
327-
quote,
328-
),
329-
"media:image",
330-
"media",
331-
),
332-
);
333-
} else if (media.kind === "audio") {
334-
const quote = getQuote();
335-
rememberSendResult(
336-
await sendWithRetry(
337-
() =>
338-
transport.sendMedia(
339-
{
340-
audio: media.buffer,
341-
ptt: true,
342-
mimetype: media.mimetype,
343-
},
344-
quote,
345-
),
346-
"media:audio",
347-
"media",
348-
),
349-
);
350-
if (caption) {
351-
rememberSendResult(
352-
await sendWithRetry(() => transport.reply(caption, quote), "media:audio-text", "text"),
353-
);
354-
}
355-
} else if (media.kind === "video") {
356-
const quote = getQuote();
357-
rememberSendResult(
358-
await sendWithRetry(
359-
() =>
360-
transport.sendMedia(
361-
{
362-
video: media.buffer,
363-
caption,
364-
mimetype: media.mimetype,
365-
},
366-
quote,
367-
),
368-
"media:video",
369-
"media",
370-
),
371-
);
372-
} else {
373-
const quote = getQuote();
335+
const quote = getQuote();
336+
const mediaContent =
337+
media.kind === "image"
338+
? { image: media.buffer, caption }
339+
: media.kind === "audio"
340+
? { audio: media.buffer, ptt: true }
341+
: media.kind === "video"
342+
? { video: media.buffer, caption }
343+
: { document: media.buffer, fileName: media.fileName, caption };
344+
rememberSendResult(
345+
await sendWithRetry(
346+
() => transport.sendMedia({ ...mediaContent, mimetype: media.mimetype }, quote),
347+
`media:${media.kind}`,
348+
"media",
349+
mediaUrl,
350+
),
351+
mediaUrl,
352+
);
353+
if (media.kind === "audio" && caption) {
374354
rememberSendResult(
375-
await sendWithRetry(
376-
() =>
377-
transport.sendMedia(
378-
{
379-
document: media.buffer,
380-
fileName: media.fileName,
381-
caption,
382-
mimetype: media.mimetype,
383-
},
384-
quote,
385-
),
386-
"media:document",
387-
"media",
388-
),
355+
await sendWithRetry(() => transport.reply(caption, quote), "media:audio-text", "text"),
389356
);
390357
}
391358
whatsappOutboundLog.info(
@@ -407,12 +374,7 @@ async function deliverWebReplyInActivityScope(
407374
);
408375
},
409376
onError: async ({ error, mediaUrl, caption, isFirst }) => {
410-
const currentMediaWasAccepted = sendResults.some((result) =>
411-
listWhatsAppSendResultMessageIds(result).some(
412-
(messageId) => !acceptedIdsBeforeCurrentMedia.has(messageId),
413-
),
414-
);
415-
if (currentMediaWasAccepted) {
377+
if (acceptedMediaUrls.has(mediaUrl)) {
416378
// Earlier accepted uploads do not make a genuinely rejected trailing upload successful.
417379
throw preserveAcceptedDeliveryError(error);
418380
}

0 commit comments

Comments
 (0)