Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): name the sender of a group read receipt
Yudhi Armyndharis145e5edb8ec5
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 1f30cabb3..355a140fa 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -988,7 +988,7 @@ Mark a chat as read/seen.| `chatId` | string | Yes | `@IsString`; `@IsNotEmpty`; `@MaxLength(255)`; `@Matches(/^[^\s@]+@[^\s@]+$/)` (localpart@host, no whitespace) | Engine-native JID, e.g. `[email protected]` (wwebjs) or `[email protected]` (Baileys) || `messageIds` | string[] | No | `@IsArray`; `@ArrayNotEmpty`; `@ArrayMaxSize(100)`; each a non-empty token with no whitespace | Messages to acknowledge. Omit the field to acknowledge only the newest received message; an empty array is rejected. |-Baileys acknowledges individual messages rather than chats, and the receipt enumerates ids instead of carrying a read-up-to watermark. Without `messageIds` only the newest received message the engine still holds in memory gets a receipt, so a burst leaves its earlier messages unread and a session restarted since the message arrived has nothing to acknowledge at all. Each supplied id is resolved through the message store, which is what carries the `participant` a group receipt needs. Ignored by whatsapp-web.js, whose own `sendSeen` is chat-level.+Baileys acknowledges individual messages rather than chats, and the receipt enumerates ids instead of carrying a read-up-to watermark. Without `messageIds` only the newest received message the engine still holds in memory gets a receipt, so a burst leaves its earlier messages unread and a session restarted since the message arrived has nothing to acknowledge at all. Each supplied id is resolved through the message store, which is what carries the `participant` a group receipt needs. An id the store never held (history backfill) in a group takes its `participant` from the author the gateway stored for that message; one with no stored author is left out of the receipt, and the route answers `{ "success": false }` when none of the ids could be named. Ignored by whatsapp-web.js, whose own `sendSeen` is chat-level.```json{ "chatId": "[email protected]", "messageIds": ["3EB0C767D26B8A3F1A2B", "3EB0C767D26B8A3F1A2C"] }diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex 70486a73a..ccdde696a 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -973,6 +973,9 @@ adapter boundary — none silently stubs.resolves `false` rather than throwing, so a chat the session has seen no message in, or one holdingonly this account's own sends, answers `POST chats/read` with `{"success": false}`, wherewhatsapp-web.js marks it read from the page-side chat object without needing any local history.+ With message ids, a group id the message store never held (history backfill) takes its receipt's+ participant from the author the gateway stored for it; one with no stored author is left out of the+ receipt, and the answer is `false` when no id could be named.- **`setProfileName` / `setProfilePicture` / `deleteProfilePicture` refusals (baileys).**whatsapp-web.js reads a page-side verdict for all three (`setDisplayName` and `setProfilePicture`resolve `false`, `deleteProfilePicture` resolves an explicit `false`) and raises a `403`. Thediff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex 102e64be1..b13a25ebb 100644--- a/src/engine/adapters/baileys-contacts.ts+++ b/src/engine/adapters/baileys-contacts.ts@@ -6,7 +6,7 @@ import { BAILEYS_QUERY_BUDGET_MS, confirmedWrite, withQueryDeadline } from './baimport { EngineTransportError } from '../../common/errors/engine-transport.error';import { RecipientUnreachableError } from '../../common/errors/recipient-unreachable.error';import { LidNotMappedError } from '../../common/errors/lid-not-mapped.error';-import { parseWaId, userPart } from '../identity/wa-id';+import { chatKind, parseWaId, userPart } from '../identity/wa-id';import { storedKeyInChat } from './baileys-message-mapper';import { refusedStatusCode } from './baileys-groups';@@ -372,9 +372,9 @@ export class BaileysContacts {return this.host.listChats();}- async sendSeen(chatId: string, messageIds?: string[]): Promise<boolean> {+ async sendSeen(chatId: string, messageIds?: string[], authors?: ReadonlyMap<string, string>): Promise<boolean> {this.host.ensureReady();- const keys = await this.receiptKeys(chatId, messageIds);+ const keys = await this.receiptKeys(chatId, messageIds, authors);if (keys.length === 0) {return false; // nothing known to mark read}@@ -400,9 +400,16 @@ export class BaileysContacts {* sender; its hardcoded `fromMe: false` is wrong for an id that belongs to an outbound message;* and its jid is whichever dialect the caller happened to send. The stored key has all three* right. Ids the store has never seen — history backfill is emitted but not persisted — keep the- * synthesised key, which is what the 1:1 case ran on before.+ * synthesised key in a 1:1 chat, which is what that case ran on before. A group receipt that names+ * no sender cannot be attributed, so there the key takes `authors` (message id to the stored poster,+ * which the gateway keeps for every group message), and an id with no known author is left out of+ * the receipt rather than sent as one WhatsApp may ignore.*/- private async receiptKeys(chatId: string, messageIds?: string[]): Promise<WAMessageKey[]> {+ private async receiptKeys(+ chatId: string,+ messageIds?: string[],+ authors?: ReadonlyMap<string, string>,+ ): Promise<WAMessageKey[]> {// null as well as undefined: the REST body rejects an explicit null, but this is the engine// boundary and an internal caller reaching it with one used to dereference it below as a 500.if (messageIds === undefined || messageIds === null) {@@ -432,7 +439,14 @@ export class BaileysContacts {).map(msg => [msg.key.id as string, msg.key]),);- return messageIds.map(id => keyById.get(id) ?? { remoteJid, id, fromMe: false });+ const inGroup = chatKind(remoteJid) === 'group';+ return messageIds.flatMap((id): WAMessageKey[] => {+ const key = keyById.get(id);+ if (key) return [key];+ if (!inGroup) return [{ remoteJid, id, fromMe: false }];+ const author = authors?.get(id);+ return author ? [{ remoteJid, id, fromMe: false, participant: this.host.toEngineJid(author) }] : [];+ });}async markUnread(chatId: string): Promise<boolean> {diff --git a/src/engine/adapters/baileys-send-seen.spec.ts b/src/engine/adapters/baileys-send-seen.spec.tsindex 06d66ed00..83f0bbf3b 100644--- a/src/engine/adapters/baileys-send-seen.spec.ts+++ b/src/engine/adapters/baileys-send-seen.spec.ts@@ -206,6 +206,89 @@ describe('sendSeen', () => {]);});+ describe('ids of a group the message store never held', () => {+ // History backfill is emitted and persisted for the chat view only, so a group message of that kind has no+ // stored key. A group receipt names its sender through `participant`; without it WhatsApp cannot attribute+ // the receipt, so the id takes the gateway's stored author or is left out.+ const GROUP = '[email protected]';+ const authors = (entries: Array<[string, string]>): ReadonlyMap<string, string> => new Map(entries);++ it('builds the key with the stored author as its participant', async () => {+ const readMessages = jest.fn().mockResolvedValue(undefined);+ const host = makeHost({ getSocket: () => ({ readMessages }) as unknown as WASocket });++ await expect(+ new BaileysContacts(host, 500).sendSeen(GROUP, ['H1'], authors([['H1', '[email protected]']])),+ ).resolves.toBe(true);++ expect(readMessages).toHaveBeenCalledWith([+ { remoteJid: GROUP, id: 'H1', fromMe: false, participant: '[email protected]' },+ ]);+ });++ it('leaves a lid author in its own dialect', async () => {+ const readMessages = jest.fn().mockResolvedValue(undefined);+ const host = makeHost({ getSocket: () => ({ readMessages }) as unknown as WASocket });++ await new BaileysContacts(host, 500).sendSeen(GROUP, ['H1'], authors([['H1', '9988@lid']]));++ expect(readMessages).toHaveBeenCalledWith([+ { remoteJid: GROUP, id: 'H1', fromMe: false, participant: '9988@lid' },+ ]);+ });++ it('sends no key at all for an id whose author is unknown, and says nothing was acknowledged', async () => {+ const readMessages = jest.fn().mockResolvedValue(undefined);+ const host = makeHost({ getSocket: () => ({ readMessages }) as unknown as WASocket });++ await expect(new BaileysContacts(host, 500).sendSeen(GROUP, ['H1', 'H2'])).resolves.toBe(false);+ await expect(+ new BaileysContacts(host, 500).sendSeen(GROUP, ['H1'], authors([['OTHER', '[email protected]']])),+ ).resolves.toBe(false);++ expect(readMessages).not.toHaveBeenCalled();+ });++ it('acknowledges the ids it can name and skips the rest without failing the read', async () => {+ const readMessages = jest.fn().mockResolvedValue(undefined);+ const stored1 = { id: 'S1', remoteJid: GROUP, fromMe: false, participant: '[email protected]' };+ const host = makeHost({+ getSocket: () => ({ readMessages }) as unknown as WASocket,+ getStoredMessages: () => Promise.resolve([stored(stored1)]),+ });++ await expect(+ new BaileysContacts(host, 500).sendSeen(+ GROUP,+ ['S1', 'H1', 'LOST', 'H2'],+ // S1 has an author too: the stored key wins, as it carries the dialect WhatsApp used.+ authors([+ ['S1', '[email protected]'],+ ['H1', '[email protected]'],+ ['H2', '[email protected]'],+ ]),+ ),+ ).resolves.toBe(true);++ expect(readMessages).toHaveBeenCalledWith([+ stored1,+ { remoteJid: GROUP, id: 'H1', fromMe: false, participant: '[email protected]' },+ { remoteJid: GROUP, id: 'H2', fromMe: false, participant: '[email protected]' },+ ]);+ });++ it('keeps a stored key and leaves a one to one chat on its synthesised key whatever authors say', async () => {+ const readMessages = jest.fn().mockResolvedValue(undefined);+ const host = makeHost({ getSocket: () => ({ readMessages }) as unknown as WASocket });++ await expect(+ new BaileysContacts(host, 500).sendSeen('[email protected]', ['M1'], authors([['M1', '[email protected]']])),+ ).resolves.toBe(true);++ expect(readMessages).toHaveBeenCalledWith([{ remoteJid: '[email protected]', id: 'M1', fromMe: false }]);+ });+ });+it('marks supplied messages even when the store has nothing cached', async () => {// The restart case: the in-memory store is empty, so the old code returned false under a 200// and no receipt was ever sent. A caller that persisted the IDs is not subject to that.diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 4d529b299..4add37110 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -545,8 +545,8 @@ export class BaileysAdapter implements IWhatsAppEngine {return this.messaging.subscribeToPresence(chatId);}- async sendSeen(chatId: string, messageIds?: string[]): Promise<boolean> {- return this.contacts.sendSeen(chatId, messageIds);+ async sendSeen(chatId: string, messageIds?: string[], authors?: ReadonlyMap<string, string>): Promise<boolean> {+ return this.contacts.sendSeen(chatId, messageIds, authors);}async markUnread(chatId: string): Promise<boolean> {diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 806d5ba71..7c2753e45 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -1591,8 +1591,11 @@ export interface ChatCapability {* `messageIds` names exactly which messages to acknowledge. Engines that acknowledge per* message (Baileys) need it to mark a burst, or anything at all after a restart; engines with a* chat-level receipt (whatsapp-web.js) ignore it.+ *+ * `authors` maps a message id to who posted it, for a group: a receipt names its sender, and an id the+ * engine never kept (history backfill) has no key to read it from. An id with neither is not acknowledged.*/- sendSeen(chatId: string, messageIds?: string[]): Promise<boolean>;+ sendSeen(chatId: string, messageIds?: string[], authors?: ReadonlyMap<string, string>): Promise<boolean>;markUnread(chatId: string): Promise<boolean>;diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex bb6ef533c..79688590d 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -8322,7 +8322,7 @@ describe('SessionService', () => {// Second argument is the optional messageIds, absent here — the engine falls back to the// newest message it still holds.- expect(mockEngine.sendSeen).toHaveBeenCalledWith('[email protected]', undefined);+ expect(mockEngine.sendSeen).toHaveBeenCalledWith('[email protected]', undefined, undefined);expect(result).toBe(true);});@@ -8336,7 +8336,63 @@ describe('SessionService', () => {await service.sendSeen('sess-uuid-1', '[email protected]', ['M1', 'M2']);- expect(mockEngine.sendSeen).toHaveBeenCalledWith('[email protected]', ['M1', 'M2']);+ // A one to one receipt needs no sender, so the rows are not read.+ expect(mockEngine.sendSeen).toHaveBeenCalledWith('[email protected]', ['M1', 'M2'], undefined);+ expect(messageRepository.find).not.toHaveBeenCalled();+ });++ describe('in a group', () => {+ const GROUP = '[email protected]';+ const start = async (): Promise<void> => {+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ await service.start('sess-uuid-1');+ mockEngine.sendSeen.mockResolvedValue(true);+ };++ it('hands the engine who posted each named message, from the rows the gateway stored', async () => {+ await start();+ (messageRepository.find as jest.Mock).mockResolvedValue([+ { waMessageId: 'M1', author: '[email protected]' },+ { waMessageId: 'M2', author: '9988@lid' },+ { waMessageId: 'M3', author: null },+ ]);++ await service.sendSeen('sess-uuid-1', GROUP, ['M1', 'M2', 'M3']);++ expect(messageRepository.find).toHaveBeenCalledWith(+ expect.objectContaining({+ where: expect.objectContaining({+ sessionId: 'sess-uuid-1',+ chatId: GROUP,+ direction: MessageDirection.INCOMING,+ }) as unknown,+ }),+ );+ const [, , authors] = mockEngine.sendSeen.mock.calls[0] as [string, string[], ReadonlyMap<string, string>];+ expect([...authors]).toEqual([+ ['M1', '[email protected]'],+ ['M2', '9988@lid'],+ ]);+ });++ it('reads no rows when it names no message', async () => {+ await start();++ await service.sendSeen('sess-uuid-1', GROUP);++ expect(messageRepository.find).not.toHaveBeenCalled();+ expect(mockEngine.sendSeen).toHaveBeenCalledWith(GROUP, undefined, undefined);+ });++ it('still reads the chat when the rows cannot be read', async () => {+ await start();+ (messageRepository.find as jest.Mock).mockRejectedValue(new Error('database is locked'));++ await expect(service.sendSeen('sess-uuid-1', GROUP, ['M1'])).resolves.toBe(true);++ expect(mockEngine.sendSeen).toHaveBeenCalledWith(GROUP, ['M1'], undefined);+ });});it('should throw BadRequestException when session is not started', async () => {diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 87382b46c..89cba191b 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -57,7 +57,8 @@ import { ShutdownService } from '../../common/services/shutdown.service';import { HookManager } from '../../core/hooks';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';import { resolveJidCandidates } from '../../engine/identity/jid-candidates';-import { Message } from '../message/entities/message.entity';+import { chatKind } from '../../engine/identity/wa-id';+import { Message, MessageDirection } from '../message/entities/message.entity';import { ServerShuttingDownException, SessionStoppedException } from './session-engine-controls';// Type-only: the module binds this class to PLUGIN_SESSION_PORT with a `useExisting` alias, which// TypeScript does not check, so `implements` is what keeps the two in step.@@ -1130,7 +1131,34 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatawait this.findOne(id); // Verify session existsconst engine = this.requireEngine(id);- return engine.sendSeen(chatId, messageIds);+ return engine.sendSeen(chatId, messageIds, await this.groupAuthors(id, chatId, messageIds));+ }++ /**+ * Who posted each named message of a group, from the rows the gateway stored. A group read receipt+ * names the sender, and for a message the engine never kept (history backfill) these rows are the only+ * place it is recorded. Best-effort: a read that cannot learn them still acknowledges what the engine+ * can name on its own.+ */+ private async groupAuthors(+ sessionId: string,+ chatId: string,+ messageIds?: string[],+ ): Promise<ReadonlyMap<string, string> | undefined> {+ if (!messageIds?.length || chatKind(chatId) !== 'group') return undefined;+ try {+ const rows = await this.messageRepository.find({+ where: { sessionId, chatId, waMessageId: In(messageIds), direction: MessageDirection.INCOMING },+ select: { waMessageId: true, author: true },+ });+ return new Map(rows.flatMap(row => (row.waMessageId && row.author ? [[row.waMessageId, row.author]] : [])));+ } catch (error) {+ this.logger.warn('Could not read who posted the messages a read names; sending the read without them', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ return undefined;+ }}async markUnread(id: string, chatId: string): Promise<boolean> {