Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): announce a deleted message without its edit mark

Yudhi Armyndharisaacf9b6b0e5e
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 9c4965617..5790a8f7c 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -7290,7 +7290,7 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve
> **`contact` on `message.received` is minimal unless you opt in (`WEBHOOK_CONTACT_DETAILS`).** By default the payload carries only `contact { name?, pushName? }`. Setting `WEBHOOK_CONTACT_DETAILS=true` adds `id`, `number`, `shortName`, `type`, `isMyContact`, `isWAContact`, `isBusiness`, `isEnterprise`, `verifiedName`, `verifiedLevel`, `isBlocked` and `labels`, each present only when the engine has a value for it. Every field is copied from the contact record the engine has already loaded for the message, so opting in costs no extra WhatsApp lookup and cannot add rate-limiting pressure. The same enrichment reaches the websocket event, since both are dispatched from one payload. `contact` itself is omitted entirely when the engine has no value for any of its fields, so treat the whole object as optional rather than just its members. **whatsapp-web.js only** — the Baileys path emits `contact { pushName }` when a push name is available, and never reads this flag.
-> **`edited` on `message.received` and `message.sent`.** When an edit reached a message before the gateway stored it, the message is announced with the edited `body` and `edited: true`, as its stored row carries `metadata.edited`. This holds when a later edit restored the text it arrived with too, and the `body` is then that text; edit events that each repeat the text set neither. Its `message.edited` can arrive before the message itself, so a client that holds no copy of it yet reads the mark from here. An own message the engine delivers again after an edit marked its stored row is announced in `message.sent` with `edited: true` too, after the `message.edited` of an edit that reached the gateway first (it remembers up to 500 marked messages per session, the oldest forgotten first, while the session has an engine). The field is absent otherwise.
+> **`edited` on `message.received` and `message.sent`.** When an edit reached a message before the gateway stored it, the message is announced with the edited `body` and `edited: true`, as its stored row carries `metadata.edited`. This holds when a later edit restored the text it arrived with too, and the `body` is then that text; edit events that each repeat the text set neither. Its `message.edited` can arrive before the message itself, so a client that holds no copy of it yet reads the mark from here. An own message the engine delivers again after an edit marked its stored row is announced in `message.sent` with `edited: true` too, after the `message.edited` of an edit that reached the gateway first (it remembers up to 500 marked messages per session, the oldest forgotten first, while the session has an engine). A message announced deleted (`type: 'revoked'`) never carries the field. The field is absent otherwise.
> **Large media is not inlined into webhook payloads.** A `media` blob whose decoded size exceeds `WEBHOOK_MEDIA_INLINE_MAX_BYTES` (default **1 MiB**; `0` = never inline) is replaced — before the payload is fanned out to your webhook — with the marker form `media: { mimetype, filename?, omitted: true, sizeBytes }`, the same shape the engine emits for capped inbound media. Media at or under the cap stays inline unchanged. Additionally, if the serialized body still exceeds `WEBHOOK_MAX_PAYLOAD_BYTES` (default **1 MiB**) after `webhook:before` hooks ran, any remaining inline media is shed the same way so the event is still delivered; only a payload that is over budget _without_ inline media is dropped (recorded in `GET /api/webhooks/delivery-failures`). Because shedding happens before enqueue, queued and failed BullMQ jobs in Redis never carry the blob either — failed-job retention is bounded by the queue's `removeOnComplete`/`removeOnFail` windows (1h/1000 completed, 24h/5000 failed). The two limits compound: `WEBHOOK_MAX_PAYLOAD_BYTES` is measured on the serialized JSON body after `WEBHOOK_MEDIA_INLINE_MAX_BYTES` has been applied, and base64 inflates media by a third, so at the defaults media above roughly **768 KiB** reaches your webhook as the omitted marker. To inline larger media, raise both together and keep the payload limit at least 4/3 of the inline limit plus room for the rest of the event (for example `5242880` inline with `7340032` payload). The **WebSocket** `message.received` / `message.sent` events apply only the inline cap, with the same marker: an over-cap blob is never broadcast to subscribed sockets (or, with the Redis adapter enabled, replicated across every replica's pub/sub link). On either sink, media the engine downloaded stays retrievable from [`GET /api/sessions/:sessionId/messages/:chatId/:messageId/media`](#get-apisessionssessionidmessageschatidmessageidmedia), which returns `404` when nothing was stored.
diff --git a/src/engine/adapters/wwebjs-message-changes.spec.ts b/src/engine/adapters/wwebjs-message-changes.spec.ts
index ec446186b..fca383600 100644
--- a/src/engine/adapters/wwebjs-message-changes.spec.ts
+++ b/src/engine/adapters/wwebjs-message-changes.spec.ts
@@ -537,6 +537,23 @@ describe.each([
expect(events('message.received')).toEqual([expect.objectContaining({ body: 'fixed', edited: true })]);
});
+ it('announces a message edited and then deleted for me while the hook runs as deleted, without the mark', async () => {
+ const hook = deferred<void>();
+ hookGate = hook.promise;
+ client.emit('message', incoming('A', 'orig'));
+ await flush();
+ editEvent(client, 'A', 'fixed');
+ await flush();
+ const deleted = projector.recordRevoke('s1', 'A', { kind: 'revoke', chatId: CHAT });
+ hook.resolve();
+ await deleted;
+ await flush();
+
+ expect(rows).toEqual([expect.objectContaining({ waMessageId: 'A', body: '', type: 'revoked', metadata: null })]);
+ expect(events('message.received')).toEqual([expect.objectContaining({ body: '', type: 'revoked' })]);
+ expect(events('message.received')[0]).not.toHaveProperty('edited');
+ });
+
it.each([
['before', true],
['after', false],
@@ -694,6 +711,68 @@ describe.each([
expect(events('message.sent')[1]).not.toHaveProperty('edited');
});
+ // A delete for me raises no revoke event: the REST delete alone takes the message back.
+ it('announces an own message delivered again while its edit is written and deleted for me, without the mark', async () => {
+ client.emit('message_create', own('S', 'orig'));
+ await flush();
+ editEvent(client, 'S', 'e0', { fromMe: true });
+ await flush();
+ const write = deferred<void>();
+ holdWrite = patch => (patch.body === 'e1' ? write.promise : undefined);
+ editEvent(client, 'S', 'e1', { fromMe: true });
+ client.emit('message_create', own('S', 'e1'));
+ await flush();
+ const deleted = projector.recordRevoke('s1', 'S', { kind: 'revoke', chatId: CHAT });
+ await flush();
+ write.resolve();
+ await deleted;
+ await flush();
+
+ expect(rows).toEqual([expect.objectContaining({ waMessageId: 'S', body: '', type: 'revoked', metadata: null })]);
+ expect(events('message.sent')).toEqual([
+ expect.objectContaining({ body: 'orig', type: 'text' }),
+ expect.objectContaining({ body: '', type: 'revoked' }),
+ ]);
+ expect(events('message.sent')[1]).not.toHaveProperty('edited');
+ });
+
+ it('announces an own message delivered again as deleted without the mark its row still has', async () => {
+ client.emit('message_create', own('S', 'orig'));
+ await flush();
+ editEvent(client, 'S', 'e0', { fromMe: true });
+ await flush();
+ client.emit('message_create', { ...own('S', ''), type: 'revoked' });
+ await flush();
+
+ expect(events('message.sent')).toEqual([
+ expect.objectContaining({ body: 'orig', type: 'text' }),
+ expect.objectContaining({ body: '', type: 'revoked' }),
+ ]);
+ expect(events('message.sent')[1]).not.toHaveProperty('edited');
+ });
+
+ // Its commit waits behind an earlier message of the chat, whose hook runs meanwhile.
+ it('announces an own message delivered again as deleted while its edit waits with it, without the mark', async () => {
+ const hook = deferred<void>();
+ hookGate = hook.promise;
+ client.emit('message', incoming('P', 'earlier'));
+ await flush();
+ client.emit('message_create', own('S', 'orig'));
+ await flush();
+ editEvent(client, 'S', 'e0', { fromMe: true });
+ await flush();
+ client.emit('message_create', { ...own('S', ''), type: 'revoked' });
+ await flush();
+ hook.resolve();
+ await flush();
+
+ expect(events('message.sent')).toEqual([
+ expect.objectContaining({ body: 'e0', type: 'text', edited: true }),
+ expect.objectContaining({ type: 'revoked' }),
+ ]);
+ expect(events('message.sent')[1]).not.toHaveProperty('edited');
+ });
+
it('announces an own message delivered again after its delete and an API edit of it without the mark', async () => {
client.emit('message_create', own('S', 'orig'));
await flush();
diff --git a/src/modules/session/message-projector.service.ts b/src/modules/session/message-projector.service.ts
index d7be5e3d2..82479c7a6 100644
--- a/src/modules/session/message-projector.service.ts
+++ b/src/modules/session/message-projector.service.ts
@@ -1044,13 +1044,14 @@ export class MessageProjector {
* null once the engine revoked it (message.revoked already went out, so the deleted content is not
* announced after it), the revoked placeholder when only the REST delete did (a delete-for-me emits no
* engine revoke, and the message still exists for its sender), the edited body when edited
- * (message.edited already went out with it), plus `edited: true` when the row is marked for it: a consumer
- * that held no copy of the message could not apply that event. The stored row takes the same changes in
- * {@link applyChangesMadeInFlight}.
+ * (message.edited already went out with it), plus `edited: true` when the row is marked for it or already
+ * was (`rowMarked`): a consumer that held no copy of the message could not apply that event. A message
+ * announced deleted carries no mark. The stored row takes the same changes in {@link applyChangesMadeInFlight}.
*/
private withChangesMadeInFlight(
id: string,
message: InboundMessageData,
+ rowMarked = false,
): (InboundMessageData & { edited?: true }) | null {
const pending = this.inboundInFlight.get(`${id}:${message.id}`);
if (pending?.revokeAnnounced) return null;
@@ -1061,9 +1062,11 @@ export class MessageProjector {
message;
return { ...kept, body: '', type: 'revoked' };
}
+ // The mark described content a message delivered deleted no longer has.
+ const edited = (rowMarked || pending?.edited) && message.type !== 'revoked';
// An edit the engine applied before the hand-over is in the body already.
- if (pending?.editedBody === undefined) return pending?.edited ? { ...message, edited: true as const } : message;
- return { ...message, body: pending.editedBody, ...(pending.edited ? { edited: true as const } : {}) };
+ if (pending?.editedBody === undefined) return edited ? { ...message, edited: true as const } : message;
+ return { ...message, body: pending.editedBody, ...(edited ? { edited: true as const } : {}) };
}
/** Engine callback body, lifted out of initializeEngine so the wiring table stays readable. */
@@ -1230,9 +1233,8 @@ export class MessageProjector {
}
}
- const announced = this.withChangesMadeInFlight(id, finalMessage);
- if (!announced) return;
- const sent = rowMarked ? { ...announced, edited: true as const } : announced;
+ const sent = this.withChangesMadeInFlight(id, finalMessage, rowMarked);
+ if (!sent) return;
void this.webhookService.dispatch(id, 'message.sent', sent);
// Emit real-time event to WebSocket clients (as message.sent, not message.received)
this.eventsGateway.emitMessageSent(id, sent);