Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(wwebjs): resolve history message sender through getContact()
Tanmay Chachraa7c7d9a7dcce
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7c26c57f6..37bdf31c4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,6 +25,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- whatsapp-web.js chat history resolves each message's sender through `getContact()`, as the live `message` handler already does, so a group participant outside the account's contacts gets a sender label in history too.- Baileys sessions list the saved address book again after a process restart. WhatsApp sends neither history nor an app-state snapshot to a device that has synced once, and the contact store is in memory, so a restarted gateway answered `GET /api/sessions/:sessionId/contacts` with only the peers it had seen since. A reconnect that finds the store empty now re-pulls the snapshot of the app-state collection that carries saved contacts. The list is also the address book only: a peer known by pushname alone is no longer listed, while `GET .../contacts/:contactId` still resolves it with `isMyContact: false`, and a chat title from history sync no longer overwrites a saved name. Thanks @gabrielmmoraes1999.- whatsapp-web.js sessions send media again on the WhatsApp Web builds rolled out on 2026-09-17: the library spread the media model into the outgoing message after its id, and the model's private `__x_id` clobbered it, so every image, video, audio, document, sticker and status media send failed with `Data passed to getter must include an id property` while text kept working. An install-time patch carries upstream's one-line fix until a whatsapp-web.js release ships it ([#1643](https://github.com/rmyndharis/OpenWA/issues/1643), [#1636](https://github.com/rmyndharis/OpenWA/issues/1636)). Thanks @15874611923 and @Magnarks for the reports.- An ingress route can declare `dedupOn: "body"` to key provider retries on the raw body instead of the delivery-id header. A provider that mints a fresh delivery id on every retry attempt, as supabase/auth does inside its hook retry loop, was never deduplicated when an ack was lost, so the contact received the message twice; routes that do not declare it keep the header ([#1641](https://github.com/rmyndharis/OpenWA/issues/1641)).diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 93890841c..58a3445a3 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -712,6 +712,55 @@ describe('WhatsAppWebJsAdapter.getChatHistory enrichment (parity with the live pexpect(out[0].isGroup).toBe(true);});+ it("resolves the sender name via getContact() when the raw payload carries no notifyName (group participant not in the account's own contacts)", async () => {+ // A participant identified only by @lid, with no push name on the stored message object — the+ // shape that made the chat view render a group message with no sender label at all, even though+ // the live `message` event handler resolves a name for the identical message via getContact().+ const groupMsg = {+ id: { _serialized: 'M6' },+ from: '[email protected]',+ to: 'me',+ author: '999@lid',+ body: 'hi all',+ type: 'chat',+ timestamp: 500,+ fromMe: false,+ hasMedia: false,+ hasQuotedMsg: false,+ getContact: jest.fn().mockResolvedValue({ pushname: 'Alice' }),+ };+ const chat = { fetchMessages: jest.fn().mockResolvedValue([groupMsg]) };+ const client = { getChatById: jest.fn().mockResolvedValue(chat) };++ const out = await readyAdapter(client).getChatHistory('[email protected]', 50, false);++ expect(groupMsg.getContact).toHaveBeenCalled();+ expect(out[0].contact).toEqual({ pushName: 'Alice' });+ });++ it('tolerates a getContact() failure on a historical message instead of failing the whole history fetch', async () => {+ const groupMsg = {+ id: { _serialized: 'M7' },+ from: '[email protected]',+ to: 'me',+ author: '999@lid',+ body: 'hi all',+ type: 'chat',+ timestamp: 600,+ fromMe: false,+ hasMedia: false,+ hasQuotedMsg: false,+ getContact: jest.fn().mockRejectedValue(new Error('boom')),+ };+ const chat = { fetchMessages: jest.fn().mockResolvedValue([groupMsg]) };+ const client = { getChatById: jest.fn().mockResolvedValue(chat) };++ const out = await readyAdapter(client).getChatHistory('[email protected]', 50, false);++ expect(out[0].contact).toBeUndefined();+ expect(out[0].body).toBe('hi all');+ });+it('skips the media download when the declared size exceeds a caller-tightened mediaMaxBytes', async () => {// 12 MB passes the global 50 MiB default but not the seed's 10 MB store cap — proving the// override (not the default) did the gating, and the blob is never downloaded.diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.tsindex 2cc971b63..af9aaa513 100644--- a/src/engine/adapters/wwebjs-messaging.ts+++ b/src/engine/adapters/wwebjs-messaging.ts@@ -18,7 +18,7 @@ import { EngineRefusedError } from '../../common/errors/engine-refused.error';import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';import { chatKind, userPart } from '../identity/wa-id';import { chatHistoryMediaBudgetBytes, coerceDeclaredSize, ingestMediaBudgetBytes } from './inbound-media-cap';-import { buildIncomingMessageBase } from './message-mapper';+import { buildIncomingMessageBase, mapContactFields } from './message-mapper';import { buildVCard } from './vcard';import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';import { RecipientUnreachableError } from '../../common/errors/recipient-unreachable.error';@@ -721,6 +721,24 @@ export class WwebjsMessaging {out.isGroup = chatId.endsWith('@g.us');out.isStatusBroadcast = chatId === 'status@broadcast';out.kind = chatKind(chatId);+ // buildIncomingMessageBase only fills `contact` from the raw payload's synchronous+ // notifyName, which is frequently absent on a history-fetched message object (unlike a+ // freshly delivered one). Without this, a group participant not in the account's own+ // contacts (author-only, no saved name) shows no sender label at all in the chat view,+ // even though the live `message` event handler resolves one via getContact() for the+ // exact same message. Mirror that here so history and live rendering agree.+ try {+ const contact = await msg.getContact();+ if (contact) {+ const full = process.env.WEBHOOK_CONTACT_DETAILS === 'true';+ const merged = { ...out.contact, ...mapContactFields(contact, full) };+ if (Object.keys(merged).length > 0) {+ out.contact = merged;+ }+ }+ } catch (error) {+ this.host.logger.warn(`Failed to resolve contact for history message ${msg.id._serialized}: ${String(error)}`);+ }const call = extractWwebjsCall(msg);if (call) out.call = call;// Mirror the live handler's location + quoted-message enrichment so history renders identically —