Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): preserve ephemeral inbound content + harden media/QR handling (#542)

Yudhi Armyndharis800b6cf28792
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 25f23fb04..a08bf24ff 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- **Inbound @mentions are surfaced on the Baileys engine.** An incoming message that tags participants now exposes the tagged WIDs as `mentionedIds` (normalized to the neutral `@c.us` convention), reaching parity with the whatsapp-web.js engine and feeding the existing `mentions` webhook filter and command-targeting. (#542)
+
+### Fixed
+
+- **Disappearing-messages (ephemeral) inbound messages no longer lose their content on Baileys.** A message in a chat with disappearing messages enabled arrives wrapped, so its text, media, location, and resolved type were silently dropped (the message surfaced empty and typed `unknown`). The adapter now reads the unwrapped inner content, so the body, voice/media/location detail, and correct type are preserved. (#542)
+- **Captioned documents surface their caption on Baileys.** A `documentWithCaptionMessage` now contributes its caption to the message body instead of an empty string. (#542)
+- **Inbound media downloads on whatsapp-web.js stay within the configured concurrency limit.** When a download exceeded its wall-clock deadline, its slot was freed while the un-abortable download kept running, letting a slow sender push the number of simultaneous in-flight downloads above `INBOUND_MEDIA_CONCURRENCY`. The slot is now held until the real download settles, bounding peak memory. (#542)
+- **A stale QR code can no longer be emitted while a whatsapp-web.js session is shutting down.** A QR event buffered by the browser page could flush during teardown and flip a disconnecting session back to `QR_READY`; the handler now ignores QR events once teardown has begun. (#542)
+- **Bulk send persists the correct filename for every media type.** A bulk image/video/audio message now records its own `filename` in the stored message metadata instead of only documents'. (#542)
+
## [0.7.14] - 2026-06-30
### Added
diff --git a/src/engine/adapters/baileys-message-mapper.spec.ts b/src/engine/adapters/baileys-message-mapper.spec.ts
index 578fff837..3143c49e9 100644
--- a/src/engine/adapters/baileys-message-mapper.spec.ts
+++ b/src/engine/adapters/baileys-message-mapper.spec.ts
@@ -19,6 +19,9 @@ describe('mapBaileysMessageType (baileys content-type -> neutral MessageType)',
['contactMessage', false, 'contact'],
[undefined, false, 'unknown'],
['pollCreationMessage', false, 'unknown'],
+ // Regression trap: calls arrive via the `call` socket event, never as a message content type,
+ // so any call-ish token must stay 'unknown' (no accidental mapping).
+ ['callLogMessage', false, 'unknown'],
])('maps %s (ptt=%s) -> %s', (raw, ptt, expected) => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
expect(mapBaileysMessageType(raw as string | undefined, ptt as boolean)).toBe(expected);
@@ -140,4 +143,18 @@ describe('buildIncomingMessageFromBaileys', () => {
const r = buildIncomingMessageFromBaileys({ ...base, ephemeralDuration: 0 });
expect(r.ephemeralDuration).toBeUndefined();
});
+
+ it('maps mentionedIds, normalizing each JID, when present', () => {
+ const normalize = (jid: string) => jid.replace('@s.whatsapp.net', '@c.us');
+ const r = buildIncomingMessageFromBaileys(
+ { ...base, mentionedJids: ['[email protected]', '[email protected]'] },
+ normalize,
+ );
+ expect(r.mentionedIds).toEqual(['[email protected]', '[email protected]']);
+ });
+
+ it('omits mentionedIds when absent or empty', () => {
+ expect(buildIncomingMessageFromBaileys(base).mentionedIds).toBeUndefined();
+ expect(buildIncomingMessageFromBaileys({ ...base, mentionedJids: [] }).mentionedIds).toBeUndefined();
+ });
});
diff --git a/src/engine/adapters/baileys-message-mapper.ts b/src/engine/adapters/baileys-message-mapper.ts
index dd11d5472..e830d02ce 100644
--- a/src/engine/adapters/baileys-message-mapper.ts
+++ b/src/engine/adapters/baileys-message-mapper.ts
@@ -4,6 +4,11 @@ import { DeliveryStatus, IncomingMessage, MessageType } from '../interfaces/what
* Map a Baileys message content-type token (from `getContentType`) to the engine-neutral
* {@link MessageType}. `audioMessage` splits on the `ptt` flag into `voice` vs `audio`,
* mirroring the wwjs `ptt -> voice` mapping. Anything unmapped becomes `unknown`.
+ *
+ * Note: Baileys surfaces phone calls through the dedicated `call` socket event (a `WACallEvent`),
+ * never as a message content type returned by `getContentType`, so `call`-typed messages are
+ * intentionally not produced on this engine — unlike the wwjs adapter, which sources call detail
+ * from the gated `getChatHistory` path.
*/
export function mapBaileysMessageType(contentType: string | undefined, isPtt = false): MessageType {
switch (contentType) {
@@ -85,6 +90,8 @@ export interface BaileysIncomingFields {
quotedMessage?: IncomingMessage['quotedMessage'];
/** Ephemeral/disappearing-messages timer from `contextInfo.expiration` on the Baileys message. */
ephemeralDuration?: number;
+ /** @mentioned engine JIDs from `contextInfo.mentionedJid`; normalized and surfaced as `mentionedIds`. */
+ mentionedJids?: string[];
}
/**
@@ -150,5 +157,11 @@ export function buildIncomingMessageFromBaileys(
incoming.ephemeralDuration = fields.ephemeralDuration;
}
+ // @mentioned WIDs, normalized to the neutral convention — parity with the wwjs adapter
+ // (message-mapper.ts:90), consumed by command targeting and the `mentions` webhook filter.
+ if (fields.mentionedJids && fields.mentionedJids.length > 0) {
+ incoming.mentionedIds = fields.mentionedJids.map(normalizeJid);
+ }
+
return incoming;
}
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 37947eecc..63984ad36 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -660,6 +660,50 @@ describe('BaileysAdapter inbound fan-out', () => {
expect(msg).toMatchObject({ id: 'IN1', body: 'hi there', type: 'text', fromMe: false });
});
+ it('surfaces inbound @mentions as neutral mentionedIds (contextInfo.mentionedJid)', async () => {
+ const onMessage = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize({ onMessage });
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [
+ {
+ key: { remoteJid: '[email protected]', participant: '[email protected]', fromMe: false, id: 'IN_MENTION' },
+ message: {
+ extendedTextMessage: { text: '@628111 hi', contextInfo: { mentionedJid: ['[email protected]'] } },
+ },
+ messageTimestamp: 1700000002,
+ },
+ ],
+ });
+ await new Promise(r => setImmediate(r));
+ expect(onMessage).toHaveBeenCalledTimes(1);
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ const msg = onMessage.mock.calls[0][0] as { mentionedIds?: string[] };
+ expect(msg.mentionedIds).toEqual(['[email protected]']);
+ });
+
+ it('omits mentionedIds on an inbound message without @mentions', async () => {
+ const onMessage = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize({ onMessage });
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [
+ {
+ key: { remoteJid: '[email protected]', fromMe: false, id: 'IN_NOMENTION' },
+ message: { conversation: 'plain text' },
+ messageTimestamp: 1700000003,
+ },
+ ],
+ });
+ await new Promise(r => setImmediate(r));
+ expect(onMessage).toHaveBeenCalledTimes(1);
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ const msg = onMessage.mock.calls[0][0] as { mentionedIds?: string[] };
+ expect(msg.mentionedIds).toBeUndefined();
+ });
+
it('canonicalizes an inbound message JID from @s.whatsapp.net to @c.us', async () => {
const onMessage = jest.fn();
const adapter = newAdapter();
@@ -988,9 +1032,12 @@ describe('BaileysAdapter inbound fan-out', () => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const msg = onMessage.mock.calls[0][0] as {
type: string;
+ body: string;
media: { mimetype: string; filename?: string; data: string };
};
expect(msg.type).toBe('document');
+ // The caption rides under the unwrapped documentMessage; reading the raw wrapper would lose it.
+ expect(msg.body).toBe('Q1 report');
expect(msg.media.mimetype).toBe('application/pdf');
expect(msg.media.filename).toBe('report.pdf');
expect(msg.media.data).toBe(docBuf.toString('base64'));
@@ -1002,10 +1049,16 @@ describe('BaileysAdapter inbound fan-out', () => {
getContentType: jest.Mock;
normalizeMessageContent: jest.Mock;
};
- baileys.getContentType.mockReturnValue('extendedTextMessage');
+ // Mirror real Baileys: getContentType returns the OUTER key for a wrapped message ('ephemeralMessage')
+ // and the inner key once normalized ('extendedTextMessage'). This forces the test through the
+ // production normalize-then-getContentType path instead of a mock shortcut — if the adapter forgot to
+ // normalize before reading the type/body, the assertions below would fail.
+ baileys.getContentType.mockImplementation((m?: { ephemeralMessage?: unknown }) =>
+ m?.ephemeralMessage ? 'ephemeralMessage' : 'extendedTextMessage',
+ );
// A live disappearing message arrives wrapped in `ephemeralMessage`; normalizeMessageContent unwraps
- // it to the inner content carrying the timer on `contextInfo.expiration`. Reading the raw (wrapped)
- // content would miss it — the exact case this guards.
+ // it to the inner content carrying the body and the timer on `contextInfo.expiration`. Reading the raw
+ // (wrapped) content would miss both — the exact case this guards.
baileys.normalizeMessageContent.mockReturnValue({
extendedTextMessage: { text: 'vanishes', contextInfo: { expiration: 86400 } },
});
@@ -1030,10 +1083,57 @@ describe('BaileysAdapter inbound fan-out', () => {
await new Promise(r => setImmediate(r));
expect(onMessage).toHaveBeenCalledTimes(1);
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
- const msg = onMessage.mock.calls[0][0] as { ephemeralDuration?: number };
+ const msg = onMessage.mock.calls[0][0] as { type: string; body: string; ephemeralDuration?: number };
+ // The body and type are derived from the normalized inner content, not the ephemeralMessage wrapper.
+ expect(msg.type).toBe('text');
+ expect(msg.body).toBe('vanishes');
expect(msg.ephemeralDuration).toBe(86400);
});
+ it('wrapped voice note in a disappearing chat maps to type voice', async () => {
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
+ const baileys = jest.requireMock('@whiskeysockets/baileys') as {
+ getContentType: jest.Mock;
+ normalizeMessageContent: jest.Mock;
+ };
+ baileys.getContentType.mockImplementation((m?: { ephemeralMessage?: unknown }) =>
+ m?.ephemeralMessage ? 'ephemeralMessage' : 'audioMessage',
+ );
+ baileys.normalizeMessageContent.mockReturnValue({
+ audioMessage: { ptt: true, mimetype: 'audio/ogg; codecs=opus' },
+ });
+
+ const prev = process.env.MEDIA_DOWNLOAD_ENABLED;
+ process.env.MEDIA_DOWNLOAD_ENABLED = 'false'; // omitted-marker path: no download mock needed
+ try {
+ const onMessage = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize({ onMessage });
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [
+ {
+ key: { remoteJid: '[email protected]', fromMe: false, id: 'EPHVOICE1' },
+ message: {
+ ephemeralMessage: {
+ message: { audioMessage: { ptt: true, mimetype: 'audio/ogg; codecs=opus' } },
+ },
+ },
+ messageTimestamp: 1700000041,
+ },
+ ],
+ });
+ await new Promise(r => setImmediate(r));
+ expect(onMessage).toHaveBeenCalledTimes(1);
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ const msg = onMessage.mock.calls[0][0] as { type: string };
+ expect(msg.type).toBe('voice');
+ } finally {
+ if (prev === undefined) delete process.env.MEDIA_DOWNLOAD_ENABLED;
+ else process.env.MEDIA_DOWNLOAD_ENABLED = prev;
+ }
+ });
+
it('inbound location: populates the location field with coordinates', async () => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const baileys = jest.requireMock('@whiskeysockets/baileys') as { getContentType: jest.Mock };
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index fbdea61ba..16ea84e43 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -189,7 +189,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
}
// An internal reconnect (transient drop) overwrites this.sock WITHOUT going through
- // disconnect/logout/destroy, so the previous socket's WebSocket and the 9 ev listeners we
+ // disconnect/logout/destroy, so the previous socket's WebSocket and the 10 ev listeners we
// register below would leak on every reconnect. Tear the prior socket down first. Detach OUR
// connection.update listener BEFORE end(): Baileys' own end() synchronously emits a synthetic
// connection.update {connection:'close'}, which — if still wired — would re-enter
@@ -206,6 +206,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
previous.ev.removeAllListeners('chats.upsert');
previous.ev.removeAllListeners('chats.update');
previous.ev.removeAllListeners('messaging-history.set');
+ previous.ev.removeAllListeners('chats.phoneNumberShare');
previous.end(undefined);
} catch {
// end() may already have run from Baileys' own close handler — a safe no-op.
@@ -930,7 +931,13 @@ export class BaileysAdapter implements IWhatsAppEngine {
// sender resolves to its phone in this message and for later contact lookups (#362). The pairs
// also write through to the persistent lid->phone table via addLidMappings.
this.sessionStore.recordKeyLidMappings(msg.key);
- const contentType = b.getContentType(msg.message ?? undefined);
+ // A live disappearing message (also viewOnce / documentWithCaption / edited) arrives wrapped, so the
+ // raw `getContentType` returns the OUTER wrapper key (e.g. 'ephemeralMessage') and downstream type/
+ // body/media/location detection would miss the real inner content. Normalize ONCE so the true inner
+ // type drives routing here AND mapMessage. normalizeMessageContent leaves protocolMessage and
+ // reactionMessage untouched, so the early-return branches below still match.
+ const normalizedRoot = b.normalizeMessageContent(msg.message ?? undefined) ?? msg.message ?? undefined;
+ const contentType = b.getContentType(normalizedRoot);
// --- protocolMessage REVOKE: don't emit onMessage ---
if (contentType === 'protocolMessage') {
@@ -1044,14 +1051,18 @@ export class BaileysAdapter implements IWhatsAppEngine {
private async mapMessage(msg: WAMessage, contentType: string | undefined): Promise<IncomingMessage> {
const b = await this.loadLib();
const content = msg.message ?? {};
+ // Read body/isPtt off the NORMALIZED content: a disappearing message (ephemeralMessage), a captioned
+ // document (documentWithCaptionMessage) and viewOnce/edited wrappers nest the real text/caption under
+ // an inner message, so the raw wrapper exposes none at top level. Identity no-op when unwrapped.
+ const normalized = b.normalizeMessageContent(content) ?? content;
// Body: text first, then media caption as fallback.
const body =
- content.conversation ??
- content.extendedTextMessage?.text ??
- content.imageMessage?.caption ??
- content.videoMessage?.caption ??
- content.documentMessage?.caption ??
+ normalized.conversation ??
+ normalized.extendedTextMessage?.text ??
+ normalized.imageMessage?.caption ??
+ normalized.videoMessage?.caption ??
+ normalized.documentMessage?.caption ??
'';
// --- location ---
@@ -1172,6 +1183,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
stanzaId?: string | null;
quotedMessage?: Record<string, unknown> | null;
expiration?: number | null;
+ mentionedJid?: string[] | null;
};
}
| undefined
@@ -1202,7 +1214,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
participant: msg.key.participant ?? undefined,
body,
contentType,
- isPtt: content.audioMessage?.ptt === true,
+ isPtt: normalized.audioMessage?.ptt === true,
timestamp: this.toUnixSeconds(msg.messageTimestamp),
pushName: msg.pushName ?? undefined,
selfJid: this.normalizedSelfJid(),
@@ -1210,6 +1222,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
location,
quotedMessage,
ephemeralDuration: contextInfo?.expiration ?? undefined,
+ mentionedJids: contextInfo?.mentionedJid ?? undefined,
},
jid => this.sessionStore.toNeutralJid(jid),
);
diff --git a/src/engine/adapters/inbound-media-cap.ts b/src/engine/adapters/inbound-media-cap.ts
index 962aab05e..40a6ab040 100644
--- a/src/engine/adapters/inbound-media-cap.ts
+++ b/src/engine/adapters/inbound-media-cap.ts
@@ -34,10 +34,12 @@ export function inboundMediaTimeoutMs(): number {
/**
* Bound an inbound media download by a wall-clock deadline. The byte cap and concurrency limiter don't
* bound TIME: a remote sender can trickle bytes slowly (never tripping the cap) and hold a concurrency
- * slot indefinitely — a slow-loris on the inbound pipeline. On timeout `onTimeout` runs (e.g. destroy
- * the stream so the abandoned download can't keep allocating) and the result resolves `null`, the same
- * "no usable media" sentinel the byte-cap abort returns. A late rejection from the abandoned download is
- * swallowed so it can't surface as an unhandled rejection after the race has already settled.
+ * slot indefinitely — a slow-loris on the inbound pipeline. On timeout `onTimeout` runs — a best-effort
+ * hook to abort the source where it's abortable (e.g. destroy a Baileys stream) — and the result resolves
+ * `null`, the same "no usable media" sentinel the byte-cap abort returns. A non-abortable source (the wwjs
+ * `downloadMedia()`) can't be stopped, so that caller must instead hold its concurrency slot until the real
+ * download settles. A late rejection from the abandoned download is swallowed so it can't surface as an
+ * unhandled rejection after the race has already settled.
*/
export function withInboundDownloadTimeout<T>(
promise: Promise<T>,
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 7e0b9dc5e..81fdb0678 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -12,6 +12,7 @@ import {
} from './whatsapp-web-js.adapter';
import { getEffectiveWebVersionInfo, resolveWebVersionPin, __resetWebVersionCache } from '../wa-web-version';
import * as fs from 'fs';
+import * as qrcode from 'qrcode';
import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';
import { EngineStatus } from '../interfaces/whatsapp-engine.interface';
@@ -25,6 +26,14 @@ jest.mock('undici', () => {
return { __esModule: true, ...actual, fetch: jest.fn() };
});
+// Deterministic QR encode: the real qrcode.toDataURL is an unmocked multi-ms macrotask, so timing-based
+// waits are flaky. Mocking it to resolve on the microtask queue lets the 'qr' handler settle within a
+// couple of awaited flushes. No existing wwebjs spec emits 'qr', so only the QR tests are affected.
+jest.mock('qrcode', () => ({
+ __esModule: true,
+ toDataURL: jest.fn(() => Promise.resolve('data:image/png;base64,FAKEQR')),
+}));
+
describe('wwebjsAckToDeliveryStatus (engine ack-int -> neutral DeliveryStatus boundary, #265)', () => {
// Regression-locks the integer boundary the decoupling moved behaviour into, incl. the
// PLAYED(4) -> 'read' collapse that the old ackToMessageStatus(4) -> READ test used to cover.
@@ -546,6 +555,51 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {
expect(onReady).not.toHaveBeenCalled();
});
+ // A 'qr' IPC buffered by a wedged page can flush during the awaited client.destroy() (teardown sets
+ // tearingDown + DISCONNECTED first), and must not resurrect the adapter to QR_READY / re-emit a stale QR.
+ // The guard returns BEFORE the qrcode encode, so spying on qrcode.toDataURL gives a deterministic check
+ // (no timing dependence on the real ~ms encode): guarded => never called; unguarded => called (regression).
+ it('ignores a qr event fired during teardown (status stays disconnected, no stale QR emitted)', async () => {
+ (qrcode.toDataURL as unknown as jest.Mock).mockClear();
+ const adapter = newAdapter();
+ const teardownWait = deferredVoid();
+ const { client } = attachFakeClient(adapter);
+ const onQRCode = jest.fn();
+ (adapter as unknown as { callbacks: { onQRCode: jest.Mock } }).callbacks.onQRCode = onQRCode;
+ client.destroy = jest.fn().mockReturnValue(teardownWait.promise);
+
+ const teardown = adapter.disconnect();
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+
+ client.emit('qr', '2@abc'); // buffered QR flushed mid-destroy — must NOT flip to QR_READY
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(qrcode.toDataURL as unknown as jest.Mock).not.toHaveBeenCalled(); // guard short-circuits before the encode
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ expect(onQRCode).not.toHaveBeenCalled();
+
+ teardownWait.resolve();
+ await teardown;
+ expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);
+ expect(onQRCode).not.toHaveBeenCalled();
+ });
+
+ // Guards against over-suppression: the legitimate first QR still reaches QR_READY + onQRCode. Await the
+ // real completion signal (the onQRCode callback) rather than guessing microtask-flush counts.
+ it('emits the normal first qr (status becomes qr_ready and onQRCode is called)', async () => {
+ (qrcode.toDataURL as unknown as jest.Mock).mockClear();
+ const adapter = newAdapter();
+ const { client } = attachFakeClient(adapter);
+ const qrDone = deferredVoid();
+ const onQRCode = jest.fn(() => qrDone.resolve());
+ (adapter as unknown as { callbacks: { onQRCode: jest.Mock } }).callbacks.onQRCode = onQRCode;
+
+ client.emit('qr', '2@abc');
+ await qrDone.promise;
+ expect(adapter.getStatus()).toBe(EngineStatus.QR_READY);
+ expect(onQRCode).toHaveBeenCalledTimes(1);
+ });
+
// A wedged page can make getState() hang (the exact #251/#273 condition). The probe must keep its
// own cadence (a hung probe can't stall the loop) and still honor the 90s give-up deadline.
it('keeps probing and self-heals (clears auth + disconnects) when getState hangs past the deadline', async () => {
@@ -942,3 +996,119 @@ describe('extractWwebjsCall (call_log → { video, missed }, salvaged from #494)
});
});
});
+
+describe('WhatsAppWebJsAdapter inbound media concurrency (slot held until the real download settles)', () => {
+ const ENV_KEYS = [
+ 'INBOUND_MEDIA_CONCURRENCY',
+ 'MEDIA_DOWNLOAD_TIMEOUT_MS',
+ 'MEDIA_DOWNLOAD_MAX_BYTES',
+ 'MEDIA_DOWNLOAD_ENABLED',
+ ];
+ let saved: Record<string, string | undefined> = {};
+ beforeEach(() => {
+ saved = {};
+ ENV_KEYS.forEach(k => (saved[k] = process.env[k]));
+ });
+ afterEach(() => {
+ ENV_KEYS.forEach(k => {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ });
+ jest.useRealTimers();
+ });
+
+ type Deferred<T> = { promise: Promise<T>; resolve: (v: T) => void; reject: (e: unknown) => void };
+ const defer = <T>(): Deferred<T> => {
+ let resolve: (v: T) => void = () => undefined;
+ let reject: (e: unknown) => void = () => undefined;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+ };
+
+ const newAdapter = (): WhatsAppWebJsAdapter =>
+ new WhatsAppWebJsAdapter({ sessionId: 'media-1', sessionDataPath: './data/sessions', puppeteer: {} });
+
+ it('does not start a second download until the first real download settles, even after the caller times out', async () => {
+ process.env.INBOUND_MEDIA_CONCURRENCY = '1';
+ process.env.MEDIA_DOWNLOAD_TIMEOUT_MS = '20';
+ process.env.MEDIA_DOWNLOAD_MAX_BYTES = String(10 * 1024 * 1024);
+ process.env.MEDIA_DOWNLOAD_ENABLED = 'true';
+ jest.useFakeTimers();
+
+ const adapter = newAdapter();
+ let inFlight = 0;
+ let maxInFlight = 0;
+ const downloads: Deferred<{ mimetype: string; data: string }>[] = [];
+ const makeMsg = (id: string): unknown => ({
+ id: { _serialized: id },
+ _data: { size: 100, mimetype: 'image/png' },
+ downloadMedia: jest.fn(() => {
+ inFlight++;
+ maxInFlight = Math.max(maxInFlight, inFlight);
+ const d = defer<{ mimetype: string; data: string }>();
+ downloads.push(d);
+ return d.promise.finally(() => {
+ inFlight--;
+ });
+ }),
+ });
+ const cap = (m: unknown): Promise<unknown> =>
+ (adapter as unknown as { capInboundMediaFor: (msg: unknown) => Promise<unknown> }).capInboundMediaFor(m);
+
+ const r1 = cap(makeMsg('m1')); // download1 starts synchronously (slot 1)
+ const r2 = cap(makeMsg('m2')); // parks on the limiter; download2 must NOT start
+ expect(downloads.length).toBe(1);
+
+ // Time out BOTH callers' wall-clock deadline while the real download is still pending. With the old
+ // coupling this freed the slot and admitted download2 (inFlight 2); the fix holds the slot.
+ await jest.advanceTimersByTimeAsync(25);
+ expect(await r1).toBeUndefined(); // caller unblocked on the timeout race
+ expect(downloads.length).toBe(1); // download2 still not started — slot held by the pending real download1
+ expect(maxInFlight).toBe(1);
+
+ // The real download1 finally settles -> the slot transfers and download2 may now start.
+ downloads[0].resolve({ mimetype: 'image/png', data: Buffer.from('a').toString('base64') });
+ await jest.advanceTimersByTimeAsync(0);
+ expect(downloads.length).toBe(2);
+ expect(maxInFlight).toBe(1);
+
+ // Settle the rest so nothing dangles.
+ await jest.advanceTimersByTimeAsync(25);
+ expect(await r2).toBeUndefined();
+ downloads[1].resolve({ mimetype: 'image/png', data: Buffer.from('b').toString('base64') });
+ await jest.advanceTimersByTimeAsync(0);
+ expect(maxInFlight).toBe(1);
+ });
+
+ it('propagates a rejecting download to the caller and releases the slot for the next download', async () => {
+ process.env.INBOUND_MEDIA_CONCURRENCY = '1';
+ process.env.MEDIA_DOWNLOAD_TIMEOUT_MS = '10000'; // long: we want the reject, not the timeout
+ process.env.MEDIA_DOWNLOAD_MAX_BYTES = String(10 * 1024 * 1024);
+ process.env.MEDIA_DOWNLOAD_ENABLED = 'true';
+ jest.useFakeTimers();
+
+ const adapter = newAdapter();
+ const calls: string[] = [];
+ const makeMsg = (id: string, behavior: 'reject' | 'resolve'): unknown => ({
+ id: { _serialized: id },
+ _data: { size: 100, mimetype: 'image/png' },
+ downloadMedia: jest.fn(() => {
+ calls.push(id);
+ return behavior === 'reject'
+ ? Promise.reject(new Error('download blew up'))
+ : Promise.resolve({ mimetype: 'image/png', data: Buffer.from('ok').toString('base64') });
+ }),
+ });
+ const cap = (m: unknown): Promise<unknown> =>
+ (adapter as unknown as { capInboundMediaFor: (msg: unknown) => Promise<unknown> }).capInboundMediaFor(m);
+
+ await expect(cap(makeMsg('bad', 'reject'))).rejects.toThrow('download blew up');
+ // Slot must have been released despite the rejection — the next download proceeds and resolves.
+ const media = (await cap(makeMsg('good', 'resolve'))) as { mimetype: string; data: string };
+ expect(media.data).toBe(Buffer.from('ok').toString('base64'));
+ expect(calls).toEqual(['bad', 'good']);
+ });
+});
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 7e158a76a..d1b7a1eb1 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -240,19 +240,38 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
sizeBytes: declared,
};
}
- // Bound the download by a wall-clock deadline: msg.downloadMedia() can't be aborted, so a
- // trickling sender would otherwise pin a concurrency slot indefinitely. On timeout the slot is
- // released (the run task resolves null) and the message is emitted without media.
- const media = await this.inboundLimiter.run(() =>
- withInboundDownloadTimeout(msg.downloadMedia(), inboundMediaTimeoutMs(), () =>
- this.logger.warn(
- 'Inbound media download timed out (MEDIA_DOWNLOAD_TIMEOUT_MS); emitting message without media',
- {
- msgId: msg.id._serialized,
- },
+ // msg.downloadMedia() can't be aborted, so freeing the slot the moment the wall-clock deadline fires
+ // would admit a fresh download while the abandoned one is still materialising in heap — letting the
+ // number of in-flight downloads exceed inboundMediaConcurrency(). Instead, HOLD the slot until the real
+ // download settles; the caller still unblocks on the timeout race and emits the message without media.
+ // boundedReady adopts the timeout-bounded race (a Promise resolving a Promise flattens), so awaiting it
+ // unblocks the caller once the task is admitted AND the deadline-or-download settles — yielding the
+ // media or null on timeout.
+ let resolveBounded: (value: MessageMedia | null | PromiseLike<MessageMedia | null>) => void = () => undefined;
+ const boundedReady = new Promise<MessageMedia | null>(resolve => {
+ resolveBounded = resolve;
+ });
+ const slotHeld = this.inboundLimiter.run(() => {
+ const download = msg.downloadMedia();
+ resolveBounded(
+ withInboundDownloadTimeout(download, inboundMediaTimeoutMs(), () =>
+ this.logger.warn(
+ 'Inbound media download timed out (MEDIA_DOWNLOAD_TIMEOUT_MS); emitting message without media',
+ {
+ msgId: msg.id._serialized,
+ },
+ ),
),
- ),
- );
+ );
+ // Keep the slot occupied until the underlying download truly settles, not the timeout race.
+ return download.then(
+ () => undefined,
+ () => undefined,
+ );
+ });
+ // The slot-holder runs in the background; never let it surface as an unhandled rejection.
+ void slotHeld.catch(() => undefined);
+ const media = await boundedReady;
if (!media) return undefined;
const capped = capInboundMedia({
mimetype: media.mimetype,
@@ -343,6 +362,13 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
// eslint-disable-next-line @typescript-eslint/no-misused-promises
this.client.on('qr', async (qr: string) => {
+ // A 'qr' buffered by a wedged page can flush during the awaited client.destroy() (teardown sets
+ // tearingDown + DISCONNECTED first) or after recoverFromStuckAuth() nulls this.client. Ignore it so a
+ // late event can't resurrect a disconnecting adapter to QR_READY and re-emit a stale QR. Mirrors the
+ // 'authenticated' guard below; the normal first QR is unaffected (not tearing down, not FAILED, client set).
+ if (this.tearingDown || this.status === EngineStatus.FAILED || !this.client) {
+ return;
+ }
try {
this.qrCode = await qrcode.toDataURL(qr);
this.setStatus(EngineStatus.QR_READY);
diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.ts
index 6dcedd038..dd6381c0c 100644
--- a/src/modules/message/bulk-message.service.spec.ts
+++ b/src/modules/message/bulk-message.service.spec.ts
@@ -92,7 +92,12 @@ describe('BulkMessageService.processBatch', () => {
let service: BulkMessageService;
let repo: { findOne: jest.Mock; save: jest.Mock };
let messageService: { saveOutgoingMessage: jest.Mock };
- let engine: { sendTextMessage: jest.Mock };
+ let engine: {
+ sendTextMessage: jest.Mock;
+ sendImageMessage?: jest.Mock;
+ sendVideoMessage?: jest.Mock;
+ sendAudioMessage?: jest.Mock;
+ };
let sessionService: { getEngine: jest.Mock; findOne: jest.Mock };
const makeBatch = (messageCount: number): MessageBatch =>
@@ -192,6 +197,28 @@ describe('BulkMessageService.processBatch', () => {
expect(img?.mimetype).toBe('image/png');
});
+ it('persists the media filename from the chosen media type (image), not just from document', async () => {
+ engine.sendImageMessage = jest.fn().mockResolvedValue({ id: 'waimg', timestamp: 222 });
+ const batch = makeBatch(1);
+ batch.messages = [
+ {
+ chatId: '[email protected]',
+ type: 'image',
+ content: { image: { base64: 'QkFTRTY0SU1BR0U=', mimetype: 'image/png', filename: 'p.png' } },
+ },
+ ];
+ repo.findOne.mockResolvedValue(batch);
+
+ await runProcessBatch();
+
+ const imageSave = (
+ messageService.saveOutgoingMessage.mock.calls as Array<
+ [string, { type: string; metadata?: { media?: { filename?: string } } }]
+ >
+ ).find(([, payload]) => payload.type === 'image');
+ expect(imageSave?.[1].metadata?.media?.filename).toBe('p.png');
+ });
+
it('stops sending when the batch is cancelled in the DB by another instance/restart', async () => {
// First load is the running batch; the cadence re-read reports a CANCELLED status.
repo.findOne.mockResolvedValueOnce(makeBatch(3)).mockResolvedValue({ status: BatchStatus.CANCELLED });
diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.ts
index 14492a914..0e8344bbc 100644
--- a/src/modules/message/bulk-message.service.ts
+++ b/src/modules/message/bulk-message.service.ts
@@ -22,9 +22,9 @@ import { IWhatsAppEngine, MessageResult } from '../../engine/interfaces/whatsapp
interface BulkMessageContent {
text?: string;
caption?: string;
- image?: { url?: string; base64?: string; mimetype?: string };
- video?: { url?: string; base64?: string; mimetype?: string };
- audio?: { url?: string; base64?: string; mimetype?: string };
+ image?: { url?: string; base64?: string; mimetype?: string; filename?: string };
+ video?: { url?: string; base64?: string; mimetype?: string; filename?: string };
+ audio?: { url?: string; base64?: string; mimetype?: string; filename?: string };
document?: { url?: string; base64?: string; mimetype?: string; filename?: string };
}
@@ -397,7 +397,7 @@ export class BulkMessageService implements OnApplicationBootstrap {
media: {
mimetype: media.mimetype,
data: media.url ?? media.base64,
- filename: content.document?.filename,
+ filename: media.filename,
},
}
: undefined,