Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(wwjs): report sends honestly when the engine returns no usable message (#762)

Yudhi Armyndharis325476000bd7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b4d328edd..bc79ac3b2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -42,6 +42,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
whatsapp-web.js cannot resolve the original (it is no longer in its local store) `revokedId` is
absent and the lookup falls back to `id`, as before. Refs #755.
+- **A send whose message can't be read back no longer crashes, and never claims a delivery it can't
+ prove.** `whatsapp-web.js`'s `Client.sendMessage()` can *resolve* with `undefined` instead of
+ throwing, while its typings declare `Promise<Message>` — so the adapter's `msg.id._serialized` reads
+ surfaced as an opaque `TypeError: Cannot read properties of undefined (reading 'id')` and a 500, at
+ seven send sites. All of them now route through one helper that distinguishes the two cases the
+ dependency collapses into that single `undefined`: no message at all is reported as a failed send
+ (it is genuinely ambiguous whether anything was dispatched, and a retryable false negative beats
+ claiming a delivery that never happened), whereas a message whose id is merely unreadable reports
+ the empty no-id sentinel `forwardMessage` already used — never a synthesised id. An empty id is now
+ normalized to NULL inside `saveOutgoingMessage`, so it can't collide on the non-partial
+ `(sessionId, waMessageId)` unique index and silently drop a bulk row. Refs #757.
+
### Security
## [0.8.18] - 2026-07-17
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 102d750c3..c6d202eb6 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -2003,3 +2003,60 @@ describe('WhatsAppWebJsAdapter inbound media concurrency (slot held until the re
expect(calls).toEqual(['bad', 'good']);
});
});
+
+/**
+ * The send contract when whatsapp-web.js cannot hand back a usable message (#757).
+ *
+ * `Client.sendMessage` RESOLVES with `undefined` rather than throwing, collapsing two opposite outcomes
+ * into one value (`Client.js:1558`), and its typings claim `Promise<Message>` — so nothing upstream of
+ * these tests catches a regression here.
+ */
+describe('WhatsAppWebJsAdapter send-result contract', () => {
+ const readyAdapter = (client: unknown): WhatsAppWebJsAdapter => {
+ const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });
+ (adapter as unknown as { status: EngineStatus }).status = EngineStatus.READY;
+ (adapter as unknown as { client: unknown }).client = client;
+ return adapter;
+ };
+
+ it('reports a send as failed when the engine resolves without a message', async () => {
+ // The dangerous case: `undefined` means EITHER the chat never resolved and nothing was sent, OR the
+ // message went out and only its id was unreadable. Indistinguishable here — so this must not be
+ // reported as success. A false negative is retryable; a 201 for a message that never left is not.
+ const sendMessage = jest.fn().mockResolvedValue(undefined);
+
+ await expect(readyAdapter({ sendMessage }).sendTextMessage('[email protected]', 'hi')).rejects.toThrow(
+ /may not have been delivered/,
+ );
+ // Regression guard: the old code dereferenced `msg.id` and surfaced an opaque TypeError instead.
+ await expect(readyAdapter({ sendMessage }).sendTextMessage('[email protected]', 'hi')).rejects.not.toThrow(TypeError);
+ });
+
+ it('returns the empty no-id sentinel when the message exists but its id is unreadable', async () => {
+ // A Message instance proves the send happened, so an unreadable id is unambiguously "sent, id
+ // unknown" — the shape a future WhatsApp Web re-mangle of `$1` would produce. Never fabricate one.
+ const sendMessage = jest.fn().mockResolvedValue({ id: { someFutureName: 'x' }, timestamp: 1700000000 });
+
+ const res = await readyAdapter({ sendMessage }).sendTextMessage('[email protected]', 'hi');
+
+ expect(res).toEqual({ id: '', timestamp: 1700000000 });
+ });
+
+ it('reads a renamed $1 id when the dependency has not normalized it', async () => {
+ const sendMessage = jest.fn().mockResolvedValue({ id: { $1: '[email protected]_ABC' }, timestamp: 1700000001 });
+
+ const res = await readyAdapter({ sendMessage }).sendTextMessage('[email protected]', 'hi');
+
+ expect(res).toEqual({ id: '[email protected]_ABC', timestamp: 1700000001 });
+ });
+
+ it('passes a healthy id straight through', async () => {
+ const sendMessage = jest
+ .fn()
+ .mockResolvedValue({ id: { _serialized: '[email protected]_XYZ' }, timestamp: 1700000002 });
+
+ const res = await readyAdapter({ sendMessage }).sendTextMessage('[email protected]', 'hi');
+
+ expect(res).toEqual({ id: '[email protected]_XYZ', timestamp: 1700000002 });
+ });
+});
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 99fe2ddd1..3bbd992d9 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -997,10 +997,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
const msg = await this.sendResolved(chatId, to =>
mentions?.length ? this.client!.sendMessage(to, text, { mentions }) : this.client!.sendMessage(to, text),
);
- return {
- id: msg.id._serialized,
- timestamp: msg.timestamp,
- };
+ return this.toMessageResult(msg);
}
async sendImageMessage(chatId: string, media: MediaInput): Promise<MessageResult> {
@@ -1052,10 +1049,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
}),
);
- return {
- id: msg.id._serialized,
- timestamp: msg.timestamp,
- };
+ return this.toMessageResult(msg);
}
async getContacts(): Promise<Contact[]> {
@@ -1156,10 +1150,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
address: location.address || '',
});
const msg = await this.sendResolved(chatId, to => this.client!.sendMessage(to, loc));
- return {
- id: msg.id._serialized,
- timestamp: msg.timestamp,
- };
+ return this.toMessageResult(msg);
}
async sendContactMessage(chatId: string, contact: ContactCard): Promise<MessageResult> {
@@ -1173,10 +1164,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
parseVCards: true,
}),
);
- return {
- id: msg.id._serialized,
- timestamp: msg.timestamp,
- };
+ return this.toMessageResult(msg);
}
async sendStickerMessage(chatId: string, media: MediaInput): Promise<MessageResult> {
@@ -1202,10 +1190,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
sendMediaAsSticker: true,
}),
);
- return {
- id: msg.id._serialized,
- timestamp: msg.timestamp,
- };
+ return this.toMessageResult(msg);
}
async sendPollMessage(chatId: string, poll: PollInput): Promise<MessageResult> {
@@ -1224,10 +1209,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
const msg = await this.sendResolved(chatId, to =>
this.client!.sendMessage(to, new Poll(poll.name, poll.options, pollOptions)),
);
- return {
- id: msg.id._serialized,
- timestamp: msg.timestamp,
- };
+ return this.toMessageResult(msg);
}
async replyToMessage(chatId: string, quotedMsgId: string, text: string): Promise<MessageResult> {
@@ -1245,10 +1227,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
// so route it through sendResolved (resolve @c.us->@lid, cache, self-heal). reply(content, chatId)
// accepts an explicit target (#583 R1).
const msg = await this.sendResolved(chatId, to => quotedMsg.reply(text, to));
- return {
- id: msg.id._serialized,
- timestamp: msg.timestamp,
- };
+ return this.toMessageResult(msg);
}
async forwardMessage(fromChatId: string, toChatId: string, messageId: string): Promise<MessageResult> {
@@ -1288,7 +1267,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
}
}
if (sent) {
- return { id: sent.id._serialized, timestamp: sent.timestamp };
+ return this.toMessageResult(sent);
}
} catch (error) {
this.logger.warn(`Forward succeeded but recovering the sent message id failed: ${String(error)}`);
@@ -1835,6 +1814,32 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
return new MessageMedia(media.mimetype, media.data.toString('base64'), media.filename);
}
+ /**
+ * Build the `MessageResult` for a send from whatever whatsapp-web.js hands back.
+ *
+ * `client.sendMessage()` can RESOLVE with `undefined` instead of throwing, and it collapses two
+ * opposite outcomes into that one value (`Client.js:1558`): the chat could not be resolved so nothing
+ * was sent (`if (!chat) return null`, `Client.js:1539`), or the message went out and only its id could
+ * not be read back (`Msg.get` miss, `Injected/Utils.js:585`). Nothing here can tell those apart, so an
+ * absent message is reported as a failed send: a false negative is visible and retryable, while
+ * claiming delivery for a message that never left is not recoverable. wwebjs's own typings hide the
+ * case entirely — `index.d.ts` declares `Promise<Message>`, so `strict` never flagged these reads.
+ *
+ * A `Message` instance is different: wwebjs only builds one from a real message model, so its presence
+ * proves the send happened. An id it cannot read there means "sent, id unknown" and carries the empty
+ * sentinel `forwardMessage` already returns — which `saveOutgoingMessage` stores as NULL rather than a
+ * fabricated id that a later ack could mis-match.
+ */
+ private toMessageResult(msg: Message | undefined): MessageResult {
+ if (!msg) {
+ throw new Error(
+ 'the engine returned no message for this send, so it may not have been delivered — check the chat before retrying',
+ );
+ }
+ const id = msg.id as unknown as SerializedWid | undefined;
+ return { id: id?._serialized ?? id?.$1 ?? '', timestamp: msg.timestamp };
+ }
+
private toStatusResult(msg: Message | undefined): StatusResult {
const ts = msg?.timestamp ? new Date(msg.timestamp * 1000) : new Date();
return {
diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.ts
index 6ae405f36..d4dc39cae 100644
--- a/src/modules/message/message.service.spec.ts
+++ b/src/modules/message/message.service.spec.ts
@@ -969,4 +969,28 @@ describe('MessageService', () => {
expect(mockEngine.deleteMessage).toHaveBeenCalledWith('[email protected]', 'wa-msg-1', false);
});
});
+
+ /**
+ * The empty id is the engine's "sent, but I couldn't read the id back" signal (#757). It has to reach
+ * the DB as NULL: UQ_messages_sessionId_waMessageId is NOT partial, so '' collides with the next
+ * id-less send in the same session, while NULLs stay exempt. In the bulk path that violation is
+ * swallowed into a warning, so the row would vanish with nothing surfacing.
+ */
+ describe('saveOutgoingMessage id normalization (#757)', () => {
+ it('stores an empty engine id as NULL rather than an empty string', async () => {
+ await service.saveOutgoingMessage('sess-1', { waMessageId: '', chatId: '[email protected]', type: 'text' });
+
+ expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({ waMessageId: undefined }));
+ });
+
+ it('leaves a real id untouched', async () => {
+ await service.saveOutgoingMessage('sess-1', {
+ waMessageId: '[email protected]_ABC',
+ chatId: '[email protected]',
+ type: 'text',
+ });
+
+ expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({ waMessageId: '[email protected]_ABC' }));
+ });
+ });
});
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index fa677bd0a..cb513ac99 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -524,7 +524,13 @@ export class MessageService {
const session = await this.sessionService.findOne(sessionId);
const message = this.messageRepository.create({
sessionId,
- waMessageId: data.waMessageId,
+ // An engine that sent a message but could not read its id back reports an empty id (see the
+ // whatsapp-web.js adapter's `toMessageResult`). Store NULL rather than '': the
+ // (sessionId, waMessageId) unique index is not partial, so a second id-less send in the same
+ // session collides on '' while NULLs stay exempt — and in the bulk path that violation is
+ // swallowed into a warning, losing the row silently. Normalizing at this one chokepoint covers
+ // every caller instead of relying on each to remember.
+ waMessageId: data.waMessageId || undefined,
chatId: data.chatId,
from: session?.phone || 'me',
to: data.chatId,
@@ -565,8 +571,9 @@ export class MessageService {
* `message:failed`. Log and return success instead.
*/
private async persistSentState(message: Message, result: MessageResult): Promise<MessageResponseDto> {
- // A forward whose engine couldn't recover the sent copy's id returns an empty id — leave waMessageId
- // unset (NULL) so no ack mis-matches it. Every other send path carries a real id.
+ // A send whose engine couldn't read the sent message's id back reports an empty id — a forward that
+ // can't recover the copy, or a WhatsApp Web build that renamed the id field out from under the
+ // engine. Leave waMessageId unset (NULL) so no ack mis-matches it.
if (result.id) message.waMessageId = result.id;
message.status = MessageStatus.SENT;
message.timestamp = result.timestamp;