Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(messages): synchronize edited messages in real time

Carlos Rogerio Orioli4ca9589d258a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 923e9a890..f81401c37 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- Live message-edit support now emits `message.edited` through webhooks and WebSocket subscriptions on
+ both engines, updates the stored message and Chats dashboard in occurrence order, and exposes the
+ standard sender/direction/type/media/mention fields to webhook smart filters. Existing wildcard (`*`)
+ subscriptions receive the new event automatically. Thanks @rogeriorioli. (#734)
+
### Changed
- `GET /api/settings` no longer returns the incorrect, always-zero `general.sessionTimeout` field. Clients
diff --git a/dashboard/src/hooks/useWebSocket.ts b/dashboard/src/hooks/useWebSocket.ts
index e42781bb5..e64e48851 100644
--- a/dashboard/src/hooks/useWebSocket.ts
+++ b/dashboard/src/hooks/useWebSocket.ts
@@ -41,6 +41,14 @@ interface MessageReactionEvent {
timestamp: string;
}
+interface MessageEditedEvent {
+ sessionId: string;
+ messageId: string;
+ chatId: string;
+ body: string;
+ timestamp: number;
+}
+
interface MessageRevokedEvent {
sessionId: string;
id: string;
@@ -64,6 +72,7 @@ interface WebSocketEvents {
onMessageAck?: (event: MessageAckEvent) => void;
onMessageReaction?: (event: MessageReactionEvent) => void;
onMessageRevoked?: (event: MessageRevokedEvent) => void;
+ onMessageEdited?: (event: MessageEditedEvent) => void;
}
// Shape of the server -> client event envelope produced by the NestJS gateway.
@@ -234,6 +243,25 @@ export function useWebSocket(events: WebSocketEvents = {}) {
timestamp: Number(data.timestamp),
});
break;
+ case 'message.edited':
+ // Keep optional/malformed wire fields from becoming the truthy strings "undefined"/"null"
+ // and accidentally matching an unrelated cached row.
+ if (
+ typeof data.messageId !== 'string' ||
+ !data.messageId ||
+ typeof data.chatId !== 'string' ||
+ typeof data.body !== 'string'
+ ) {
+ break;
+ }
+ events.onMessageEdited?.({
+ sessionId,
+ messageId: data.messageId,
+ chatId: data.chatId,
+ body: data.body,
+ timestamp: Number(data.timestamp),
+ });
+ break;
default:
break;
}
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index c1a4eff89..03d9a963c 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -26,7 +26,12 @@ import {
type MessageType,
type SearchHit,
} from '../services/api';
-import { mergeDeliveryStatus, findRevokedIndex, type ChatMessageView } from '../utils/chatMessages';
+import {
+ applyMessageEdit,
+ mergeDeliveryStatus,
+ findRevokedIndex,
+ type ChatMessageView,
+} from '../utils/chatMessages';
import { useWebSocket } from '../hooks/useWebSocket';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { useRole } from '../hooks/useRole';
@@ -352,11 +357,48 @@ export function Chats() {
[selectedSessionId, queryClient],
);
+ const handleIncomingMessageEdited = useCallback(
+ (event: { sessionId: string; messageId: string; chatId: string; body: string }) => {
+ if (event.sessionId !== selectedSessionId) return;
+
+ const caches = queryClient.getQueriesData<ChatMessageView[]>({
+ queryKey: ['messages', event.sessionId],
+ });
+ let matchedCachedMessage = false;
+ let editedLastMessage = false;
+ for (const [key, list] of caches) {
+ if (!list) continue;
+ const next = applyMessageEdit(list, event);
+ if (next === list) continue;
+ matchedCachedMessage = true;
+ queryClient.setQueryData(key, next);
+
+ // Message caches are chronological; only editing the final row changes the sidebar preview.
+ // Confirm the cache belongs to the event chat before touching that summary.
+ const cachedChatId = Array.isArray(key) && typeof key[2] === 'string' ? key[2] : undefined;
+ const editedIndex = list.findIndex(m => m.id === event.messageId || m.waMessageId === event.messageId);
+ if (cachedChatId === event.chatId && editedIndex === list.length - 1) editedLastMessage = true;
+ }
+ if (editedLastMessage) {
+ setChats(previous =>
+ previous.map(chat => (chat.id === event.chatId ? { ...chat, lastMessage: event.body } : chat)),
+ );
+ } else if (!matchedCachedMessage) {
+ // The chat may never have been opened, so there is no message cache from which to prove
+ // whether this was its latest row. Refresh summaries instead of guessing and overwriting the
+ // sidebar with the body of an older edited message.
+ void loadChats(selectedSessionId);
+ }
+ },
+ [selectedSessionId, queryClient, loadChats],
+ );
+
const { isConnected, connectionFailed, reconnect, subscribe, unsubscribe } = useWebSocket({
onMessage: handleIncomingMessage,
onMessageAck: handleIncomingMessageAck,
onMessageReaction: handleIncomingMessageReaction,
onMessageRevoked: handleIncomingMessageRevoked,
+ onMessageEdited: handleIncomingMessageEdited,
});
// A transient WebSocket gap means message.received/ack/revoke events were missed, and the chat
@@ -386,6 +428,7 @@ export function Chats() {
'message.ack',
'message.reaction',
'message.revoked',
+ 'message.edited',
]);
return () => {
unsubscribe(selectedSessionId);
diff --git a/dashboard/src/pages/Webhooks.tsx b/dashboard/src/pages/Webhooks.tsx
index d3e1caa07..3242a862f 100644
--- a/dashboard/src/pages/Webhooks.tsx
+++ b/dashboard/src/pages/Webhooks.tsx
@@ -95,6 +95,7 @@ const availableEventNames = [
'message.failed',
'message.revoked',
'message.reaction',
+ 'message.edited',
'session.status',
'session.qr',
'session.authenticated',
diff --git a/dashboard/src/utils/chatMessages.test.ts b/dashboard/src/utils/chatMessages.test.ts
index 0d090d1ae..298dcdbcd 100644
--- a/dashboard/src/utils/chatMessages.test.ts
+++ b/dashboard/src/utils/chatMessages.test.ts
@@ -92,6 +92,7 @@ import {
updateMessageById,
removeMessageById,
findRevokedIndex,
+ applyMessageEdit,
type ChatMessageView,
} from './chatMessages.ts';
@@ -233,3 +234,24 @@ test('findRevokedIndex ignores an undefined revokedId rather than matching a row
const list = [msg({ id: 'row-1', waMessageId: undefined })];
assert.equal(findRevokedIndex(list, { id: 'REVOKE_NOTIF' }), -1);
});
+
+test('applyMessageEdit updates a persisted row by waMessageId without mutating the input', () => {
+ const before = [msg({ id: 'row-uuid', waMessageId: 'WA_EDIT_1', body: 'old' })];
+ const after = applyMessageEdit(before, { messageId: 'WA_EDIT_1', body: 'new' });
+
+ assert.notEqual(after, before);
+ assert.equal(after[0].body, 'new');
+ assert.equal(before[0].body, 'old');
+});
+
+test('applyMessageEdit updates a live row by id', () => {
+ const before = [msg({ id: 'WA_EDIT_1', waMessageId: undefined, body: 'old' })];
+ const after = applyMessageEdit(before, { messageId: 'WA_EDIT_1', body: '' });
+ assert.equal(after[0].body, '');
+});
+
+test('applyMessageEdit is a referential no-op for an empty or unknown target id', () => {
+ const before = [msg({ id: 'm-1', body: 'old' })];
+ assert.equal(applyMessageEdit(before, { messageId: '', body: 'new' }), before);
+ assert.equal(applyMessageEdit(before, { messageId: 'missing', body: 'new' }), before);
+});
diff --git a/dashboard/src/utils/chatMessages.ts b/dashboard/src/utils/chatMessages.ts
index bcee2bdfd..d70b8d4ab 100644
--- a/dashboard/src/utils/chatMessages.ts
+++ b/dashboard/src/utils/chatMessages.ts
@@ -166,3 +166,20 @@ export function findRevokedIndex(
m => matches(m, event.id) || (event.revokedId !== undefined && matches(m, event.revokedId)),
);
}
+
+/**
+ * Replace the displayed body of a cached WhatsApp message after a `message.edited` event. Persisted
+ * rows use a local UUID in `id` and the WhatsApp identity in `waMessageId`; live rows often use the
+ * WhatsApp identity for both, so both candidates are required. Returns the original array on a miss.
+ */
+export function applyMessageEdit(
+ list: ChatMessageView[],
+ event: { messageId: string; body: string },
+): ChatMessageView[] {
+ if (!event.messageId) return list;
+ const idx = list.findIndex(m => m.id === event.messageId || m.waMessageId === event.messageId);
+ if (idx === -1) return list;
+ const next = list.slice();
+ next[idx] = { ...next[idx], body: event.body };
+ return next;
+}
diff --git a/docs/05-database-design.md b/docs/05-database-design.md
index 1c52d3288..9b493bb6c 100644
--- a/docs/05-database-design.md
+++ b/docs/05-database-design.md
@@ -353,8 +353,10 @@ CREATE TABLE webhooks (
"message.received",
"message.sent",
"message.ack",
+ "message.failed",
"message.revoked",
"message.reaction",
+ "message.edited",
"session.status",
"session.qr",
"session.authenticated",
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 78875b969..1143112a5 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -4598,6 +4598,7 @@ message.sent
message.ack
message.revoked
message.reaction
+message.edited
session.status
session.qr
session.authenticated
@@ -4670,7 +4671,7 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve
| `message.failed` | A receipt resolves to `failed` (dispatched in addition to `message.ack`) | `{ id, messageId, status: "failed", ack: -1 }` |
| `message.revoked` | A message is deleted/recalled | `{ id, revokedId?, chatId, from, to, type: "revoked", body: "", timestamp }` — **reconcile on `revokedId`** (the original deleted message's id), falling back to `id`. On whatsapp-web.js `id` is the *revocation notification* (a distinct message that won't match a stored id) and `revokedId` may be absent when the original isn't cached locally; on Baileys the two coincide |
| `message.reaction` | A reaction is added, changed, or removed | `{ messageId, chatId, reaction, senderId, reactions }` — `reactions` is the post-apply `{ senderId: emoji }` snapshot; `reaction` is empty when removed |
-| `message.edited` | A message is edited | `{ messageId, chatId, body, senderId, timestamp }` — `messageId` is the original message id, `body` contains the newly edited text |
+| `message.edited` | A message body or media caption is edited | `{ messageId, chatId, body, senderId, from, to, fromMe, isGroup, type, hasMedia, author?, mentionedIds?, timestamp }` — `messageId` is the original message id, `body` is the latest text/caption, and `timestamp` is the edit occurrence time in epoch **seconds** (not the original creation time) |
| `session.qr` | A new pairing QR is generated | `{ sessionId, qr }` (raw QR string) |
| `session.authenticated` | The session pairs and becomes ready | `{ sessionId, phone, pushName }` |
| `session.disconnected` | The session disconnects | `{ sessionId, reason }` |
diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.md
index 8924c0f7e..271323ea8 100644
--- a/docs/12-troubleshooting-faq.md
+++ b/docs/12-troubleshooting-faq.md
@@ -989,6 +989,7 @@ available_events:
- message.failed # Receipt resolved to failed
- message.revoked # Message deleted
- message.reaction # Reaction added, changed, or removed
+ - message.edited # Message body or media caption edited
# Session
- session.status # Session status change
diff --git a/docs/22-n8n-integration.md b/docs/22-n8n-integration.md
index 16bb859ae..58ff7eab9 100644
--- a/docs/22-n8n-integration.md
+++ b/docs/22-n8n-integration.md
@@ -81,6 +81,7 @@ Start workflows when WhatsApp events occur.
| `message.failed` | Outgoing message failed | Failure alerting |
| `message.revoked` | Message deleted for everyone | Deletion tracking |
| `message.reaction` | Reaction added / changed / removed | Reaction tracking |
+| `message.edited` | Message body or caption edited | Content synchronization |
| `session.status` | Session status changed | Lifecycle tracking |
| `session.qr` | QR code generated | Reconnection alerts |
| `session.authenticated` | Session logged in (phone available) | Startup notifications |
diff --git a/src/engine/adapters/baileys-session-store.spec.ts b/src/engine/adapters/baileys-session-store.spec.ts
index 36a08c124..309b0a339 100644
--- a/src/engine/adapters/baileys-session-store.spec.ts
+++ b/src/engine/adapters/baileys-session-store.spec.ts
@@ -67,6 +67,21 @@ describe('BaileysSessionStore', () => {
expect(store.lastMessage('[email protected]')?.key.id).toBe('NEW');
});
+ it('updates the chat preview only when the edited message is the current last message', () => {
+ store.upsertChats([{ id: '[email protected]', name: 'Alice' }]);
+ store.recordMessage({
+ key: { remoteJid: '[email protected]', id: 'LATEST' },
+ message: { conversation: 'before edit' },
+ messageTimestamp: 200,
+ });
+
+ store.recordMessageEdit('[email protected]', 'OLDER', 'must not replace preview');
+ expect(store.listChats()[0]).toEqual(expect.objectContaining({ lastMessage: 'before edit', timestamp: 200 }));
+
+ store.recordMessageEdit('[email protected]', 'LATEST', 'after edit');
+ expect(store.listChats()[0]).toEqual(expect.objectContaining({ lastMessage: 'after edit', timestamp: 200 }));
+ });
+
it('flags a group chat by jid', () => {
store.upsertChats([{ id: '[email protected]', name: 'Grp' }]);
expect(store.listChats()[0].isGroup).toBe(true);
diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.ts
index 8fbf50f15..eec4385e6 100644
--- a/src/engine/adapters/baileys-session-store.ts
+++ b/src/engine/adapters/baileys-session-store.ts
@@ -129,6 +129,18 @@ export class BaileysSessionStore {
this.lastMessages.set(chatId, { key: msg.key, timestamp, text });
}
+ /**
+ * Refresh the chat preview when (and only when) the edited message is still the latest message in
+ * that chat. Editing an older message must not replace the preview or reorder the conversation.
+ */
+ recordMessageEdit(chatId: string, messageId: string, text: string): void {
+ if (!messageId) return;
+ const rawChatId = this.lastMessages.has(chatId) ? chatId : this.toEngineJid(chatId);
+ const existing = this.lastMessages.get(rawChatId);
+ if (!existing || existing.key.id !== messageId) return;
+ this.lastMessages.set(rawChatId, { ...existing, text });
+ }
+
/**
* Cache a positive disappearing-messages timer learned from an inbound message under both the raw chat
* JID and its neutral form, so {@link getEphemeralExpiration} hits regardless of which dialect the caller
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 9fb24f4b4..be2c92435 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -90,7 +90,7 @@ jest.mock('@whiskeysockets/baileys', () => ({
}));
import { BaileysAdapter } from './baileys.adapter';
-import { EngineStatus, EngineEventCallbacks } from '../interfaces/whatsapp-engine.interface';
+import { EditedMessage, EngineStatus, EngineEventCallbacks } from '../interfaces/whatsapp-engine.interface';
import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';
import { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';
@@ -124,6 +124,13 @@ const newAdapter = (): BaileysAdapter =>
const noopCallbacks = (over: Partial<EngineEventCallbacks> = {}): EngineEventCallbacks => over;
+function firstEditedMessage(callback: jest.Mock): EditedMessage {
+ const calls = callback.mock.calls as Array<[EditedMessage]>;
+ const first = calls[0];
+ if (!first) throw new Error('Expected an edited-message callback');
+ return first[0];
+}
+
describe('BaileysAdapter lifecycle & status', () => {
beforeEach(() => {
fakeSock.user = undefined;
@@ -1453,7 +1460,7 @@ describe('BaileysAdapter inbound fan-out', () => {
it('EDIT protocolMessage: fires onMessageEdited and NOT onMessage', async () => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const baileys = jest.requireMock('@whiskeysockets/baileys') as { getContentType: jest.Mock };
- baileys.getContentType.mockReturnValue('protocolMessage');
+ baileys.getContentType.mockReturnValueOnce('protocolMessage').mockReturnValueOnce('conversation');
const onMessage = jest.fn();
const onMessageEdited = jest.fn();
@@ -1463,15 +1470,21 @@ describe('BaileysAdapter inbound fan-out', () => {
type: 'notify',
messages: [
{
- key: { remoteJid: '[email protected]', participant: '[email protected]', fromMe: false, id: 'PROTO_EDIT' },
+ key: {
+ remoteJid: '[email protected]',
+ participant: '[email protected]',
+ fromMe: false,
+ id: 'PROTO_EDIT',
+ },
message: {
protocolMessage: {
key: { id: 'ORIGINAL_MSG_ID' },
type: 14, // MESSAGE_EDIT
+ timestampMs: 1700000030123,
editedMessage: { conversation: 'New edited message text' },
},
},
- messageTimestamp: 1700000030,
+ messageTimestamp: 1700000000,
},
],
});
@@ -1480,24 +1493,25 @@ describe('BaileysAdapter inbound fan-out', () => {
expect(onMessageEdited).toHaveBeenCalledTimes(1);
expect(fakeStore.put).not.toHaveBeenCalled();
- const edited = onMessageEdited.mock.calls[0][0] as {
- messageId: string;
- chatId: string;
- body: string;
- senderId: string;
- timestamp: number;
- };
- expect(edited.messageId).toBe('ORIGINAL_MSG_ID');
- expect(edited.chatId).toBe('[email protected]');
- expect(edited.body).toBe('New edited message text');
- expect(edited.senderId).toBe('[email protected]');
- expect(edited.timestamp).toBe(1700000030);
+ expect(firstEditedMessage(onMessageEdited)).toEqual({
+ messageId: 'ORIGINAL_MSG_ID',
+ chatId: '[email protected]',
+ body: 'New edited message text',
+ senderId: '[email protected]',
+ fromMe: false,
+ isGroup: false,
+ type: 'text',
+ hasMedia: false,
+ timestamp: 1700000030,
+ });
});
it('EDIT protocolMessage: extracts media caption correctly (e.g. image caption)', async () => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const baileys = jest.requireMock('@whiskeysockets/baileys') as { getContentType: jest.Mock };
- baileys.getContentType.mockReturnValue('protocolMessage');
+ baileys.getContentType.mockReturnValueOnce('protocolMessage').mockReturnValueOnce('imageMessage');
const onMessage = jest.fn();
const onMessageEdited = jest.fn();
@@ -1507,7 +1521,12 @@ describe('BaileysAdapter inbound fan-out', () => {
type: 'notify',
messages: [
{
- key: { remoteJid: '[email protected]', participant: '[email protected]', fromMe: false, id: 'PROTO_EDIT_MEDIA' },
+ key: {
+ remoteJid: '[email protected]',
+ participant: '[email protected]',
+ fromMe: false,
+ id: 'PROTO_EDIT_MEDIA',
+ },
message: {
protocolMessage: {
key: { id: 'ORIGINAL_MSG_ID' },
@@ -1525,24 +1544,20 @@ describe('BaileysAdapter inbound fan-out', () => {
expect(onMessage).not.toHaveBeenCalled();
expect(onMessageEdited).toHaveBeenCalledTimes(1);
- const edited = onMessageEdited.mock.calls[0][0] as {
- messageId: string;
- chatId: string;
- body: string;
- senderId: string;
- timestamp: number;
- };
+ const edited = firstEditedMessage(onMessageEdited);
expect(edited.messageId).toBe('ORIGINAL_MSG_ID');
expect(edited.chatId).toBe('[email protected]');
expect(edited.body).toBe('Edited image caption text');
expect(edited.senderId).toBe('[email protected]');
expect(edited.timestamp).toBe(1700000035);
+ expect(edited.type).toBe('image');
+ expect(edited.hasMedia).toBe(true);
});
it('EDIT protocolMessage: correctly maps senderId for own outgoing edits (fromMe = true)', async () => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const baileys = jest.requireMock('@whiskeysockets/baileys') as { getContentType: jest.Mock };
- baileys.getContentType.mockReturnValue('protocolMessage');
+ baileys.getContentType.mockReturnValueOnce('protocolMessage').mockReturnValueOnce('conversation');
fakeSock.user = { id: '628999:[email protected]', name: 'Me' };
const onMessage = jest.fn();
@@ -1569,18 +1584,64 @@ describe('BaileysAdapter inbound fan-out', () => {
expect(onMessage).not.toHaveBeenCalled();
expect(onMessageEdited).toHaveBeenCalledTimes(1);
- const edited = onMessageEdited.mock.calls[0][0] as {
- messageId: string;
- chatId: string;
- body: string;
- senderId: string;
- timestamp: number;
- };
+ const edited = firstEditedMessage(onMessageEdited);
expect(edited.messageId).toBe('ORIGINAL_MSG_ID');
expect(edited.chatId).toBe('[email protected]');
expect(edited.body).toBe('Self-edited text');
expect(edited.senderId).toBe('[email protected]');
expect(edited.timestamp).toBe(1700000040);
+ expect(edited.from).toBe('[email protected]');
+ expect(edited.to).toBe('[email protected]');
+ expect(edited.fromMe).toBe(true);
+ });
+
+ it('EDIT protocolMessage: normalizes group author and mentions for webhook filters', async () => {
+ baileys.getContentType.mockReturnValueOnce('protocolMessage').mockReturnValueOnce('extendedTextMessage');
+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };
+
+ const onMessageEdited = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize({ onMessageEdited });
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [
+ {
+ key: {
+ remoteJid: '[email protected]',
+ participant: '[email protected]',
+ fromMe: false,
+ id: 'PROTO_EDIT_GROUP',
+ },
+ message: {
+ protocolMessage: {
+ key: { id: 'GROUP_MSG_ID' },
+ type: 14,
+ editedMessage: {
+ extendedTextMessage: {
+ text: 'Hello @628222',
+ contextInfo: { mentionedJid: ['[email protected]'] },
+ },
+ },
+ },
+ },
+ messageTimestamp: 1700000045,
+ },
+ ],
+ });
+ await new Promise(resolve => setImmediate(resolve));
+
+ expect(firstEditedMessage(onMessageEdited)).toEqual(
+ expect.objectContaining({
+ chatId: '[email protected]',
+ senderId: '[email protected]',
+ author: '[email protected]',
+ mentionedIds: ['[email protected]'],
+ isGroup: true,
+ type: 'text',
+ }),
+ );
});
it('reactionMessage: fires onMessageReaction and NOT onMessage', async () => {
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 48805d1d6..142f8e817 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -4,6 +4,7 @@ import * as qrcode from 'qrcode';
import type * as BaileysLib from '@whiskeysockets/baileys';
import type { AnyMessageContent, MiscMessageGenerationOptions, WAMessage, WASocket } from '@whiskeysockets/baileys';
import { buildIncomingMessageFromBaileys, extractBaileysBody, mapBaileysStatus } from './baileys-message-mapper';
+import { buildEditedMessage } from './message-mapper';
import { mapBaileysGroup, mapBaileysGroupInfo } from './baileys-group-mapper';
import type { ILogger } from '@whiskeysockets/baileys/lib/Utils/logger.js';
import {
@@ -1103,16 +1104,44 @@ export class BaileysAdapter implements IWhatsAppEngine {
return;
}
if (pm?.type === b.proto.Message.ProtocolMessage.Type.MESSAGE_EDIT) {
- const body = extractBaileysBody(pm.editedMessage ?? {});
- const edited: EditedMessage = {
- messageId: pm.key?.id ?? '',
- chatId: this.sessionStore.toNeutralJid(remoteJid),
- body,
- senderId: this.sessionStore.toNeutralJid(
- msg.key.fromMe === true ? this.normalizedSelfJid() : (msg.key.participant ?? remoteJid),
- ),
- timestamp: this.toUnixSeconds(msg.messageTimestamp),
- };
+ // MESSAGE_EDIT wraps the message's latest content. Normalize that INNER content separately
+ // so captions, type, PTT, media presence and mentions describe the edited value rather than
+ // the outer protocol envelope.
+ const normalizedEdited = b.normalizeMessageContent(pm.editedMessage ?? undefined) ?? pm.editedMessage ?? {};
+ const editedContentType = b.getContentType(normalizedEdited);
+ const editedSubMessage =
+ normalizedEdited.extendedTextMessage ??
+ normalizedEdited.imageMessage ??
+ normalizedEdited.videoMessage ??
+ normalizedEdited.audioMessage ??
+ normalizedEdited.documentMessage ??
+ normalizedEdited.stickerMessage ??
+ normalizedEdited.locationMessage;
+ const contextInfo = editedSubMessage?.contextInfo;
+ const base = buildIncomingMessageFromBaileys(
+ {
+ id: pm.key?.id ?? '',
+ remoteJid,
+ fromMe: msg.key.fromMe === true,
+ participant: msg.key.participant ?? undefined,
+ body: extractBaileysBody(normalizedEdited),
+ contentType: editedContentType,
+ isPtt: normalizedEdited.audioMessage?.ptt === true,
+ timestamp: this.toEditUnixSeconds(pm.timestampMs, msg.messageTimestamp),
+ selfJid: this.normalizedSelfJid(),
+ mentionedJids: contextInfo?.mentionedJid ?? undefined,
+ },
+ jid => this.sessionStore.toNeutralJid(jid),
+ );
+ const hasMedia =
+ editedContentType === 'imageMessage' ||
+ editedContentType === 'videoMessage' ||
+ editedContentType === 'audioMessage' ||
+ editedContentType === 'documentMessage' ||
+ editedContentType === 'documentWithCaptionMessage' ||
+ editedContentType === 'stickerMessage';
+ const edited: EditedMessage = buildEditedMessage(base, hasMedia);
+ this.sessionStore.recordMessageEdit(remoteJid, edited.messageId, edited.body);
this.callbacks.onMessageEdited?.(edited);
return;
}
@@ -1514,6 +1543,16 @@ export class BaileysAdapter implements IWhatsAppEngine {
return typeof ts === 'number' ? ts : ts.toNumber();
}
+ /** Protocol-message edit timestamps are milliseconds; the enclosing message timestamp is seconds. */
+ private toEditUnixSeconds(
+ timestampMs: number | { toNumber(): number } | null | undefined,
+ fallback: number | { toNumber(): number } | null | undefined,
+ ): number {
+ if (timestampMs == null) return this.toUnixSeconds(fallback);
+ const milliseconds = typeof timestampMs === 'number' ? timestampMs : timestampMs.toNumber();
+ return Number.isFinite(milliseconds) ? Math.floor(milliseconds / 1000) : this.toUnixSeconds(fallback);
+ }
+
/** Resolve a MediaInput's data (Buffer | base64 string | http(s) URL) to bytes + mimetype. */
private async resolveMediaBuffer(media: MediaInput): Promise<{ data: Buffer; mimetype: string }> {
if (Buffer.isBuffer(media.data)) {
diff --git a/src/engine/adapters/message-mapper.ts b/src/engine/adapters/message-mapper.ts
index 12ea1d0eb..d37d9b7e1 100644
--- a/src/engine/adapters/message-mapper.ts
+++ b/src/engine/adapters/message-mapper.ts
@@ -1,4 +1,4 @@
-import { IncomingMessage, MessageContact, MessageType } from '../interfaces/whatsapp-engine.interface';
+import { EditedMessage, IncomingMessage, MessageContact, MessageType } from '../interfaces/whatsapp-engine.interface';
import type { SerializedWid } from '../types/whatsapp-web-js.types';
/**
@@ -126,6 +126,28 @@ export function buildIncomingMessageBase(msg: RawMessageFields): IncomingMessage
return incoming;
}
+/**
+ * Project an engine-neutral message base into the public edit-event contract. Keeping this projection
+ * shared prevents the two adapters from drifting on identity, direction, group, type, or filter fields.
+ */
+export function buildEditedMessage(message: IncomingMessage, hasMedia: boolean): EditedMessage {
+ return {
+ messageId: message.id,
+ chatId: message.chatId,
+ body: message.body,
+ senderId: message.author ?? message.from,
+ from: message.from,
+ to: message.to,
+ fromMe: message.fromMe,
+ isGroup: message.isGroup,
+ type: message.type,
+ hasMedia,
+ ...(message.author ? { author: message.author } : {}),
+ ...(message.mentionedIds ? { mentionedIds: message.mentionedIds } : {}),
+ timestamp: message.timestamp,
+ };
+}
+
/**
* The subset of whatsapp-web.js `Contact` properties we read synchronously (already on the resolved
* contact, no network call). Declared explicitly so {@link mapContactFields} is unit-testable without a
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index a1ba3b20e..0a7b20333 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -19,7 +19,7 @@ import { InternalServerErrorException, UnprocessableEntityException } from '@nes
import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
import { ChannelNotFoundError } from '../../common/errors/channel-not-found.error';
import { ChannelMediaNotSupportedError } from '../../common/errors/channel-media-not-supported.error';
-import { EngineStatus } from '../interfaces/whatsapp-engine.interface';
+import { EditedMessage, EngineStatus } from '../interfaces/whatsapp-engine.interface';
import { SsrfBlockedError } from '../../common/security/ssrf-guard';
import { fetch as undiciFetch } from 'undici';
@@ -1647,33 +1647,47 @@ describe('WhatsAppWebJsAdapter message_edit', () => {
it('emits onMessageEdited with the new body and mapped fields', () => {
const { onMessageEdited, client } = wireEditHandler();
-
- client.emit(
- 'message_edit',
- {
- id: { _serialized: 'MSG_EDIT_1' },
- author: '[email protected]',
- timestamp: 1700000080,
- },
- 'Edited new text',
- 'Old text',
- );
+ const now = jest.spyOn(Date, 'now').mockReturnValue(1700000089123);
+
+ try {
+ client.emit(
+ 'message_edit',
+ {
+ id: { _serialized: 'MSG_EDIT_1' },
+ author: '[email protected]',
+ body: 'Old text',
+ type: 'chat',
+ fromMe: false,
+ hasMedia: false,
+ mentionedIds: ['[email protected]'],
+ timestamp: 1700000080,
+ },
+ 'Edited new text',
+ 'Old text',
+ );
+ } finally {
+ now.mockRestore();
+ }
expect(onMessageEdited).toHaveBeenCalledTimes(1);
- const edited = onMessageEdited.mock.calls[0][0] as {
- messageId: string;
- chatId: string;
- body: string;
- senderId: string;
- timestamp: number;
- };
- expect(edited.messageId).toBe('MSG_EDIT_1');
- expect(edited.chatId).toBe('[email protected]');
- expect(edited.body).toBe('Edited new text');
- expect(edited.senderId).toBe('[email protected]');
- expect(edited.timestamp).toBe(1700000080);
+ const calls = onMessageEdited.mock.calls as Array<[EditedMessage]>;
+ expect(calls[0][0]).toEqual({
+ messageId: 'MSG_EDIT_1',
+ chatId: '[email protected]',
+ body: 'Edited new text',
+ senderId: '[email protected]',
+ fromMe: false,
+ isGroup: false,
+ type: 'text',
+ hasMedia: false,
+ author: '[email protected]',
+ mentionedIds: ['[email protected]'],
+ timestamp: 1700000089,
+ });
});
});
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 3c218e7b7..595888cfd 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -56,7 +56,7 @@ import {
GroupCreateResult,
SerializedWid,
} from '../types/whatsapp-web-js.types';
-import { buildIncomingMessageBase, mapContactFields } from './message-mapper';
+import { buildEditedMessage, buildIncomingMessageBase, mapContactFields } from './message-mapper';
import { buildVCard } from './vcard';
import {
capInboundMedia,
@@ -692,15 +692,24 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
}
});
- this.client.on('message_edit', (message, newBody, prevBody) => {
+ this.client.on('message_edit', (message, newBody) => {
try {
- const payload: EditedMessage = {
- messageId: message.id._serialized,
- chatId: message.from === this.client?.info?.wid?._serialized ? message.to : message.from,
+ // whatsapp-web.js keeps `message.timestamp` at the ORIGINAL creation time. Consumers need
+ // occurrence time for ordering multiple edits, so stamp the edit at receipt and project the
+ // otherwise-normal message fields through the same adapter mapper used by inbound messages.
+ const editTimestamp = Math.floor(Date.now() / 1000);
+ const base = buildIncomingMessageBase({
+ id: message.id,
+ from: message.from,
+ to: message.to,
body: String(newBody),
- senderId: message.author || message.from,
- timestamp: message.timestamp,
- };
+ type: message.type,
+ timestamp: editTimestamp,
+ fromMe: message.fromMe,
+ author: message.author,
+ mentionedIds: message.mentionedIds,
+ });
+ const payload: EditedMessage = buildEditedMessage(base, Boolean(message.hasMedia));
this.callbacks.onMessageEdited?.(payload);
} catch (error) {
this.logger.error('Error processing message_edit', String(error));
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index 61de16908..60f5ac73c 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -386,6 +386,17 @@ export interface EditedMessage {
chatId: string;
body: string;
senderId: string;
+ from: string;
+ to: string;
+ fromMe: boolean;
+ isGroup: boolean;
+ type: MessageType;
+ hasMedia: boolean;
+ /** For group messages, the participant that authored the edited message. */
+ author?: string;
+ /** WIDs mentioned by the edited message's latest content. */
+ mentionedIds?: string[];
+ /** Unix seconds when the edit occurred (not the original message creation time). */
timestamp: number;
}
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 2d162d0d6..cf825b513 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -119,6 +119,7 @@ describe('SessionService', () => {
emitMessageAck: jest.fn(),
emitMessageRevoked: jest.fn(),
emitMessageReaction: jest.fn(),
+ emitMessageEdited: jest.fn(),
emitQRCode: jest.fn(),
};
@@ -1533,7 +1534,7 @@ describe('SessionService', () => {
for (let i = 0; i < 3; i++) await flush();
- const chains = (service as unknown as { reactionChains: Map<string, unknown> }).reactionChains;
+ const chains = (service as unknown as { messageMutationChains: Map<string, unknown> }).messageMutationChains;
expect(chains.size).toBe(0);
});
@@ -2596,35 +2597,52 @@ describe('SessionService', () => {
// ── onMessageEdited ───────────────────────────────────────────────
describe('onMessageEdited callback', () => {
- it('updates body and emits message.edited event', async () => {
+ const startAndCaptureEditCallback = async (): Promise<NonNullable<EngineEventCallbacks['onMessageEdited']>> => {
const session = createMockSession();
(repository.findOne as jest.Mock).mockResolvedValue(session);
(repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
- (messageRepository.update as jest.Mock).mockResolvedValue({ affected: 1 });
-
await service.start('sess-uuid-1');
-
const initializeCall = mockEngine.initialize.mock.calls[0] as unknown[];
- const callbacks = initializeCall[0] as {
- onMessageEdited: (m: { messageId: string; chatId: string; body: string; senderId: string; timestamp: number }) => void;
- };
+ const callbacks = initializeCall[0] as EngineEventCallbacks;
+ return callbacks.onMessageEdited!;
+ };
- const edited = {
- messageId: 'WA_MSG_EDIT_1',
- chatId: '[email protected]',
- body: 'New edited text',
- senderId: '[email protected]',
- timestamp: 1700000005,
- };
+ const edited = (body = 'New edited text') => ({
+ messageId: 'WA_MSG_EDIT_1',
+ chatId: '[email protected]',
+ body,
+ senderId: '[email protected]',
+ fromMe: false,
+ isGroup: false,
+ type: 'text' as const,
+ hasMedia: false,
+ timestamp: 1700000005,
+ });
+
+ it('persists the body before emitting the WebSocket and webhook event', async () => {
+ let releaseUpdate!: () => void;
+ (messageRepository.update as jest.Mock).mockImplementationOnce(
+ () =>
+ new Promise(resolve => {
+ releaseUpdate = () => resolve({ affected: 1 });
+ }),
+ );
+ const onMessageEdited = await startAndCaptureEditCallback();
- callbacks.onMessageEdited(edited);
- await Promise.resolve();
- await Promise.resolve();
+ onMessageEdited(edited());
+ await new Promise(resolve => setImmediate(resolve));
expect(messageRepository.update).toHaveBeenCalledWith(
{ sessionId: 'sess-uuid-1', waMessageId: 'WA_MSG_EDIT_1' },
{ body: 'New edited text' },
);
+ expect(eventsGateway.emitMessageEdited).not.toHaveBeenCalled();
+ expect(webhookService.dispatch).not.toHaveBeenCalledWith('sess-uuid-1', 'message.edited', expect.anything());
+
+ releaseUpdate();
+ await new Promise(resolve => setImmediate(resolve));
expect(webhookService.dispatch).toHaveBeenCalledWith(
'sess-uuid-1',
@@ -2643,6 +2661,58 @@ describe('SessionService', () => {
}),
);
});
+
+ it('serializes rapid edits so the latest body cannot be overwritten by an older slow update', async () => {
+ const releases: Array<() => void> = [];
+ (messageRepository.update as jest.Mock).mockImplementation(
+ () =>
+ new Promise(resolve => {
+ releases.push(() => resolve({ affected: 1 }));
+ }),
+ );
+ const onMessageEdited = await startAndCaptureEditCallback();
+
+ onMessageEdited(edited('first edit'));
+ onMessageEdited(edited('second edit'));
+ await new Promise(resolve => setImmediate(resolve));
+
+ expect(messageRepository.update).toHaveBeenCalledTimes(1);
+ expect(eventsGateway.emitMessageEdited).not.toHaveBeenCalled();
+
+ releases[0]();
+ await new Promise(resolve => setImmediate(resolve));
+ expect(messageRepository.update).toHaveBeenCalledTimes(2);
+ expect(eventsGateway.emitMessageEdited).toHaveBeenCalledTimes(1);
+
+ releases[1]();
+ await new Promise(resolve => setImmediate(resolve));
+ const payloads = (eventsGateway.emitMessageEdited as jest.Mock).mock.calls.map(
+ call => (call as [string, { body: string }])[1].body,
+ );
+ expect(payloads).toEqual(['first edit', 'second edit']);
+ });
+
+ it('drops an edit with no target id before any persistence or notification', async () => {
+ const onMessageEdited = await startAndCaptureEditCallback();
+
+ onMessageEdited({ ...edited(), messageId: '' });
+ await new Promise(resolve => setImmediate(resolve));
+
+ expect(messageRepository.update).not.toHaveBeenCalled();
+ expect(eventsGateway.emitMessageEdited).not.toHaveBeenCalled();
+ expect(webhookService.dispatch).not.toHaveBeenCalledWith('sess-uuid-1', 'message.edited', expect.anything());
+ });
+
+ it('still reports a real edit occurrence when the best-effort database update fails', async () => {
+ (messageRepository.update as jest.Mock).mockRejectedValueOnce(new Error('database unavailable'));
+ const onMessageEdited = await startAndCaptureEditCallback();
+
+ onMessageEdited(edited());
+ await new Promise(resolve => setImmediate(resolve));
+
+ expect(eventsGateway.emitMessageEdited).toHaveBeenCalledTimes(1);
+ expect(webhookService.dispatch).toHaveBeenCalledWith('sess-uuid-1', 'message.edited', edited());
+ });
});
// ── getActiveCount / isActive ─────────────────────────────────────
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index b0dec0c6a..edba9a33e 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -36,6 +36,7 @@ import {
DeliveryStatus,
IncomingMessage,
ReactionEvent,
+ EditedMessage,
} from '../../engine/interfaces/whatsapp-engine.interface';
import { createLogger } from '../../common/services/logger.service';
import { ShutdownService } from '../../common/services/shutdown.service';
@@ -169,10 +170,10 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// awaited hook and orphan an engine the lifecycle could never destroy.
private initializingSessions: Set<string> = new Set();
- // Serializes the read-modify-write of a message's reactions map per `${sessionId}:${waMessageId}`,
- // so two concurrent reaction events on the same message don't clobber each other (both read the
- // same snapshot, both full-row save, last writer wins). Entries are deleted once their chain drains.
- private reactionChains: Map<string, Promise<void>> = new Map();
+ // Serializes stored-message mutations per `${sessionId}:${waMessageId}`. Reactions perform a
+ // read-modify-write and rapid edits must remain latest-write-wins; sharing one chain also preserves
+ // order when different mutation kinds for the same message arrive together.
+ private messageMutationChains: Map<string, Promise<void>> = new Map();
constructor(
@InjectRepository(Session, 'data')
@@ -1082,42 +1083,37 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
},
onMessageReaction: (event): void => {
if (!this.isLiveEngine(id, engine)) return;
+ if (!event.messageId) {
+ this.logger.warn('Ignoring message reaction without a target message id', {
+ sessionId: id,
+ action: 'message_reaction_ignored',
+ });
+ return;
+ }
this.logger.debug(`Message reaction received: ${event.messageId} -> ${event.reaction}`, {
sessionId: id,
messageId: event.messageId,
action: 'message_reaction_received',
});
- // Serialize per message so two concurrent reactions don't read the same snapshot and clobber
- // each other on the full-row save. A prior chain's failure must not block later reactions.
- const key = `${id}:${event.messageId}`;
- const prior = this.reactionChains.get(key) ?? Promise.resolve();
- const next = prior.catch(() => undefined).then(() => this.applyReaction(id, event));
- this.reactionChains.set(key, next);
- void next.finally(() => {
- // Clean up only if no newer reaction chained after us, so the map can't leak per message.
- if (this.reactionChains.get(key) === next) {
- this.reactionChains.delete(key);
- }
- });
+ this.enqueueMessageMutation(id, event.messageId, () => this.applyReaction(id, event));
},
onMessageEdited: (message): void => {
if (!this.isLiveEngine(id, engine)) return;
+ if (!message.messageId) {
+ this.logger.warn('Ignoring message edit without a target message id', {
+ sessionId: id,
+ action: 'message_edit_ignored',
+ });
+ return;
+ }
this.logger.debug(`Message edited: ${message.messageId}`, {
sessionId: id,
messageId: message.messageId,
action: 'message_edited',
});
- void this.messageRepository
- .update({ sessionId: id, waMessageId: message.messageId }, { body: message.body })
- .catch(err => {
- this.logger.error(`Failed to update edited message: ${message.messageId}`, String(err));
- });
-
- const editedPayload = message as unknown as Record<string, unknown>;
- void this.webhookService.dispatch(id, 'message.edited', editedPayload);
- this.eventsGateway.emitMessageEdited(id, editedPayload);
+ this.enqueueMessageMutation(id, message.messageId, () => this.applyMessageEdit(id, message));
},
onDisconnected: (reason: string): void => {
if (!this.isLiveEngine(id, engine)) return;
@@ -1296,7 +1292,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
metadata.reactions = reactions;
// Scoped update of ONLY the metadata column. A full-row save(msg) would re-persist the `status`
// read at findOne time, clobbering a concurrent ack UPDATE (SENT→DELIVERED/READ) that committed in
- // the window between this findOne and the write — reactionChains serializes reaction-vs-reaction
+ // the window between this findOne and the write — the mutation chain serializes reaction-vs-reaction
// but NOT reaction-vs-ack, so scoping the write to metadata is what keeps delivery state monotonic
// (#220). Other metadata fields are carried through untouched (they were read into `metadata`).
await this.messageRepository.update({ sessionId: id, waMessageId: event.messageId }, {
@@ -1312,6 +1308,40 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
}
+ /** Queue a message-scoped mutation. A failed operation is isolated so later events still run. */
+ private enqueueMessageMutation(id: string, messageId: string, work: () => Promise<void>): void {
+ const key = `${id}:${messageId}`;
+ const prior = this.messageMutationChains.get(key) ?? Promise.resolve();
+ const next = prior
+ .catch(() => undefined)
+ .then(work)
+ .catch(err => {
+ // Both current mutation implementations contain their own contextual error handling. Keep a
+ // final guard here so a future implementation cannot leak a rejected fire-and-forget promise
+ // or permanently block the message's later mutations.
+ this.logger.error(`Unexpected failure applying message mutation: ${messageId}`, String(err));
+ });
+ this.messageMutationChains.set(key, next);
+ void next.finally(() => {
+ if (this.messageMutationChains.get(key) === next) {
+ this.messageMutationChains.delete(key);
+ }
+ });
+ }
+
+ /** Persist an edit before notifying consumers, while still surfacing the occurrence if storage fails. */
+ private async applyMessageEdit(id: string, message: EditedMessage): Promise<void> {
+ try {
+ await this.messageRepository.update({ sessionId: id, waMessageId: message.messageId }, { body: message.body });
+ } catch (err) {
+ this.logger.error(`Failed to update edited message: ${message.messageId}`, String(err));
+ }
+
+ const editedPayload = message as unknown as Record<string, unknown>;
+ this.eventsGateway.emitMessageEdited(id, editedPayload);
+ void this.webhookService.dispatch(id, 'message.edited', editedPayload);
+ }
+
private scheduleReconnect(id: string, session: Session): void {
// Don't launch a fresh engine (Chromium) mid-shutdown: a disconnect during the drain window would
// otherwise schedule a reconnect that races onModuleDestroy's teardown and could orphan a browser.
diff --git a/src/modules/webhook/filters/filter-evaluator.spec.ts b/src/modules/webhook/filters/filter-evaluator.spec.ts
index a48d12d7f..657b6ed0f 100644
--- a/src/modules/webhook/filters/filter-evaluator.spec.ts
+++ b/src/modules/webhook/filters/filter-evaluator.spec.ts
@@ -109,6 +109,28 @@ describe('evaluateFilters', () => {
).toBe(true);
});
+ it('applies message-family smart filters to the normalized message.edited payload', () => {
+ const edit = msg({
+ author: '[email protected]',
+ body: 'Updated invoice',
+ type: 'image',
+ isGroup: true,
+ hasMedia: true,
+ mentionedIds: ['[email protected]'],
+ });
+ const f = filters(
+ { field: 'sender', operator: 'is', value: ['[email protected]'] },
+ { field: 'body', operator: 'contains', value: 'invoice' },
+ { field: 'type', operator: 'is', value: ['image'] },
+ { field: 'hasMedia', operator: 'is', value: true },
+ { field: 'mentions', operator: 'is', value: ['[email protected]'] },
+ );
+
+ expect(evaluateFilters(f, 'message.edited', edit)).toBe(true);
+ expect(evaluateFilters(f, 'message.edited', { ...edit, hasMedia: false })).toBe(false);
+ });
+
it('mentions (idArray) intersects', () => {
const f = filters({ field: 'mentions', operator: 'is', value: ['[email protected]'] });
expect(evaluateFilters(f, 'message.received', msg({ mentionedIds: ['[email protected]', '[email protected]'] }))).toBe(true);
diff --git a/src/modules/webhook/filters/filter-types.ts b/src/modules/webhook/filters/filter-types.ts
index 5f8013224..602a6c7c5 100644
--- a/src/modules/webhook/filters/filter-types.ts
+++ b/src/modules/webhook/filters/filter-types.ts
@@ -111,7 +111,9 @@ export const FILTER_FIELDS: Record<string, FieldDefinition[]> = {
field: 'hasMedia',
kind: 'boolean',
operators: BOOLEAN_OPERATORS,
- resolve: data => data.media != null,
+ // Edit events carry an explicit marker rather than a media blob; preserve the blob-based
+ // behaviour for received/sent messages while making the common message filter meaningful.
+ resolve: data => data.hasMedia === true || data.media != null,
},
{
field: 'mentions',
diff --git a/src/modules/webhook/utils/idempotency.util.ts b/src/modules/webhook/utils/idempotency.util.ts
index 58e5f1b54..6ee08d9c7 100644
--- a/src/modules/webhook/utils/idempotency.util.ts
+++ b/src/modules/webhook/utils/idempotency.util.ts
@@ -24,16 +24,16 @@ function hashData(data: Record<string, unknown>): string {
* Same event with same data will produce the same key (deterministic).
*
* @remarks
- * Message keys are content-based (keyed on the unique message id), so two deliveries of the same
- * logical message dedupe. Lifecycle events (session.status/authenticated/disconnected) recur with
- * identical content — the same phone on every reconnect, a constant disconnect reason — so they are
- * salted with `occurredAt` (captured ONCE per dispatch and reused across retries): distinct
- * occurrences get distinct keys while retries of the same occurrence stay stable.
+ * Stable message keys are content-based (keyed on the unique message id), so two deliveries of the
+ * same logical message dedupe. Recurring events (message edits/reactions and session lifecycle
+ * transitions) can repeat with identical content, so they are salted with `occurredAt` (captured ONCE
+ * per dispatch and reused across retries): distinct occurrences get distinct keys while retries of
+ * the same occurrence stay stable.
*
- * @param occurredAt - ISO timestamp captured once per dispatch; salts recurring lifecycle keys.
+ * @param occurredAt - ISO timestamp captured once per dispatch; salts recurring occurrence keys.
*/
export function generateIdempotencyKey(event: string, data: Record<string, unknown>, occurredAt?: string): string {
- // Salt applied only to the recurring lifecycle keys below; message/qr keys ignore it.
+ // Only recurring occurrence keys consume this salt; stable message and QR keys ignore it.
const occurrence = occurredAt ? `_${occurredAt}` : '';
switch (event) {
case 'message.received':
diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.ts
index a78615879..77ab336d5 100644
--- a/src/modules/webhook/webhook.service.spec.ts
+++ b/src/modules/webhook/webhook.service.spec.ts
@@ -764,6 +764,25 @@ describe('WebhookService', () => {
expect(await deliveries(hasMedia, 'message.received', { body: 'just text' })).toBe(0);
});
+ it('filters message.edited through a wildcard subscription using its normalized message fields', async () => {
+ const f = conds(
+ { field: 'sender', operator: 'is', value: ['[email protected]'] },
+ { field: 'body', operator: 'contains', value: 'invoice' },
+ { field: 'type', operator: 'is', value: ['image'] },
+ { field: 'hasMedia', operator: 'is', value: true },
+ );
+ const data = {
+ author: '[email protected]',
+ body: 'Updated invoice',
+ type: 'image',
+ hasMedia: true,
+ };
+
+ expect(await deliveries(f, 'message.edited', data)).toBe(1);
+ expect(await deliveries(f, 'message.edited', { ...data, body: 'lunch?', hasMedia: false })).toBe(0);
+ });
+
it('mentions: fires when the message mentions one of the listed JIDs', async () => {
const f = conds({ field: 'mentions', operator: 'is', value: ['[email protected]'] });
expect(await deliveries(f, 'message.received', { mentionedIds: ['[email protected]', '[email protected]'] })).toBe(1);