Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): keep the media envelope when inbound download fails
Yudhi Armyndharis044a623ac149
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 07cce0bfd..02219ebaf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0Behaviour is unchanged on the current Puppeteer; the guard keeps a future bump from reporting aslow command as a transport death.+### Fixed++- Inbound media whose download fails now keeps the `media` envelope with `omitted: true` and the declared+ size, on both engines, instead of dropping the field and looking like a message that never had media.+- Webhook filters and automation rules gated on `hasMedia` now match those messages.+- Baileys logs a failed inbound media download at `warn` instead of `debug`, so it is visible by default.+## [0.23.3] - 2026-08-24### Addeddiff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex db39fb121..ab9f6d325 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -837,12 +837,14 @@ export class BaileysEvents {toBase64: () => buf.toString('base64'),});} catch (err) {- // A download failure yields a message with no media, never a propagated throw.- this.host.logger.debug('Failed to download inbound media; emitting message without media', {+ // A download failure yields the omitted marker, never a propagated throw: the media field stays+ // present, matching the skip/pre-gate/abort exits above. The declared size is the honest number+ // here, since nothing was downloaded and the cap the abort reports would be a fabrication.+ this.host.logger.warn('Inbound media download failed; emitting the omitted marker', {error: err instanceof Error ? err.message : String(err),msgId: msg.key.id,});- return undefined;+ return { mimetype, filename, omitted: true, sizeBytes: declared };}}diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex f95a47e28..1ba6f094b 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -2532,7 +2532,7 @@ describe('BaileysAdapter inbound fan-out', () => {expect(event.senderId).toBe('[email protected]'); // canonicalized to the neutral dialect});- it('media download failure: logs the error and emits the message without media (no throw)', async () => {+ it('media download failure: logs the error and emits the omitted marker (no throw)', async () => {// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertionconst baileys = jest.requireMock('@whiskeysockets/baileys') as {getContentType: jest.Mock;@@ -2540,26 +2540,38 @@ describe('BaileysAdapter inbound fan-out', () => {};baileys.getContentType.mockReturnValue('imageMessage');baileys.downloadMediaMessage.mockRejectedValue(new Error('download failed'));+ // The skip exit builds a marker identical to the one this asserts, so an ambient 'false' would+ // otherwise let the test pass having never reached the download at all.+ const prev = process.env.MEDIA_DOWNLOAD_ENABLED;+ process.env.MEDIA_DOWNLOAD_ENABLED = 'true';- 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: 'IMGFAIL' },- message: { imageMessage: { mimetype: 'image/jpeg', caption: 'broken' } },- messageTimestamp: 1700000025,- },- ],- });- await new Promise(r => setImmediate(r));- // message is still emitted, just without media- expect(onMessage).toHaveBeenCalledTimes(1);- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access- const msg = onMessage.mock.calls[0][0] as { media?: unknown };- expect(msg.media).toBeUndefined();+ 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: 'IMGFAIL' },+ message: { imageMessage: { mimetype: 'image/jpeg', caption: 'broken', fileLength: 4096 } },+ messageTimestamp: 1700000025,+ },+ ],+ });+ await new Promise(r => setImmediate(r));+ // The message is still emitted, and it still says it carried an image. sizeBytes is the DECLARED+ // size: nothing was downloaded, so reporting the cap (as the streaming abort does) would lie.+ expect(onMessage).toHaveBeenCalledTimes(1);+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const msg = onMessage.mock.calls[0][0] as { media?: unknown; body?: string };+ expect(msg.media).toEqual({ mimetype: 'image/jpeg', omitted: true, sizeBytes: 4096 });+ expect(msg.body).toBe('broken');+ expect(baileys.downloadMediaMessage).toHaveBeenCalled();+ } finally {+ if (prev === undefined) delete process.env.MEDIA_DOWNLOAD_ENABLED;+ else process.env.MEDIA_DOWNLOAD_ENABLED = prev;+ }});});diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 49eb1d725..8a447afb3 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -3033,7 +3033,11 @@ describe('WhatsAppWebJsAdapter inbound media (MEDIA_DOWNLOAD_ENABLED=false)', ()expect(msg.media?.omitted).toBeUndefined();});- it('still emits the echo (without media) when the own-send media download fails', async () => {+ it('emits the echo with the omitted marker when the own-send media download fails', async () => {+ // Pinned on: the disabled exit builds an identical marker, so an ambient 'false' would let this+ // pass without ever attempting a download. The describe's afterEach restores it.+ process.env[ENV] = 'true';+const adapter = new WhatsAppWebJsAdapter({sessionId: 'sess-echo-media-fail',sessionDataPath: './data/sessions',@@ -3071,9 +3075,58 @@ describe('WhatsAppWebJsAdapter inbound media (MEDIA_DOWNLOAD_ENABLED=false)', ()expect(onMessageCreate).toHaveBeenCalledTimes(1);// eslint-disable-next-line @typescript-eslint/no-unsafe-member-accessconst msg = onMessageCreate.mock.calls[0][0] as { media?: unknown };- // The failure is contained at the call site: the echo still fires, just without the media field- // (the omitted marker is synthesized downstream, in SessionService's persistence).- expect(msg.media).toBeUndefined();+ // The failure is contained in capInboundMediaFor: the echo still fires, carrying the declared-only+ // marker so a consumer can tell "the image was lost" from "there was no image".+ expect(msg.media).toEqual({ mimetype: 'image/png', omitted: true, sizeBytes: 3 });+ expect(mockMsg.downloadMedia).toHaveBeenCalled(); // the disabled exit builds the same marker+ });++ it('emits the omitted marker when an inbound media download fails', async () => {+ // The received path guards its assignment with `if (capped)`, so it drops the field on its own if the+ // adapter ever stops returning an envelope. A webhook consumer filtering on hasMedia sees nothing then.+ process.env[ENV] = 'true';++ const adapter = new WhatsAppWebJsAdapter({+ sessionId: 'sess-inbound-media-fail',+ sessionDataPath: './data/sessions',+ puppeteer: {},+ });+ const client = Object.assign(new EventEmitter(), {+ info: { wid: { user: '628123' }, pushname: 'Tester' },+ getState: jest.fn().mockResolvedValue(WAState.CONNECTED),+ pupPage: { evaluate: jest.fn().mockResolvedValue(true) },+ });+ (adapter as unknown as { client: unknown }).client = client;+ const onMessage = jest.fn();+ (adapter as unknown as { callbacks: unknown }).callbacks = { onMessage };+ (adapter as unknown as { setupEventHandlers: () => void }).setupEventHandlers();++ const mockMsg = {+ id: { _serialized: 'IN_MEDIA_FAIL_1' },+ from: '[email protected]',+ to: '[email protected]',+ body: '',+ type: 'image',+ timestamp: 1700000080,+ fromMe: false,+ hasMedia: true,+ _data: { mimetype: 'image/jpeg', size: 2048 },+ // The minified page-side throw a WhatsApp Web build surfaces through Puppeteer.+ downloadMedia: jest.fn().mockRejectedValue(new Error('t: t')),+ getContact: jest.fn().mockResolvedValue(null),+ hasQuotedMsg: false,+ };++ client.emit('message', mockMsg);+ await new Promise(r => setImmediate(r));+ 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 { media?: unknown; type?: string };+ expect(msg.type).toBe('image');+ expect(msg.media).toEqual({ mimetype: 'image/jpeg', omitted: true, sizeBytes: 2048 });+ expect(mockMsg.downloadMedia).toHaveBeenCalled(); // the disabled exit builds the same marker});});@@ -4698,7 +4751,7 @@ describe('WhatsAppWebJsAdapter inbound media concurrency (slot held until the reexpect(maxInFlight).toBe(1);});- it('propagates a rejecting download to the caller and releases the slot for the next download', async () => {+ it('returns the omitted marker for a rejecting download and releases the slot for the next one', async () => {process.env.INBOUND_MEDIA_CONCURRENCY = '1';process.env.MEDIA_DOWNLOAD_TIMEOUT_MS = '10000'; // long: we want the reject, not the timeoutprocess.env.MEDIA_DOWNLOAD_MAX_BYTES = String(10 * 1024 * 1024);@@ -4720,7 +4773,12 @@ describe('WhatsAppWebJsAdapter inbound media concurrency (slot held until the reconst 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');+ // A rejection is the same "no usable media" outcome as the disabled, pre-gate and timeout exits, and+ // reports it the same way. It used to be the one download outcome with no exit of its own: the caller's+ // race adopted it and rethrew, so every call site dropped the media field entirely.+ await expect(cap(makeMsg('bad', 'reject'))).resolves.toEqual(+ expect.objectContaining({ mimetype: 'image/png', omitted: true, sizeBytes: 100 }),+ );// 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'));diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 23c3e3013..8442ffdb3 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -68,6 +68,7 @@ import {withInboundDownloadTimeout,} from './inbound-media-cap';import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';+import { readWid } from '../types/whatsapp-web-js.types';export interface WhatsAppWebJsConfig {sessionId: string;@@ -280,7 +281,8 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin/*** Download inbound media safely. downloadMedia() can't be size-bounded at the source, so (1) pre-gate* on the sender-declared size and skip the download entirely when it exceeds the cap, and (2) run the- * download through the concurrency limiter for backpressure. Returns undefined when there's no media.+ * download through the concurrency limiter for backpressure. Resolves an envelope whenever it has one+ * to build: the payload, or the declared-only marker when no blob is available.*/private async capInboundMediaFor(msg: Message,@@ -289,12 +291,16 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginif (!isMediaDownloadEnabled()) {return declaredOnlyMedia(msg);}+ // Read the id once, through readWid: a bare `_serialized` read yields undefined on the WA Web build+ // that renamed it to `$1` (#747), which is the same build whose page-side rename makes these+ // downloads fail. The warnings below are the diagnostic for it, so they must carry a real id.+ const msgId = readWid(msg.id);const maxBytes = maxBytesOverride ?? inboundMediaMaxBytes();const data = (msg as unknown as { _data?: { size?: number; mimetype?: string; filename?: string } })._data;const declared = coerceDeclaredSize(data?.size);if (declared > maxBytes) {this.logger.warn('Inbound media declared size exceeds the cap; skipped download', {- msgId: msg.id._serialized,+ msgId,sizeBytes: declared,maxBytes,});@@ -312,13 +318,23 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginresolveBounded = resolve;});const slotHeld = this.inboundLimiter.run(() => {- const download = msg.downloadMedia();+ // downloadMedia() is async, so a page-side throw (a detached target, a WA Web field rename) arrives+ // as a rejection, which boundedReady adopts and rethrows past the only exit that builds the marker,+ // leaving every call site to emit with no media field at all. It is the same "no usable media"+ // outcome as the timeout below, so it takes the same null sentinel.+ const download = msg.downloadMedia().catch((error: unknown) => {+ this.logger.warn('Inbound media download failed; emitting the omitted marker', {+ msgId,+ error: String(error),+ });+ return null;+ });resolveBounded(withInboundDownloadTimeout(download, inboundMediaTimeoutMs(), () =>this.logger.warn('Inbound media download timed out (MEDIA_DOWNLOAD_TIMEOUT_MS); emitting message without media',{- msgId: msg.id._serialized,+ msgId,},),),@@ -335,7 +351,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin// fire-and-forget promise is not an acceptable way to find that out.void slotHeld.catch((error: unknown) => {this.logger.warn('Inbound media slot holder rejected unexpectedly; emitting message without media', {- msgId: msg.id._serialized,+ msgId,error: String(error),});resolveBounded(null);@@ -351,7 +367,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginthis.logger.warn('Inbound media did not arrive within MEDIA_DOWNLOAD_TIMEOUT_MS; emitting message without media',{- msgId: msg.id._serialized,+ msgId,},),);@@ -366,7 +382,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin});if (capped.omitted) {this.logger.warn('Inbound media exceeds MEDIA_DOWNLOAD_MAX_BYTES; dropped payload, kept envelope', {- msgId: msg.id._serialized,+ msgId,sizeBytes: capped.sizeBytes,});}diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 5e716c1d8..648b7211d 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -132,7 +132,7 @@ export interface IncomingMessage {mimetype: string;filename?: string;data?: string; // base64; absent when the payload was omitted (see `omitted`)- /** True when the media blob was dropped due to a size cap, timeout, or concurrency saturation. */+ /** True when the media blob was dropped: a size cap, a timeout, a disabled download, or a failed one. */omitted?: boolean;/** Decoded byte size of the media; always set when `omitted` is true. */sizeBytes?: number;diff --git a/src/modules/session/message-row.mapper.spec.ts b/src/modules/session/message-row.mapper.spec.tsindex 22cf816ca..3293b613b 100644--- a/src/modules/session/message-row.mapper.spec.ts+++ b/src/modules/session/message-row.mapper.spec.ts@@ -40,9 +40,8 @@ describe('buildMessageMetadata', () => {});describe('omitted-media synthesis', () => {- // A wwjs own-send echo whose media download failed and the history backfill both arrive without- // the payload; without a marker the row renders as an empty bubble and drops out of the by-type- // stats.+ // The history backfill arrives without the payload; without a marker the row renders as an empty+ // bubble and drops out of the by-type stats.it.each([...MEDIA_MESSAGE_TYPES])('synthesizes a placeholder for a media-typed %s when asked', type => {expect(buildMessageMetadata(msg({ type: type as MessageType }), true)).toEqual({media: { mimetype: '', omitted: true },diff --git a/src/modules/session/message-row.mapper.ts b/src/modules/session/message-row.mapper.tsindex da231cdb0..11d2d5892 100644--- a/src/modules/session/message-row.mapper.ts+++ b/src/modules/session/message-row.mapper.ts@@ -3,11 +3,11 @@ import type { IncomingMessage } from '../../engine/interfaces/whatsapp-engine.in/*** Message types whose rows must show a media placeholder even when the payload carried none.*- * A wwjs own-send echo whose media download failed carries no media field at all, and the history- * sync maps messages media-free to keep its footprint down. Without the marker such a row renders+ * The history sync maps messages media-free to keep its footprint down, so a media-typed message can+ * still reach persistence with no media field at all. Without the marker such a row renders* as an empty bubble — the DB copy wins over the engine-history placeholder in the dashboard- * merge — and the by-type stats filter would skip it. (The Baileys API-send echo needs no synthesis:- * it emits the omitted marker itself.)+ * merge — and the by-type stats filter would skip it. (Neither engine's live path needs synthesis:+ * both emit the omitted marker whenever they have one to build.)*/export const MEDIA_MESSAGE_TYPES = new Set(['image', 'video', 'audio', 'voice', 'sticker', 'document']);diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.tsindex f98f4d555..669f765ba 100644--- a/src/modules/session/session-engine-lifecycle.service.ts+++ b/src/modules/session/session-engine-lifecycle.service.ts@@ -41,9 +41,8 @@ const isStatusSeedOnReadyEnabled = (): boolean => process.env.STATUS_SEED_ON_REA// Message types that carry downloadable media. Any persisted row of these types must have a media// marker in metadata — never NULL — or the dashboard renders an empty bubble (no placeholder) and the-// by-type stats filter skips the row. Sources that arrive without a media field (media-free history-// sync, a wwjs own-send echo whose download failed) get the omitted marker synthesized at the-// persistence chokepoints.+// by-type stats filter skips the row. Sources that arrive without a media field (the media-free+// history sync) get the omitted marker synthesized at the persistence chokepoints.export interface ReconnectState extends ReconnectAttemptState {/** The pending attempt's timer. Lives here, not in the policy, which stays free of side effects. */diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 3162a1a45..0fd4d0a48 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -3437,9 +3437,9 @@ describe('SessionService', () => {});it('synthesizes the omitted media marker for a media echo carrying no media field', async () => {- // A wwjs echo whose media download failed carries no media field at all — the sync- // buildIncomingMessageBase attaches none and the enrichment around it is best-effort. Without- // the marker the dashboard renders an empty bubble and the by-type stats filter would skip the row.+ // An echo can reach persistence with no media field at all — the sync buildIncomingMessageBase+ // attaches none and the enrichment around it is best-effort. Without the marker the dashboard+ // renders an empty bubble and the by-type stats filter would skip the row.const callbacks = await startAndCaptureCallbacks();(hookManager.execute as jest.Mock).mockImplementation((_e: string, data: unknown) =>Promise.resolve({ continue: true, data }),