Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): keep the chat preview in step with edits and deletes
Yudhi Armyndharis2f0613816a03
diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex dcf815973..f847706dc 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -299,6 +299,7 @@ export class BaileysEvents {body: '',timestamp: toUnixSeconds(msg.messageTimestamp),};+ this.host.recordMessageEdit(remoteJid, revoked.id, '');this.host.getOnMessageRevoked()?.(revoked);return;}diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.tsindex 48b6b0fb7..99ee20152 100644--- a/src/engine/adapters/baileys-messaging.ts+++ b/src/engine/adapters/baileys-messaging.ts@@ -52,6 +52,8 @@ export interface BaileysMessagingHost {putStoredMessage(msg: WAMessage): Promise<void> | undefined;/** Make a just-sent message the chat's last-message preview and sort time (its echo is skipped). */recordMessage(msg: WAMessage): void;+ /** Replace the chat preview's text when the message is still the chat's last one (edit, or '' once deleted). */+ recordMessageEdit(chatId: string, messageId: string, text: string): void;/** Record the id of a message this session just sent, so its library echo is recognised as ours. */rememberOwnSend(id: string | null | undefined): void;/** Look up a previously-seen message from the store (the reply/forward/react/delete handle). */@@ -541,8 +543,12 @@ export class BaileysMessaging {// revoke, yet the send resolves, so it would report a deletion that never happened. WhatsApp Web// deletes such a message for the account alone instead, and so does this. A group whose member// list shows no row for the account proves nothing either way, so the revoke still goes out there.+ // Whichever branch runs, the text leaves this account's view, so it must not stay the chat+ // preview. The echo of an own revoke is skipped as an own send, so the inbound path never clears it.+ const chatJid = target.key.remoteJid ?? chatId;if (forEveryone && (target.key.fromMe === true || (await this.selfIsGroupAdmin(target.key.remoteJid)) !== false)) {await this.send(await this.toDeliverableJid(chatId), { delete: target.key });+ this.host.recordMessageEdit(chatJid, messageId, '');return;}// Delete-for-me (revoke on this device only): Baileys exposes it as a chat modification, not a@@ -560,6 +566,7 @@ export class BaileysMessaging {),'the delete-for-me',);+ this.host.recordMessageEdit(chatJid, messageId, '');}/**@@ -602,6 +609,8 @@ export class BaileysMessaging {// content, so omitting mentions drops whatever tags the original carried.const editContent = { text: body, ...this.withMentions(mentions), edit: target.key };await this.send(jid, this.previewSafe(editContent), this.previewSafeOptions(editContent));+ // The edit's echo is skipped as an own send, so the chat preview follows it from here.+ this.host.recordMessageEdit(target.key.remoteJid ?? chatId, messageId, body);// Both fields describe the EDITED MESSAGE, not the protocol envelope that carried the edit.// That envelope has an id and a send time of its own; answering with either would name something// no route can address and no stored row is keyed by, and would disagree with thediff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 2f6da964a..2f03e49eb 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -3386,6 +3386,26 @@ describe('BaileysAdapter inbound fan-out', () => {});});+ it("no longer shows a revoked message's text as the chat preview", async () => {+ baileys.getContentType.mockImplementation(realGetContentType);+ const adapter = newAdapter();+ await adapter.initialize({});+ fakeSock.fire('connection.update', { connection: 'open' });+ fakeSock.fire('chats.upsert', [{ id: '[email protected]', name: 'Alice' }]);+ const deliver = async (id: string, message: Record<string, unknown>, messageTimestamp: number) => {+ fakeSock.fire('messages.upsert', {+ type: 'notify',+ messages: [{ key: { remoteJid: '[email protected]', fromMe: false, id }, message, messageTimestamp }],+ });+ await new Promise(r => setImmediate(r));+ await new Promise(r => setImmediate(r));+ };+ await deliver('IN_LAST', { conversation: 'sent to the wrong chat' }, 1700000050);+ expect((await adapter.getChats())[0]?.lastMessage).toBe('sent to the wrong chat');+ await deliver('REVOKE_1', { protocolMessage: { key: { id: 'IN_LAST' }, type: 0 } }, 1700000060);+ expect((await adapter.getChats())[0]?.lastMessage).toBe('');+ });+describe('contentless protocol traffic on the live path (#1568)', () => {/** Push one group message through the live upsert handler with Baileys' real content-type resolution. */const fireLive = async (@@ -4387,6 +4407,40 @@ describe('BaileysAdapter store-backed ops', () => {]);});+ describe("an API edit or delete of the chat's last message", () => {+ const sentLast = {+ key: { id: 'OUT_LATER', remoteJid: '[email protected]', fromMe: true },+ message: { extendedTextMessage: { text: 'on its way' } },+ messageTimestamp: 1700000100,+ };++ /** Make an API send the chat's last message, then hand it back as the stored original. */+ const sendLast = async (): Promise<BaileysAdapter> => {+ const adapter = await ready();+ fakeSock.fire('chats.upsert', [{ id: '[email protected]', name: 'Alice' }]);+ fakeSock.sendMessage.mockResolvedValueOnce(sentLast);+ await adapter.sendTextMessage('[email protected]', 'on its way');+ fakeStore.getMessage.mockResolvedValue(sentLast);+ return adapter;+ };+ const preview = async (adapter: BaileysAdapter) => (await adapter.getChats())[0]?.lastMessage;++ it('shows the edited text as the preview', async () => {+ const adapter = await sendLast();+ await adapter.editMessage('[email protected]', 'OUT_LATER', 'arriving tomorrow');+ expect(await preview(adapter)).toBe('arriving tomorrow');+ });++ it.each([+ ['for everyone', true],+ ['for the account', false],+ ])('no longer shows the text once it is deleted %s', async (_label, forEveryone) => {+ const adapter = await sendLast();+ await adapter.deleteMessage('[email protected]', 'OUT_LATER', forEveryone);+ expect(await preview(adapter)).toBe('');+ });+ });+it('clears the store on logout', async () => {const adapter = await ready();await adapter.logout();