Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(core): preserve revoked history and event order (#1779)

Yudhi Armyndharis051003c304b4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 626f64439..7958ae654 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,12 +24,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- Preserve chat-scoped WebSocket event order while resolving chat identities.
+- Preserve poll choices across dashboard echoes and keep revoked messages cleared.
+- Serialize explicitly selected empty Go redrive slices as empty arrays.
- Emit Baileys API reaction updates, including reaction removal.
- Restore legacy webhook failures and normalize terminal duplicates before SQLite schema synchronization.
- Exclude retained webhook replay payloads from database backup reads.
- Advance webhook recovery scans past live queued deliveries.
- Apply current receiver configuration and session ownership to every webhook delivery attempt.
-- Clear revoked Baileys history messages from chat previews.
+- Clear revoked Baileys history messages from storage, previews, quoted replies, and plugin indexes.
- Preserve pending message mutations when REST storage wins an own-send echo.
- Cancel archived media preview downloads when their components unmount.
- Refresh Baileys pairing secrets and prevent stale QR renders during linking.
diff --git a/dashboard/src/pages/Chats.test.ts b/dashboard/src/pages/Chats.test.ts
index c56a61754..5a550750c 100644
--- a/dashboard/src/pages/Chats.test.ts
+++ b/dashboard/src/pages/Chats.test.ts
@@ -1875,6 +1875,46 @@ test('a message deleted for everyone in a chat never opened refetches the chat l
await waitFor(() => assert.equal(countFetchCalls('GET', `/api/sessions/${SESSION.id}/chats`), 1));
});
+test('a delayed poll echo cannot restore a revoked message or its sidebar preview', async () => {
+ const { screen, fireEvent, within, waitFor } = rtl;
+ const { container } = renderChats();
+ fireEvent.click(await screen.findByText('Alice'));
+ const room = container.querySelector('.room-messages') as HTMLElement;
+ await within(room).findByText('hello from alice');
+ const id = OMITTED_MEDIA_MESSAGE_2.waMessageId as string;
+ revoke(CHAT.id, id);
+ const sidebar = container.querySelector('.chats-sidebar') as HTMLElement;
+ await waitFor(() => assert.ok(!within(sidebar).queryByText('hello from alice')));
+ resetFetchCalls();
+ lastSocket()!.receive('message', {
+ type: 'event',
+ timestamp: new Date().toISOString(),
+ payload: {
+ event: 'message.received',
+ sessionId: SESSION.id,
+ data: {
+ id,
+ chatId: CHAT.id,
+ from: CHAT.id,
+ to: 'me',
+ body: 'withdrawn question',
+ type: 'poll',
+ fromMe: false,
+ timestamp: 1_700_003_000,
+ poll: { name: 'withdrawn question', options: ['private choice'], allowMultipleAnswers: false },
+ },
+ },
+ });
+ await flush();
+ assert.ok(!within(container).queryByText('withdrawn question'));
+ assert.ok(!within(room).queryByText('private choice'));
+ assert.equal(countFetchCalls('POST', `/api/sessions/${SESSION.id}/chats/read`), 0);
+ const cached = queryClient!.getQueryData<{ pages: Array<{ db: ChatMessage[] }> }>(['messages', SESSION.id, CHAT.id]);
+ const row = cached!.pages.flatMap(page => page.db).find(m => m.waMessageId === id)!;
+ assert.equal(row.type, 'revoked');
+ assert.equal(row.metadata, undefined);
+});
+
// A global-search hit in the third session, on Alice's chat.
const THIRD_SESSION_HIT: SearchHit = {
messageId: 'db-9',
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index 0f641e74c..7acdd7249 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -442,6 +442,15 @@ export function Chats() {
if (event.sessionId !== selectedSessionId) return;
const newMsg = event.message as unknown as IncomingWsMessage;
+ if (
+ cachedSessionThreads(
+ queryClient,
+ event.sessionId,
+ m => m.chatId === newMsg.chatId && byMessageId(newMsg.id)(m) && m.type === 'revoked',
+ ).length
+ ) {
+ return;
+ }
const mappedMessage: ChatMessageView = {
id: newMsg.id,
@@ -490,7 +499,17 @@ export function Chats() {
void loadChats(selectedSessionId, { background: true });
}
},
- [selectedSessionId, activeChat, canWrite, loadChats, markChatRead, appendMessage, onMessageAppended, t],
+ [
+ selectedSessionId,
+ activeChat,
+ canWrite,
+ loadChats,
+ markChatRead,
+ appendMessage,
+ onMessageAppended,
+ queryClient,
+ t,
+ ],
);
const handleIncomingMessageAck = useCallback(
@@ -525,13 +544,17 @@ export function Chats() {
// function so the behaviour is covered by a test, because nothing here is.
for (const [key] of cachedSessionThreads(queryClient, event.sessionId, byMessageId(event.messageId))) {
updateCachedMessages(queryClient, key, list =>
- patchMatchingMessage(list, event.messageId, m => ({
- ...m,
- metadata: {
- ...(m.metadata || {}),
- reactions: mergeReactionSnapshot(m.metadata?.reactions, event.reactions),
- },
- })),
+ patchMatchingMessage(list, event.messageId, m =>
+ m.type === 'revoked'
+ ? m
+ : {
+ ...m,
+ metadata: {
+ ...(m.metadata || {}),
+ reactions: mergeReactionSnapshot(m.metadata?.reactions, event.reactions),
+ },
+ },
+ ),
);
}
},
@@ -558,7 +581,7 @@ export function Chats() {
const idx = findRevokedIndex(list, event);
if (idx === -1) return list;
const next = list.slice();
- next[idx] = { ...next[idx], body: '', type: asMessageType(event.type) };
+ next[idx] = { ...next[idx], body: '', type: asMessageType(event.type), metadata: undefined };
return next;
});
}
@@ -587,7 +610,7 @@ export function Chats() {
// Position is asked of the merged thread, never of a page: pages carry only a fraction of
// the chat each, so "is this the last message" is only ever answerable from the whole thing.
const editedIndex = thread.findIndex(byMessageId(event.messageId));
- if (editedIndex === -1) continue;
+ if (editedIndex === -1 || thread[editedIndex].type === 'revoked') continue;
matchedCachedMessage = true;
updateCachedMessages(queryClient, key, list => applyMessageEdit(list, event));
@@ -739,7 +762,7 @@ export function Chats() {
const key = messagesQueryKey(selectedSessionId, activeChat.id);
updateCachedMessages(queryClient, key, old =>
old.map(m => {
- if (m.id === msg.id || m.waMessageId === msg.id) {
+ if (m.type !== 'revoked' && (m.id === msg.id || m.waMessageId === msg.id)) {
const metadata = m.metadata || {};
const reactions = { ...(metadata.reactions || {}) };
if (emojiToSend === '') {
@@ -770,7 +793,7 @@ export function Chats() {
forEveryone: true,
});
- updateMessage(selectedSessionId, activeChat.id, msg.id, { body: '', type: 'revoked' });
+ updateMessage(selectedSessionId, activeChat.id, msg.id, { body: '', type: 'revoked', metadata: undefined });
} catch (err) {
showErrorToast(t('chats.errors.delete'), err instanceof Error ? err.message : undefined);
}
diff --git a/dashboard/src/utils/chatMessages.test.ts b/dashboard/src/utils/chatMessages.test.ts
index 3e78e0c9d..6fb76bbed 100644
--- a/dashboard/src/utils/chatMessages.test.ts
+++ b/dashboard/src/utils/chatMessages.test.ts
@@ -218,6 +218,75 @@ test('mergeOrAppend: DB-persisted prompt buttons survive a button-less echo', ()
assert.deepEqual(after[0].metadata?.buttons, buttons);
});
+test('mergeOrAppend preserves poll choices across duplicate and partial echoes', () => {
+ const poll = { name: 'Lunch?', options: ['Rice', 'Soup'], allowMultipleAnswers: false };
+ const before = msg({ type: 'poll', metadata: { poll } });
+ for (const metadata of [{ poll }, { media: undefined }]) {
+ const after = mergeOrAppend([before], msg({ type: 'poll', metadata }));
+ assert.deepEqual(after[0].metadata?.poll, poll);
+ assert.deepEqual(before.metadata, { poll });
+ }
+ const updated = { ...poll, options: ['Rice', 'Soup', 'Salad'] };
+ assert.deepEqual(
+ mergeOrAppend([before], msg({ type: 'poll', metadata: { poll: updated } }))[0].metadata?.poll,
+ updated,
+ );
+});
+
+test('mergeOrAppend keeps revocation terminal and removes content metadata', () => {
+ const original = msg({
+ type: 'poll',
+ metadata: {
+ poll: { name: 'Lunch?', options: ['Rice', 'Soup'], allowMultipleAnswers: false },
+ media: { mimetype: 'image/png', data: 'BASE64', archived: true },
+ quotedMessage: { id: 'q', body: 'quote' },
+ reactions: { me: 'yes' },
+ },
+ });
+ const revoked = msg({ type: 'revoked', body: '', metadata: undefined });
+ for (const [existing, incoming] of [
+ [original, revoked],
+ [revoked, original],
+ ]) {
+ const [result] = mergeOrAppend([existing], incoming);
+ assert.equal(result.type, 'revoked');
+ assert.equal(result.body, '');
+ assert.equal(result.metadata, undefined);
+ }
+ const [newRevoked] = mergeOrAppend([], { ...original, type: 'revoked' });
+ assert.equal(newRevoked.body, '');
+ assert.equal(newRevoked.metadata, undefined);
+ assert.equal(original.body, 'hello');
+ assert.ok(original.metadata?.poll);
+});
+
+test('mergeChatMessages keeps every revoked copy terminal regardless of source or duplicate order', () => {
+ const original = msg({
+ type: 'poll',
+ metadata: { poll: { name: 'Q', options: ['A'], allowMultipleAnswers: false } },
+ });
+ const revoked = { ...original, type: 'revoked' as const, body: '' };
+ for (const [rows, history] of [
+ [[original], [revoked]],
+ [[revoked], [original]],
+ [[revoked, original], []],
+ [[original, revoked], []],
+ [[], [revoked, original]],
+ [[], [original, revoked]],
+ ]) {
+ const [result] = mergeChatMessages(rows, history);
+ assert.equal(result.type, 'revoked');
+ assert.equal(result.body, '');
+ assert.equal(result.metadata, undefined);
+ }
+ assert.ok(original.metadata?.poll);
+});
+
+test('applyMessageEdit ignores a delayed edit for a revoked message', () => {
+ const before = [msg({ type: 'revoked', body: '' })];
+ assert.equal(applyMessageEdit(before, { messageId: before[0].waMessageId!, body: 'late' }), before);
+});
+
test('mergeOrAppend dedupes a live WS message against its DB copy (id != id but same waMessageId)', () => {
// DB-persisted copy: id = UUID, waMessageId = WA serialized id.
const dbCopy = msg({ id: 'uuid-1', waMessageId: '[email protected]_WA1', body: 'persisted' });
diff --git a/dashboard/src/utils/chatMessages.ts b/dashboard/src/utils/chatMessages.ts
index bcad08447..bac38e76b 100644
--- a/dashboard/src/utils/chatMessages.ts
+++ b/dashboard/src/utils/chatMessages.ts
@@ -50,8 +50,7 @@ const msgTime = (m: ChatMessage): number =>
// real delivery status survives. Deduped by the wweb.js serialized id (engine `id` == DB `waMessageId`).
export function mergeChatMessages(db: ChatMessage[], history: ChatMessage[]): ChatMessage[] {
const byId = new Map<string, ChatMessage>();
- for (const m of history) byId.set(msgKey(m), m);
- for (const m of db) {
+ for (const m of [...history, ...db]) {
const key = msgKey(m);
const hist = byId.get(key);
// The DB copy wins (authoritative status) — but a legacy row has no stable sender id, so
@@ -61,6 +60,9 @@ export function mergeChatMessages(db: ChatMessage[], history: ChatMessage[]): Ch
if (m.type === 'poll' && !m.metadata?.poll && hist?.metadata?.poll) {
merged = { ...merged, metadata: { ...merged.metadata, poll: hist.metadata.poll } };
}
+ if (m.type === 'revoked' || hist?.type === 'revoked') {
+ merged = { ...merged, type: 'revoked', body: '', metadata: undefined };
+ }
byId.set(key, merged);
}
const sorted = [...byId.values()].sort((a, b) => msgTime(a) - msgTime(b) || a.createdAt.localeCompare(b.createdAt));
@@ -343,6 +345,8 @@ function mergeMessageMetadata(
if (call) merged.call = call;
const buttons = incoming.buttons ?? existing.buttons;
if (buttons?.length) merged.buttons = buttons;
+ const poll = incoming.poll ?? existing.poll;
+ if (poll) merged.poll = poll;
return Object.keys(merged).length > 0 ? merged : undefined;
}
@@ -361,7 +365,10 @@ function mergeMessageMetadata(
*/
export function mergeOrAppend(list: ChatMessageView[], incoming: ChatMessageView): ChatMessageView[] {
const idx = list.findIndex(m => msgKey(m) === msgKey(incoming));
- if (idx === -1) return capMediaPayloads([...list, incoming]);
+ if (idx === -1) {
+ const message = incoming.type === 'revoked' ? { ...incoming, body: '', metadata: undefined } : incoming;
+ return capMediaPayloads([...list, message]);
+ }
const existing = list[idx];
const next = list.slice();
next[idx] = {
@@ -371,6 +378,9 @@ export function mergeOrAppend(list: ChatMessageView[], incoming: ChatMessageView
status: mergeDeliveryStatus(existing.status, incoming.status) ?? incoming.status,
metadata: mergeMessageMetadata(existing.metadata, incoming.metadata),
};
+ if (existing.type === 'revoked' || incoming.type === 'revoked') {
+ next[idx] = { ...next[idx], type: 'revoked', body: '', metadata: undefined };
+ }
return capMediaPayloads(next);
}
@@ -458,7 +468,7 @@ export function applyMessageEdit(
): ChatMessageView[] {
if (!event.messageId) return list;
const idx = list.findIndex(byMessageId(event.messageId));
- if (idx === -1) return list;
+ if (idx === -1 || list[idx].type === 'revoked') return list;
const next = list.slice();
next[idx] = { ...next[idx], body: event.body };
return next;
diff --git a/dashboard/src/utils/messagePages.test.ts b/dashboard/src/utils/messagePages.test.ts
index 17a98f5e4..a5ed54f21 100644
--- a/dashboard/src/utils/messagePages.test.ts
+++ b/dashboard/src/utils/messagePages.test.ts
@@ -1,7 +1,7 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { dbRowsFetched, nextMessagePageParam, upsertIntoPages, type MessagePage } from './messagePages.ts';
-import { MEDIA_PAYLOAD_CACHE_LIMIT, type ChatMessageView } from './chatMessages.ts';
+import { MEDIA_PAYLOAD_CACHE_LIMIT, mergeChatMessages, type ChatMessageView } from './chatMessages.ts';
const PAGE_SIZE = 100;
@@ -32,6 +32,24 @@ const rows = (count: number, prefix: string): ChatMessageView[] =>
const mediaMsg = (id: string, data: string): ChatMessageView =>
msg(id, { type: 'image', metadata: { media: { mimetype: 'image/jpeg', filename: `${id}.jpg`, data } } });
+test('a delayed live echo cannot restore a revoked history-only message', () => {
+ const pages = [page([], 0, [msg('old', { type: 'revoked', body: '' })])];
+ const result = upsertIntoPages(
+ pages,
+ msg('old', {
+ type: 'poll',
+ metadata: { poll: { name: 'Q', options: ['A'], allowMultipleAnswers: false } },
+ }),
+ );
+ const [merged] = mergeChatMessages(
+ result.flatMap(p => p.db),
+ result.flatMap(p => p.history),
+ );
+ assert.equal(merged.type, 'revoked');
+ assert.equal(merged.body, '');
+ assert.equal(merged.metadata, undefined);
+});
+
test('the cursor counts DB rows, not the rendered merge', () => {
// The regression this guards: engine history inflates the rendered list, so paging by its length
// would ask for an offset past rows the DB read never returned — silently skipping them.
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index fdb1eac42..742cbacba 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -47,7 +47,7 @@ API keys carry one of three roles, ordered by privilege:
A key may additionally be scoped to specific sessions (`allowedSessions`) and/or source IPs (`allowedIps`). The scope/IP check runs in the guard **before** any role check, so a request outside that scope is rejected with `403` even if the role would otherwise allow it. `401` is kept for a missing, unknown, revoked or expired key.
-A key may also be restricted to selected chats (`allowedChats`: group `<id>@g.us`, contact `<phone>@c.us` or `<lid>@lid`, or a bare phone number, which is stored as `<phone>@c.us`). An empty or absent list leaves the key unrestricted. A chat-restricted key is **denied by default**: it may call only routes marked as chat-scoped, and every other route (webhooks, automation, status, channels, key management, and any route added later) answers `403 "API key is restricted to selected chats"` after the role check. On a chat-scoped route, every chat id the request names (a `:chatId` / `:groupId` / `:contactId` path param, `?chatId=`, a body `chatId` / `fromChatId` / `toChatId`, and each `messages[].chatId` of a bulk send) must be inside the allowlist, or the request answers `403 "API key not authorized for this chat"`; a contact entry also matches its mapped `@lid` form, and the reverse. The chat, group, contact and label-chat list routes (`GET /api/sessions/:sessionId/chats`, `/groups`, `/contacts` and `/labels/:labelId/chats`) return only the allowed entries, filtered before paging. `GET /api/search` with the built-in provider narrows its hits to the allowed chats before `limit`/`offset`/`total` apply, and an optional `?chatId=` must name an allowed chat. Plugin providers return `403` for these keys before the worker is invoked; set `SEARCH_PROVIDER=builtin-fts` to enable scoped search. `GET /api/sessions/:sessionId/groups/:groupId` and its `GET`/`PUT .../settings` admit a group inside the allowlist and answer `403` for any other. On `GET /api/sessions/:sessionId/messages` such a key must pass `?chatId=`; omitting it answers `403`. A `quotedMessageId` is refused with `403` everywhere except the reply route, which binds the quote to the chat it sends into. The surfaces outside the REST guard refuse a chat-restricted key outright: the `/events` WebSocket at the handshake and on every subscribe, every MCP tool call (`403`), and the Bull Board queue dashboard (`403`).
+A key may also be restricted to selected chats (`allowedChats`: group `<id>@g.us`, contact `<phone>@c.us` or `<lid>@lid`, or a bare phone number, which is stored as `<phone>@c.us`). An empty or absent list leaves the key unrestricted. A chat-restricted key is **denied by default**: it may call only routes marked as chat-scoped, and every other route (webhooks, automation, status, channels, key management, and any route added later) answers `403 "API key is restricted to selected chats"` after the role check. On a chat-scoped route, every chat id the request names (a `:chatId` / `:groupId` / `:contactId` path param, `?chatId=`, a body `chatId` / `fromChatId` / `toChatId`, and each `messages[].chatId` of a bulk send) must be inside the allowlist, or the request answers `403 "API key not authorized for this chat"`; a contact entry also matches its mapped `@lid` form, and the reverse. The chat, group, contact and label-chat list routes (`GET /api/sessions/:sessionId/chats`, `/groups`, `/contacts` and `/labels/:labelId/chats`) return only the allowed entries, filtered before paging. `GET /api/search` with the built-in provider narrows its hits to the allowed chats before `limit`/`offset`/`total` apply, and an optional `?chatId=` must name an allowed chat. Plugin providers return `403` for these keys before the worker is invoked; set `SEARCH_PROVIDER=builtin-fts` to enable scoped search. `GET /api/sessions/:sessionId/groups/:groupId` and its `GET`/`PUT .../settings` admit a group inside the allowlist and answer `403` for any other. On `GET /api/sessions/:sessionId/messages` such a key must pass `?chatId=`; omitting it answers `403`. A `quotedMessageId` is refused with `403` everywhere except the reply route, which binds the quote to the chat it sends into. The `/events` WebSocket admits chat-restricted keys and delivers only chat events inside their allowlist. MCP tools enforce the same chat fence, filter list results before paging, and refuse tools without chat-scoped authorization. The Bull Board queue dashboard still refuses chat-restricted keys with `403`.
### API-Key Lifecycle
diff --git a/sdk/README.md b/sdk/README.md
index d3a46dbb3..bb5a7b4d5 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -1,5 +1,7 @@
# OpenWA SDKs
+This document describes `main`. Send idempotency, webhook failure redrive, message-window filters, poll choices, and last-message types are unreleased additions after SDK 0.5.1 and require the corresponding server changes after OpenWA 0.24.0.
+
Official client libraries for [OpenWA](https://github.com/rmyndharis/OpenWA), the
open-source WhatsApp API Gateway. OpenWA is an independent project, not
affiliated with or endorsed by WhatsApp or Meta.
diff --git a/sdk/go/README.md b/sdk/go/README.md
index b1c4c32b4..cd1b3e18e 100644
--- a/sdk/go/README.md
+++ b/sdk/go/README.md
@@ -1,5 +1,7 @@
# OpenWA Go SDK
+This document describes `main`. Send idempotency, webhook failure redrive, message-window filters, poll choices, and last-message types are unreleased additions after SDK 0.5.1 and require the corresponding server changes after OpenWA 0.24.0.
+
Idiomatic Go client for the [OpenWA](https://github.com/rmyndharis/OpenWA) WhatsApp
API Gateway. Stdlib-only (no dependencies), context-first, with typed errors and
an injectable transport pipeline.
@@ -275,6 +277,8 @@ Cutting a release:
## Send idempotency
+The example below requires the unreleased SDK changes on `main`; SDK 0.5.1 does not expose this per-send key argument. The server must also include the send idempotency changes after OpenWA 0.24.0.
+
Supply a unique caller-owned key for one logical send and reuse it when retrying that same call. Keys contain 1-255 visible ASCII characters; unrelated calls must use different keys. The SDK forwards the key without changing its retry policy or generating one automatically.
```go
diff --git a/sdk/go/client_test.go b/sdk/go/client_test.go
index 9e2fb4726..800a244f1 100644
--- a/sdk/go/client_test.go
+++ b/sdk/go/client_test.go
@@ -1794,18 +1794,31 @@ func TestSendIdempotencyKey(t *testing.T) {
func TestRedrivePreservesAnEmptyIDsFilter(t *testing.T) {
rt := &recordTransport{status: 200, body: `{}`}
c := newTestClient(t, rt)
+ var zero []string
empty := []string{}
- for _, ids := range []*[]string{nil, &empty} {
- if _, err := c.Webhooks.RedriveDeliveryFailures(context.Background(), &RedriveWebhookDeliveriesRequest{IDs: ids}); err != nil {
- t.Fatal(err)
- }
- want := `{}`
- if ids != nil {
- want = `{"ids":[]}`
- }
- if string(rt.lastRaw) != want {
- t.Fatalf("body = %s, want %s", rt.lastRaw, want)
- }
+ selected := []string{"f1"}
+ for _, tc := range []struct {
+ name string
+ ids *[]string
+ want string
+ }{
+ {"omitted", nil, `{}`},
+ {"nil slice", &zero, `{"ids":[]}`},
+ {"empty slice", &empty, `{"ids":[]}`},
+ {"selected rows", &selected, `{"ids":["f1"]}`},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ body := &RedriveWebhookDeliveriesRequest{IDs: tc.ids}
+ if _, err := c.Webhooks.RedriveDeliveryFailures(context.Background(), body); err != nil {
+ t.Fatal(err)
+ }
+ if string(rt.lastRaw) != tc.want {
+ t.Fatalf("body = %s, want %s", rt.lastRaw, tc.want)
+ }
+ if body.IDs != tc.ids || zero != nil {
+ t.Fatal("request IDs mutated")
+ }
+ })
}
}
diff --git a/sdk/go/webhooks.go b/sdk/go/webhooks.go
index 8b284f0b3..84ca460ec 100644
--- a/sdk/go/webhooks.go
+++ b/sdk/go/webhooks.go
@@ -42,6 +42,12 @@ func (s *WebhooksService) RedriveDeliveryFailures(ctx context.Context, body *Red
if body == nil {
body = &RedriveWebhookDeliveriesRequest{}
}
+ if body.IDs != nil && *body.IDs == nil {
+ copy := *body
+ empty := []string{}
+ copy.IDs = &empty
+ body = &copy
+ }
var out WebhookRedriveResult
if err := s.client.do(ctx, "POST", "/api/webhooks/delivery-failures/redrive", nil, body, &out); err != nil {
return nil, err
diff --git a/sdk/java/README.md b/sdk/java/README.md
index 385cb98c4..886ce0259 100644
--- a/sdk/java/README.md
+++ b/sdk/java/README.md
@@ -1,5 +1,7 @@
# OpenWA Java SDK
+This document describes `main`. Send idempotency, webhook failure redrive, message-window filters, poll choices, and last-message types are unreleased additions after SDK 0.5.1 and require the corresponding server changes after OpenWA 0.24.0.
+
Official Java client for [OpenWA](https://github.com/rmyndharis/OpenWA), the
open-source WhatsApp API Gateway. OpenWA is an independent project, not
affiliated with or endorsed by WhatsApp or Meta.
@@ -216,6 +218,8 @@ Cutting a release:
## Send idempotency
+The example below requires the unreleased SDK changes on `main`; SDK 0.5.1 does not expose this per-send key argument. The server must also include the send idempotency changes after OpenWA 0.24.0.
+
Supply a unique caller-owned key for one logical send and reuse it when retrying that same call. Keys contain 1-255 visible ASCII characters; unrelated calls must use different keys. The SDK forwards the key without changing its retry policy or generating one automatically.
```java
diff --git a/sdk/javascript/README.md b/sdk/javascript/README.md
index 5e44431e4..a732fbbf8 100644
--- a/sdk/javascript/README.md
+++ b/sdk/javascript/README.md
@@ -1,5 +1,7 @@
# @rmyndharis/openwa
+This document describes `main`. Send idempotency, webhook failure redrive, message-window filters, poll choices, and last-message types are unreleased additions after SDK 0.5.1 and require the corresponding server changes after OpenWA 0.24.0.
+
Official JavaScript/TypeScript SDK for [OpenWA](https://github.com/rmyndharis/OpenWA), the open-source WhatsApp API Gateway. OpenWA is an independent project, not affiliated with or endorsed by WhatsApp or Meta.
Ships dual CJS + ESM builds with bundled type declarations.
@@ -128,6 +130,8 @@ MIT
## Send idempotency
+The example below requires the unreleased SDK changes on `main`; SDK 0.5.1 does not expose this per-send key argument. The server must also include the send idempotency changes after OpenWA 0.24.0.
+
Supply a unique caller-owned key for one logical send and reuse it when retrying that same call. Keys contain 1-255 visible ASCII characters; unrelated calls must use different keys. The SDK forwards the key without changing its retry policy or generating one automatically.
```javascript
diff --git a/sdk/php/README.md b/sdk/php/README.md
index 3179069f8..4ad56eca1 100644
--- a/sdk/php/README.md
+++ b/sdk/php/README.md
@@ -1,5 +1,7 @@
# rmyndharis/openwa
+This document describes `main`. Send idempotency, webhook failure redrive, message-window filters, poll choices, and last-message types are unreleased additions after SDK 0.5.1 and require the corresponding server changes after OpenWA 0.24.0.
+
Official PHP SDK for [OpenWA](https://github.com/rmyndharis/OpenWA), the open-source WhatsApp API Gateway. OpenWA is an independent project, not affiliated with or endorsed by WhatsApp or Meta.
A synchronous client built on [Guzzle](https://docs.guzzlephp.org/), PSR-4 autoloaded.
@@ -160,6 +162,8 @@ MIT
## Send idempotency
+The example below requires the unreleased SDK changes on `main`; SDK 0.5.1 does not expose this per-send key argument. The server must also include the send idempotency changes after OpenWA 0.24.0.
+
Supply a unique caller-owned key for one logical send and reuse it when retrying that same call. Keys contain 1-255 visible ASCII characters; unrelated calls must use different keys. The SDK forwards the key without changing its retry policy or generating one automatically.
```php
diff --git a/sdk/python/README.md b/sdk/python/README.md
index 82f7fd90e..096aff4c2 100644
--- a/sdk/python/README.md
+++ b/sdk/python/README.md
@@ -1,5 +1,7 @@
# rmyndharis-openwa
+This document describes `main`. Send idempotency, webhook failure redrive, message-window filters, poll choices, and last-message types are unreleased additions after SDK 0.5.1 and require the corresponding server changes after OpenWA 0.24.0.
+
Official Python SDK for [OpenWA](https://github.com/rmyndharis/OpenWA), the open-source WhatsApp API Gateway. OpenWA is an independent project, not affiliated with or endorsed by WhatsApp or Meta.
A synchronous client built on [httpx](https://www.python-httpx.org/), with bundled type hints (PEP 561).
@@ -168,6 +170,8 @@ MIT
## Send idempotency
+The example below requires the unreleased SDK changes on `main`; SDK 0.5.1 does not expose this per-send key argument. The server must also include the send idempotency changes after OpenWA 0.24.0.
+
Supply a unique caller-owned key for one logical send and reuse it when retrying that same call. Keys contain 1-255 visible ASCII characters; unrelated calls must use different keys. The SDK forwards the key without changing its retry policy or generating one automatically.
```python
diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.ts
index a3fb5fbbf..ed25b9142 100644
--- a/src/engine/adapters/baileys-events.ts
+++ b/src/engine/adapters/baileys-events.ts
@@ -304,6 +304,21 @@ export class BaileysEvents {
}
}
+ /** Apply a history delete to the raw cache without announcing a live message event. */
+ async applyHistoryRevoke(target: WAMessageKey, envelope: WAMessageKey): Promise<WAMessageKey | undefined> {
+ if (!target.id) return undefined;
+ const generation = this.storeGeneration;
+ const stored = await this.readStoredMessage(target.id, 'checking what a history revoke targets');
+ if (generation !== this.storeGeneration) return undefined;
+ const original = stored?.key ?? this.inboundInFlight.get(target.id)?.key ?? target;
+ if (!this.mayChange(original, envelope, true)) return undefined;
+ if (stored || this.inboundInFlight.has(target.id)) this.markDeletedForEveryone(target.id);
+ this.changeStoredMessage(target.id, copy =>
+ this.mayChange(copy.key, envelope, true) ? { ...copy, message: null } : null,
+ );
+ return original;
+ }
+
handleMessagesUpsert(event: { messages: WAMessage[]; type: string }): void {
for (const msg of event.messages) {
if (!msg.message || !msg.key?.remoteJid) {
diff --git a/src/engine/adapters/baileys-history-revokes.spec.ts b/src/engine/adapters/baileys-history-revokes.spec.ts
new file mode 100644
index 000000000..986dad010
--- /dev/null
+++ b/src/engine/adapters/baileys-history-revokes.spec.ts
@@ -0,0 +1,340 @@
+import type { WAMessage, WASocket } from '@whiskeysockets/baileys';
+import { DataSource, Repository } from 'typeorm';
+import { BaileysHistory, BaileysHistoryHost } from './baileys-history';
+import { BaileysEvents, BaileysEventsHost } from './baileys-events';
+import { BaileysMessaging } from './baileys-messaging';
+import { BaileysMessageStoreService } from './baileys-message-store.service';
+import { BaileysStoredMessage } from './baileys-stored-message.entity';
+import { BaileysSessionStore } from './baileys-session-store';
+import { Message, MessageDirection } from '../../modules/message/entities/message.entity';
+import { Session, SessionStatus } from '../../modules/session/entities/session.entity';
+import { persistHistoryMessages } from '../../modules/session/message-history-projector';
+import { MessageNotFoundError } from '../../common/errors/message-not-found.error';
+import { createLogger } from '../../common/services/logger.service';
+import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';
+import type { IncomingMessage } from '../interfaces/whatsapp-engine.interface';
+
+const CHAT = '[email protected]';
+const SELF = '[email protected]';
+const target = (over: Partial<WAMessage> = {}): WAMessage => ({
+ key: { id: 'M1', remoteJid: CHAT, fromMe: false },
+ message: { conversation: 'withdrawn secret' },
+ messageTimestamp: 1_700_000_000,
+ ...over,
+});
+const revoke = (key: WAMessage['key'] = target().key, envelope: Partial<WAMessage['key']> = {}): WAMessage => ({
+ key: { id: 'R1', remoteJid: key.remoteJid, fromMe: false, ...envelope },
+ message: { protocolMessage: { type: 0, key } },
+ messageTimestamp: 1_700_000_100,
+});
+
+describe('Baileys history revokes', () => {
+ let ds: DataSource;
+ let repo: Repository<Message>;
+ let raw: BaileysMessageStoreService;
+ let history: BaileysHistory;
+ let messaging: BaileysMessaging;
+ let previews: BaileysSessionStore;
+ let pending: Promise<IncomingMessage[]>[];
+ let onHistory: jest.Mock;
+ let liveFanout: jest.Mock;
+ let persisted: jest.Mock;
+ let isLive: boolean;
+ let sendMessage: jest.Mock;
+ let events: BaileysEvents;
+ let releaseMedia: () => void;
+
+ beforeEach(async () => {
+ ds = await new DataSource({
+ type: 'better-sqlite3',
+ database: ':memory:',
+ entities: [Message, Session, BaileysStoredMessage],
+ synchronize: true,
+ }).initialize();
+ repo = ds.getRepository(Message);
+ raw = new BaileysMessageStoreService(ds.getRepository(BaileysStoredMessage));
+ await ds.getRepository(Session).save({ id: 's1', name: 's1', status: SessionStatus.READY, config: {} });
+ previews = new BaileysSessionStore(undefined, 's1');
+ previews.upsertChats([{ id: CHAT }, { id: '[email protected]' }]);
+ pending = [];
+ isLive = true;
+ liveFanout = jest.fn();
+ persisted = jest.fn();
+ onHistory = jest.fn((messages: IncomingMessage[]) => {
+ const saving = persistHistoryMessages(
+ repo,
+ undefined,
+ 's1',
+ messages,
+ { log: jest.fn() } as never,
+ () => isLive,
+ persisted,
+ );
+ pending.push(saving);
+ return saving;
+ });
+ sendMessage = jest.fn().mockResolvedValue({ key: { id: 'S1', remoteJid: CHAT, fromMe: true } });
+ const socket = { sendMessage, onWhatsApp: (jid: string) => Promise.resolve([{ jid, exists: true }]) };
+ const host = {
+ getSocket: () => socket as unknown as WASocket,
+ getSocketOrNull: () => socket as unknown as WASocket,
+ logger: createLogger('baileys-history-revokes.spec'),
+ loadLib: () =>
+ Promise.resolve({
+ normalizeMessageContent: (m: unknown) => m,
+ getContentType: (m: object) => Object.keys(m)[0],
+ extractMessageContent: (m: unknown) => m,
+ proto: { Message: { ProtocolMessage: { Type: { REVOKE: 0 } } } },
+ downloadMediaMessage: () =>
+ new Promise(resolve => {
+ releaseMedia = () =>
+ resolve({
+ // eslint-disable-next-line @typescript-eslint/require-await
+ async *[Symbol.asyncIterator]() {
+ yield Buffer.from('private photo');
+ },
+ });
+ }),
+ } as never),
+ normalizedSelfJid: () => SELF,
+ toNeutralJid: (jid: string) => previews.toNeutralJid(jid),
+ toEngineJid: (jid: string) => jid,
+ extractEphemeralDuration: (msg: WAMessage) => previews.extractEphemeralDuration(msg),
+ recordMessage: (msg: WAMessage, type: Parameters<BaileysSessionStore['recordMessage']>[1]) =>
+ previews.recordMessage(msg, type),
+ recordMessageEdit: (...args: Parameters<BaileysSessionStore['recordMessageEdit']>) =>
+ previews.recordMessageEdit(...args),
+ upsertContacts: () => undefined,
+ getOnHistoryMessages: () => onHistory,
+ getOnMessageRevoked: () => liveFanout,
+ getOnMessage: () => liveFanout,
+ getOnMessageCreate: () => liveFanout,
+ getFetchDispatcher: () => undefined,
+ inboundLimiter: new ConcurrencyLimiter(4),
+ recordKeyLidMappings: () => undefined,
+ consumeOwnSend: () => false,
+ putStoredMessage: (msg: WAMessage) => raw.put('s1', msg),
+ getStoredMessage: (id: string) => raw.getMessage('s1', id),
+ updateStoredMessage: (id: string, change: (stored: WAMessage) => WAMessage | null) =>
+ raw.update('s1', id, change),
+ ensureReady: () => undefined,
+ };
+ events = new BaileysEvents(host as unknown as BaileysEventsHost);
+ const shared = {
+ ...host,
+ applyHistoryRevoke: (...args: Parameters<BaileysEvents['applyHistoryRevoke']>) =>
+ events.applyHistoryRevoke(...args),
+ wasDeletedForEveryone: (id: string) => events.wasDeletedForEveryone(id),
+ pendingEditOf: (id: string, key: WAMessage['key']) => events.pendingEditOf(id, key),
+ };
+ history = new BaileysHistory(shared as unknown as BaileysHistoryHost);
+ messaging = new BaileysMessaging(shared as never);
+ });
+
+ afterEach(async () => {
+ await Promise.all(pending);
+ await ds.destroy();
+ });
+
+ const capture = async (messages: WAMessage[]): Promise<void> => {
+ await history.captureHistoryMessages(messages);
+ await Promise.all(pending);
+ };
+ const cleared = async (): Promise<Message> => {
+ const row = await repo.findOneByOrFail({ sessionId: 's1', waMessageId: 'M1' });
+ expect(row).toMatchObject({ body: '', type: 'revoked', metadata: null, mediaPath: null, mediaMimetype: null });
+ expect(liveFanout).not.toHaveBeenCalled();
+ return row;
+ };
+
+ it.each([false, true])('persists a cleared target in either batch order (reversed=%s)', async reversed => {
+ const batch = [target(), revoke()];
+ await capture(reversed ? batch.reverse() : batch);
+ await cleared();
+ expect(previews.listChats().find(chat => chat.id === '[email protected]')).toMatchObject({
+ lastMessage: '',
+ lastMessageType: 'revoked',
+ });
+ });
+
+ it('clears stored poll, archive, quote and reaction data in a revoke-only chunk', async () => {
+ const poll = target({
+ message: {
+ pollCreationMessageV3: {
+ name: 'Private question',
+ options: [{ optionName: 'Secret' }],
+ selectableOptionsCount: 1,
+ },
+ },
+ });
+ await capture([poll]);
+ const row = await repo.findOneByOrFail({ waMessageId: 'M1' });
+ expect(row.metadata.poll).toBeDefined();
+ await repo.update(row.id, {
+ metadata: {
+ ...row.metadata,
+ media: { data: 'secret' },
+ quotedMessage: { body: 'secret' },
+ reactions: { sender: 'yes' },
+ },
+ mediaPath: 's1/secret.jpg',
+ mediaMimetype: 'image/jpeg',
+ });
+ await raw.put('s1', poll);
+ await capture([revoke()]);
+ await cleared();
+ expect(onHistory).toHaveBeenCalledTimes(2);
+ expect(persisted).toHaveBeenCalledWith(
+ expect.objectContaining({ id: row.id, body: '', type: 'revoked', metadata: null }),
+ );
+ expect((await raw.getMessage('s1', 'M1'))?.message).toBeNull();
+ await expect(messaging.replyToMessage(CHAT, 'M1', 'reply')).rejects.toBeInstanceOf(MessageNotFoundError);
+ await expect(messaging.forwardMessage(CHAT, SELF, 'M1')).rejects.toBeInstanceOf(MessageNotFoundError);
+ expect(sendMessage).not.toHaveBeenCalled();
+ });
+
+ it('keeps a tombstone when the target arrives in a later history chunk', async () => {
+ await capture([revoke()]);
+ await cleared();
+ await capture([target()]);
+ expect(await cleared()).toMatchObject({ timestamp: 1_700_000_000, createdAt: new Date(1_700_000_000_000) });
+ expect(previews.listChats().find(chat => chat.id === '[email protected]')).toMatchObject({
+ lastMessage: '',
+ lastMessageType: 'revoked',
+ });
+ });
+
+ it('keeps the preview cleared after the bounded raw-cache marker has been evicted', async () => {
+ await raw.put('s1', target());
+ await capture([revoke()]);
+ for (let i = 0; i <= BaileysEvents.DELETED_FOR_EVERYONE_LIMIT; i++) events.markDeletedForEveryone(`other-${i}`);
+ expect(events.wasDeletedForEveryone('M1')).toBe(false);
+ await capture([target()]);
+ await cleared();
+ expect(previews.listChats().find(chat => chat.id === '[email protected]')).toMatchObject({
+ lastMessage: '',
+ lastMessageType: 'revoked',
+ });
+ });
+
+ it('keeps the tombstone when a concurrent content chunk finishes its dedup query later', async () => {
+ const find = repo.find.bind(repo);
+ let releaseFind!: () => void;
+ const gate = new Promise<void>(resolve => {
+ releaseFind = resolve;
+ });
+ const spy = jest
+ .spyOn(repo, 'find')
+ .mockImplementationOnce(async () => {
+ await gate;
+ return [];
+ })
+ .mockImplementation(find);
+ const m: IncomingMessage = {
+ id: 'M1',
+ chatId: '[email protected]',
+ fromMe: false,
+ isGroup: false,
+ kind: 'individual',
+ body: 'withdrawn secret',
+ type: 'text',
+ timestamp: 1_700_000_000,
+ };
+ const content = persistHistoryMessages(repo, undefined, 's1', [m], { log: jest.fn() } as never, () => true);
+ await capture([revoke()]);
+ releaseFind();
+ await content;
+ spy.mockRestore();
+ expect(await cleared()).toMatchObject({ timestamp: 1_700_000_000, createdAt: new Date(1_700_000_000_000) });
+ });
+
+ it('clears an original still downloading its media without live fanout', async () => {
+ const photo = target({ message: { imageMessage: { mimetype: 'image/jpeg', caption: 'withdrawn secret' } } });
+ events.handleMessagesUpsert({ messages: [photo], type: 'notify' });
+ for (let i = 0; i < 20 && !releaseMedia; i++) await new Promise<void>(resolve => setImmediate(resolve));
+ expect(releaseMedia).toBeDefined();
+ await capture([revoke()]);
+ releaseMedia();
+ for (let i = 0; i < 20; i++) await new Promise<void>(resolve => setImmediate(resolve));
+ await cleared();
+ expect((await raw.getMessage('s1', 'M1'))?.message).toBeNull();
+ });
+
+ it.each([
+ ['another chat', { remoteJid: SELF }],
+ ['another author', { fromMe: true }],
+ ])('rejects a revoke from %s in the same batch and raw cache', async (_label, envelope) => {
+ await raw.put('s1', target());
+ await capture([target(), revoke(target().key, envelope)]);
+ expect(await repo.findOneByOrFail({ waMessageId: 'M1' })).toMatchObject({ body: 'withdrawn secret', type: 'text' });
+ expect((await raw.getMessage('s1', 'M1'))?.message).toEqual(target().message);
+ });
+
+ it.each([
+ ['another chat', { remoteJid: SELF }],
+ ['another author', { fromMe: true }],
+ ])('preserves a prior SQL row when a revoke targets %s without a raw copy', async (_label, key) => {
+ await capture([target()]);
+ const other = { ...target().key, ...key };
+ await capture([revoke(other, { fromMe: other.fromMe })]);
+ await capture([target()]);
+ expect(await repo.findOneByOrFail({ waMessageId: 'M1' })).toMatchObject({ body: 'withdrawn secret', type: 'text' });
+ expect(previews.listChats().find(chat => chat.id === '[email protected]')).toMatchObject({
+ lastMessage: 'withdrawn secret',
+ lastMessageType: 'text',
+ });
+ });
+
+ it('accepts a group admin revoke and preserves the original outgoing direction', async () => {
+ const own = target({ key: { id: 'M1', remoteJid: '[email protected]', fromMe: true } });
+ await raw.put('s1', own);
+ await capture([own, revoke(own.key, { fromMe: false, participant: CHAT })]);
+ expect(await cleared()).toMatchObject({ direction: MessageDirection.OUTGOING, from: '[email protected]', author: null });
+ expect((await raw.getMessage('s1', 'M1'))?.message).toBeNull();
+ });
+
+ it('does not write history tombstones after the session is retired', async () => {
+ isLive = false;
+ await capture([revoke()]);
+ expect(await repo.count()).toBe(0);
+ });
+
+ it('does not apply a history revoke whose raw lookup outlives unlinking', async () => {
+ await raw.put('s1', target());
+ let release!: (message: WAMessage) => void;
+ const spy = jest.spyOn(raw, 'getMessage').mockImplementationOnce(
+ () =>
+ new Promise(resolve => {
+ release = resolve;
+ }),
+ );
+ const applying = events.applyHistoryRevoke(target().key, revoke().key);
+ events.fenceStoredWrites();
+ release(target());
+ expect(await applying).toBeUndefined();
+ spy.mockRestore();
+ expect((await raw.getMessage('s1', 'M1'))?.message).toEqual(target().message);
+ });
+
+ it('clears old content with retention enabled without inserting old content again', async () => {
+ await capture([target()]);
+ const previous = process.env.MESSAGE_RETENTION_DAYS;
+ process.env.MESSAGE_RETENTION_DAYS = '1';
+ try {
+ await capture([target(), revoke()]);
+ await cleared();
+ previews = new BaileysSessionStore(undefined, 's1');
+ previews.upsertChats([{ id: CHAT }]);
+ await capture([target()]);
+ expect(previews.listChats().find(chat => chat.id === '[email protected]')).toMatchObject({
+ lastMessage: '',
+ lastMessageType: 'revoked',
+ });
+ } finally {
+ if (previous === undefined) delete process.env.MESSAGE_RETENTION_DAYS;
+ else process.env.MESSAGE_RETENTION_DAYS = previous;
+ }
+ });
+});
diff --git a/src/engine/adapters/baileys-history.spec.ts b/src/engine/adapters/baileys-history.spec.ts
index a248a6aae..c17cc3e97 100644
--- a/src/engine/adapters/baileys-history.spec.ts
+++ b/src/engine/adapters/baileys-history.spec.ts
@@ -34,6 +34,8 @@ describe('history chat previews', () => {
recordMessageEdit: (...args: Parameters<typeof store.recordMessageEdit>) => store.recordMessageEdit(...args),
upsertContacts: () => undefined,
getOnHistoryMessages: () => () => undefined,
+ applyHistoryRevoke: (key: WAMessage['key']) => Promise.resolve(key),
+ wasDeletedForEveryone: () => false,
} as unknown as BaileysHistoryHost;
const history = new BaileysHistory(host);
await history.captureHistoryMessages(reversed ? [...messages].reverse() : messages);
diff --git a/src/engine/adapters/baileys-history.ts b/src/engine/adapters/baileys-history.ts
index 78c0af604..e1821bf9b 100644
--- a/src/engine/adapters/baileys-history.ts
+++ b/src/engine/adapters/baileys-history.ts
@@ -1,9 +1,8 @@
import type * as BaileysLib from '@whiskeysockets/baileys';
-import type { Chat, Contact as BaileysContact, WAMessage, WASocket } from '@whiskeysockets/baileys';
+import type { Chat, Contact as BaileysContact, WAMessage, WAMessageKey, WASocket } from '@whiskeysockets/baileys';
import { EngineEventCallbacks, IncomingMessage, MessageType } from '../interfaces/whatsapp-engine.interface';
import {
BAILEYS_NON_CONTENT_TYPES,
- baileysChatJid,
buildIncomingMessageFromBaileys,
extractBaileysBody,
extractBaileysButtonReply,
@@ -32,6 +31,7 @@ export interface BaileysHistoryHost {
/** Seed the chat's last-message preview + sort time from a history/live message. */
recordMessage(msg: WAMessage, type?: MessageType): void;
recordMessageEdit(chatId: string, messageId: string, text: string, type?: MessageType): void;
+ applyHistoryRevoke(target: WAMessageKey, envelope: WAMessageKey): Promise<WAMessageKey | undefined>;
upsertContacts(records: Partial<BaileysContact>[]): void;
upsertChats(records: Partial<Chat>[]): void;
/**
@@ -107,7 +107,8 @@ export class BaileysHistory {
const b = await this.host.loadLib();
const nameUpdates: { id: string; notify: string }[] = [];
const mapped: IncomingMessage[] = [];
- const revokes: { chatId: string; messageId: string }[] = [];
+ const revokes: { message: WAMessage; target: WAMessageKey }[] = [];
+ const targets = new Map(messages.filter(msg => msg.key?.id).map(msg => [msg.key.id!, msg]));
for (const msg of messages) {
if (msg.key?.fromMe !== true && msg.pushName) {
const sender = msg.key?.participant ?? msg.key?.remoteJid;
@@ -117,30 +118,60 @@ export class BaileysHistory {
}
const incoming = this.mapHistoryMessage(b, msg);
if (incoming) {
- // Only content messages replace the preview; reactions and protocol updates do not.
- this.host.recordMessage(msg, incoming.type);
mapped.push(incoming);
} else if (msg.key?.remoteJid) {
const content = b.normalizeMessageContent(msg.message) ?? msg.message;
const protocol = content?.protocolMessage;
if (protocol && protocol.type === b.proto.Message.ProtocolMessage.Type.REVOKE && protocol.key?.id) {
- revokes.push({
- chatId: baileysChatJid(msg.key.remoteJid, msg.key.participant, msg.key.fromMe === true),
- messageId: protocol.key.id,
- });
+ revokes.push({ message: msg, target: protocol.key });
}
}
}
- // History batches can put a revoke before its target. Update only the target preview after all content.
- for (const { chatId, messageId } of revokes) this.host.recordMessageEdit(chatId, messageId, '', 'revoked');
+ // Targets can precede or follow their revokes, including across separate history chunks.
+ for (const { message, target } of revokes) {
+ const original = targets.get(target.id!);
+ const key = await this.host.applyHistoryRevoke(
+ original?.key ?? { ...target, remoteJid: target.remoteJid ?? message.key.remoteJid },
+ message.key,
+ );
+ if (!key?.remoteJid) continue;
+ const cleared = this.revokedMessage(key, toUnixSeconds(original?.messageTimestamp ?? message.messageTimestamp));
+ mapped.push(cleared);
+ }
if (nameUpdates.length) {
this.host.upsertContacts(nameUpdates);
}
if (mapped.length) {
- this.host.getOnHistoryMessages()?.(mapped);
+ const storedRevokes = await this.host.getOnHistoryMessages()?.(mapped);
+ const revoked = (storedRevokes ?? mapped).filter(m => m.type === 'revoked');
+ const revokedKeys = new Set(revoked.map(m => JSON.stringify([m.id, m.chatId, m.fromMe])));
+ for (const incoming of mapped) {
+ if (incoming.type === 'revoked') continue;
+ const original = targets.get(incoming.id)!;
+ const deleted = revokedKeys.has(JSON.stringify([incoming.id, incoming.chatId, incoming.fromMe]));
+ this.host.recordMessage(original, deleted ? 'revoked' : incoming.type);
+ }
+ for (const m of revoked) this.host.recordMessageEdit(m.chatId, m.id, '', 'revoked');
}
}
+ private revokedMessage(key: WAMessageKey, timestamp: number): IncomingMessage {
+ const message = buildIncomingMessageFromBaileys(
+ {
+ id: key.id!,
+ remoteJid: key.remoteJid!,
+ fromMe: key.fromMe === true,
+ participant: key.participant ?? undefined,
+ body: '',
+ contentType: undefined,
+ timestamp,
+ selfJid: this.host.normalizedSelfJid(),
+ },
+ jid => this.host.toNeutralJid(jid),
+ );
+ return { ...message, type: 'revoked' };
+ }
+
/**
* Backfill chat/contact display names after connect. Baileys 6.7.x often skips the initial app-state
* sync (the state machine goes Online before it runs) and the PUSH_NAME sync can fail to decrypt, so
diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.ts
index 096154d41..ce49e54c6 100644
--- a/src/engine/adapters/baileys-lifecycle.ts
+++ b/src/engine/adapters/baileys-lifecycle.ts
@@ -510,7 +510,9 @@ export class BaileysLifecycle {
);
this.host.upsertChats(history.chats);
this.host.addLidMappings(history.lidPnMappings ?? []);
- void this.host.captureHistoryMessages(history.messages ?? []);
+ void this.host
+ .captureHistoryMessages(history.messages ?? [])
+ .catch(error => this.host.logger.warn('Failed to capture history messages', { error: String(error) }));
this.host.logger.debug('History sync received', {
action: 'baileys_history_set',
sessionId: this.host.config.sessionId,
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index e5e4aeb17..092b98cb2 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -2170,6 +2170,26 @@ describe('BaileysAdapter inbound fan-out', () => {
});
});
+ it('handles a rejected async history consumer without an unhandled rejection', async () => {
+ const onHistoryMessages = jest.fn().mockRejectedValue(new Error('history unavailable'));
+ const adapter = newAdapter();
+ await adapter.initialize({ onHistoryMessages });
+ fakeSock.fire('messaging-history.set', {
+ contacts: [],
+ chats: [],
+ messages: [
+ {
+ key: { remoteJid: '[email protected]', fromMe: false, id: 'H_FAIL' },
+ message: { conversation: 'history' },
+ messageTimestamp: 1700000000,
+ },
+ ],
+ });
+ await new Promise(resolve => setImmediate(resolve));
+ await new Promise(resolve => setImmediate(resolve));
+ expect(onHistoryMessages).toHaveBeenCalledTimes(1);
+ });
+
it('maps an ephemeral-wrapped history message to its real type and body (not unknown/empty)', async () => {
const onHistoryMessages = jest.fn();
const adapter = newAdapter();
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 38edbc8b1..1d566616a 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -148,6 +148,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
this.config.messageStore?.update(this.config.dbSessionId, messageId, change),
wasDeletedForEveryone: messageId => this.events.wasDeletedForEveryone(messageId),
markDeletedForEveryone: messageId => this.events.markDeletedForEveryone(messageId),
+ applyHistoryRevoke: (target, envelope) => this.events.applyHistoryRevoke(target, envelope),
pendingEditOf: (messageId, target) => this.events.pendingEditOf(messageId, target),
rememberOwnSend: id => this.ownSends.remember(id),
consumeOwnSend: id => this.ownSends.consume(id),
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index c24efd5f1..0010dab68 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -831,8 +831,9 @@ export interface EngineEventCallbacks {
/**
* Bulk historical messages from an engine's initial sync (e.g. Baileys `messaging-history.set`).
* They predate the live session, so consumers persist them for the chat view but must not dispatch.
+ * An async consumer may return stored revocations to keep previews cleared across resyncs.
*/
- onHistoryMessages?: (messages: IncomingMessage[]) => void;
+ onHistoryMessages?: (messages: IncomingMessage[]) => void | Promise<IncomingMessage[] | void>;
onDisconnected?: (reason: string) => void;
/**
* Fired each time the engine schedules an INTERNAL reconnect attempt: a drop it retries on its own
diff --git a/src/modules/events/events.gateway.chat-scope.spec.ts b/src/modules/events/events.gateway.chat-scope.spec.ts
index 5af3b9886..cd90b1856 100644
--- a/src/modules/events/events.gateway.chat-scope.spec.ts
+++ b/src/modules/events/events.gateway.chat-scope.spec.ts
@@ -46,7 +46,10 @@ describe('chat-scoped WebSocket rooms', () => {
gateway.handleMessage(client as unknown as Socket, { type: 'subscribe', sessionId, events });
const events = (client: ReturnType<typeof socket>) =>
client.emit.mock.calls
- .map(([, frame]) => frame as { type: string; payload: { event: string } })
+ .map(
+ ([, frame]) =>
+ frame as { type: string; payload: { event: string; sessionId: string; data: Record<string, unknown> } },
+ )
.filter(frame => frame.type === 'event');
const flush = () => new Promise<void>(resolve => setImmediate(resolve));
const connect = async (id: string, chats: string[] | null, sessions: string[] | null = ['s1'], sessionId = 's1') => {
@@ -169,6 +172,45 @@ describe('chat-scoped WebSocket rooms', () => {
expect(events(unrestricted)).toHaveLength(1);
});
+ it.each([false, true])('preserves session event order across slow lookups (failed edit: %s)', async failed => {
+ const allowed = await connect('allowed', [PHONE], null, '*');
+ const unrestricted = await connect('unrestricted', null, null, '*');
+ let finishFirst!: (ids: string[]) => void;
+ resolveIds
+ .mockImplementationOnce(() => new Promise<string[]>(resolve => (finishFirst = resolve)))
+ .mockImplementationOnce(() =>
+ failed ? Promise.reject(new Error('Mapping lookup unavailable')) : Promise.resolve([PHONE]),
+ );
+
+ gateway.emitMessage('s1', { chatId: PHONE, id: 'm1', body: 'original' });
+ gateway.emitMessageEdited('s1', { chatId: '123456@lid', messageId: 'm1', body: 'edited' });
+ gateway.emitMessageReaction('s1', { chatId: PHONE, messageId: 'm1', reaction: 'ok' });
+ gateway.emitMessage('s2', { chatId: PHONE, id: 'm2' });
+ await flush();
+ expect(events(allowed).map(frame => frame.payload.sessionId)).toEqual(['s2']);
+ expect(events(unrestricted).map(frame => frame.payload.event)).toEqual([
+ 'message.received',
+ 'message.edited',
+ 'message.reaction',
+ 'message.received',
+ ]);
+
+ finishFirst([PHONE]);
+ await flush();
+ expect(
+ events(allowed)
+ .filter(frame => frame.payload.sessionId === 's1')
+ .map(frame => frame.payload.event),
+ ).toEqual(
+ failed ? ['message.received', 'message.reaction'] : ['message.received', 'message.edited', 'message.reaction'],
+ );
+
+ lidPhone = '628111000111';
+ gateway.emitMessage('s1', { chatId: '123456@lid', id: 'm3' });
+ await flush();
+ expect(events(allowed).at(-1)?.payload.data.id).toBe('m3');
+ });
+
it('deduplicates chat rooms across wildcard and specific sessions', async () => {
const allowed = await connect('allowed', [PHONE], null, '*');
await subscribe(allowed, ['*', 'message.received']);
diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.ts
index 7293f3b06..4d58436fc 100644
--- a/src/modules/events/events.gateway.ts
+++ b/src/modules/events/events.gateway.ts
@@ -146,6 +146,7 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
* an already-subscribed socket keeps receiving events until it happens to disconnect).
*/
private readonly socketsByKeyId = new Map<string, Set<Socket>>();
+ private readonly chatDeliveries = new Map<string, Promise<void>>();
private authzSweepTimer?: ReturnType<typeof setInterval>;
/**
@@ -793,9 +794,15 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
}
// Expand the emitted identity using current persisted mappings, so new LID mappings work
// without rejoining rooms. Literal allowlist rooms also enforce the fence across Redis nodes.
- void this.chatScope
- .idsForFilter({ allowedChats: [chatId] })
- .then(ids => {
+ // Resolve identities concurrently, but retain event order within each session, including
+ // after a failed lookup. Other sessions and unrestricted broadcasts remain independent.
+ const delivery = Promise.allSettled([
+ this.chatDeliveries.get(sessionId),
+ this.chatScope.idsForFilter({ allowedChats: [chatId] }),
+ ])
+ .then(([, resolved]) => {
+ if (resolved.status === 'rejected') throw resolved.reason;
+ const ids = resolved.value;
if (!ids?.length) return;
const rooms = ids.flatMap(id => [
chatRoom(sessionId, event, id),
@@ -809,7 +816,11 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
this.logger.warn('Could not resolve chat identity for WebSocket delivery', {
error: error instanceof Error ? error.message : String(error),
}),
- );
+ )
+ .finally(() => {
+ if (this.chatDeliveries.get(sessionId) === delivery) this.chatDeliveries.delete(sessionId);
+ });
+ this.chatDeliveries.set(sessionId, delivery);
}
/**
diff --git a/src/modules/session/message-history-projector.ts b/src/modules/session/message-history-projector.ts
index 7a9a7d708..3b0a4742c 100644
--- a/src/modules/session/message-history-projector.ts
+++ b/src/modules/session/message-history-projector.ts
@@ -1,16 +1,16 @@
import { ConfigService } from '@nestjs/config';
-import { Repository, In } from 'typeorm';
+import { Repository, In, Raw } from 'typeorm';
import { QueryDeepPartialEntity } from 'typeorm';
import { Message, MessageDirection, MessageStatus } from '../message/entities/message.entity';
-import { buildMessageMetadata } from './message-row.mapper';
+import { buildMessageMetadata, REVOKED_ROW_PATCH } from './message-row.mapper';
import { resolveFeatureFlags } from '../../config/feature-flags';
import { IncomingMessage } from '../../engine/interfaces/whatsapp-engine.interface';
import { LoggerService } from '../../common/services/logger.service';
import { resolveMessageRetentionCutoff } from '../message/message-retention.service';
/**
- * Persist pre-connection history into the `messages` table for the chat view, without webhook/hook/ws
- * dispatch (it predates the live session). De-duplicated by `waMessageId` so re-syncs never duplicate.
+ * Persist pre-connection history without live dispatch. Stored revocations also notify plugin indexes
+ * and return cleared identities for the engine's previews. Re-syncs de-duplicate by `waMessageId`.
*/
export async function persistHistoryMessages(
messageRepository: Repository<Message>,
@@ -19,7 +19,9 @@ export async function persistHistoryMessages(
messages: IncomingMessage[],
logger: LoggerService,
isLive: () => boolean,
-): Promise<void> {
+ notifyRevoked?: (row: Message) => void,
+): Promise<IncomingMessage[]> {
+ const cleared: IncomingMessage[] = [];
const storeEphemeralMessages = resolveFeatureFlags(configService).storeEphemeralMessages;
// Rows are stamped with WhatsApp's own time below, so history older than the retention window
// would be written only for the next prune to delete it again.
@@ -36,13 +38,10 @@ export async function persistHistoryMessages(
if (!storeEphemeralMessages && (m.ephemeralDuration ?? 0) > 0) {
continue;
}
- if (retentionCutoffMs !== undefined && m.timestamp && m.timestamp * 1000 < retentionCutoffMs) {
- continue;
- }
- byId.set(m.id, m);
+ if (byId.get(m.id)?.type !== 'revoked' || m.type === 'revoked') byId.set(m.id, m);
}
if (byId.size === 0) {
- return;
+ return cleared;
}
// Chunk the dedup query: a batch can be thousands, past SQLite's bound-variable limit for IN (...).
const ids = [...byId.keys()];
@@ -52,7 +51,7 @@ export async function persistHistoryMessages(
const chunkIds = ids.slice(i, i + CHUNK);
const existing = await messageRepository.find({
where: { sessionId: id, waMessageId: In(chunkIds) },
- select: { waMessageId: true },
+ select: { waMessageId: true, type: true },
});
// A delete() can retire the engine while a large batch works through its chunks; its transaction
// has then already cleared this session's messages, and a row inserted after it (no FK) would
@@ -60,7 +59,18 @@ export async function persistHistoryMessages(
if (!isLive()) break;
const seen = new Set(existing.map(r => r.waMessageId));
const rows = chunkIds
- .filter(x => !seen.has(x))
+ .filter(x => !seen.has(x) || byId.get(x)?.type === 'revoked')
+ // Old content is read for revocation checks but never reinserted. Content-free tombstones
+ // must still clear a retained row and its preview, then follow ordinary retention pruning.
+ .filter(x => {
+ const m = byId.get(x)!;
+ return (
+ m.type === 'revoked' ||
+ retentionCutoffMs === undefined ||
+ !m.timestamp ||
+ m.timestamp * 1000 >= retentionCutoffMs
+ );
+ })
.map(x => {
const m = byId.get(x)!;
const metadata = buildMessageMetadata(m, true);
@@ -80,6 +90,7 @@ export async function persistHistoryMessages(
status: MessageStatus.SENT,
metadata,
});
+ if (m.type === 'revoked') Object.assign(row, REVOKED_ROW_PATCH);
// The chat panel orders by createdAt; stamp the real time so history sorts correctly.
if (m.timestamp) {
row.createdAt = new Date(m.timestamp * 1000);
@@ -98,6 +109,69 @@ export async function persistHistoryMessages(
.execute();
inserted += rows.length;
}
+ // Insert the tombstone before clearing an existing row: concurrent content inserts then either
+ // lose the unique-key race or are cleared here, and a later chunk cannot resurrect the payload.
+ for (const messageId of chunkIds) {
+ const m = byId.get(messageId)!;
+ if (m.type !== 'revoked') continue;
+ if (!isLive()) break;
+ await messageRepository.update(
+ {
+ sessionId: id,
+ waMessageId: messageId,
+ chatId: m.chatId,
+ direction: m.fromMe ? MessageDirection.OUTGOING : MessageDirection.INCOMING,
+ },
+ REVOKED_ROW_PATCH,
+ );
+ }
+ // An absent target first carries the revoke time. A later original supplies its real time,
+ // even when a concurrent tombstone made its insert lose after the initial dedup query.
+ if (rows.length || existing.some(row => row.type === 'revoked')) {
+ const revoked = await messageRepository.find({
+ where: { sessionId: id, waMessageId: In(chunkIds), type: 'revoked' },
+ });
+ for (const row of revoked) {
+ const m = byId.get(row.waMessageId)!;
+ if (!isLive()) break;
+ const direction = m.fromMe ? MessageDirection.OUTGOING : MessageDirection.INCOMING;
+ if (row.chatId !== m.chatId || row.direction !== direction || !Number.isFinite(m.timestamp)) continue;
+ if (row.timestamp == null || row.timestamp > m.timestamp) {
+ const result = await messageRepository.update(
+ {
+ sessionId: id,
+ waMessageId: m.id,
+ chatId: m.chatId,
+ direction,
+ type: 'revoked',
+ timestamp: Raw(alias => `(${alias} IS NULL OR ${alias} > :historyTimestamp)`, {
+ historyTimestamp: m.timestamp,
+ }),
+ },
+ { timestamp: m.timestamp, createdAt: new Date(m.timestamp * 1000) },
+ );
+ if (result.affected) {
+ row.timestamp = m.timestamp;
+ row.createdAt = new Date(m.timestamp * 1000);
+ }
+ }
+ if (!isLive()) break;
+ cleared.push({
+ id: m.id,
+ chatId: m.chatId,
+ from: m.from,
+ to: m.to,
+ fromMe: m.fromMe,
+ isGroup: m.isGroup,
+ kind: m.kind,
+ author: m.author,
+ type: 'revoked',
+ body: '',
+ timestamp: Math.min(row.timestamp ?? m.timestamp, m.timestamp),
+ });
+ if (m.type === 'revoked') notifyRevoked?.(row);
+ }
+ }
}
if (inserted) {
logger.log(`Persisted ${inserted} history message(s)`, {
@@ -106,4 +180,5 @@ export async function persistHistoryMessages(
action: 'history_messages_persisted',
});
}
+ return cleared;
}
diff --git a/src/modules/session/message-projector.service.spec.ts b/src/modules/session/message-projector.service.spec.ts
index 833acfe18..e732a5767 100644
--- a/src/modules/session/message-projector.service.spec.ts
+++ b/src/modules/session/message-projector.service.spec.ts
@@ -52,6 +52,7 @@ describe('MessageProjector', () => {
emitMessageReaction: jest.Mock;
};
let webhookService: { dispatch: jest.Mock };
+ let hookManager: { execute: jest.Mock };
let engines: EngineRegistry;
let engine: IWhatsAppEngine;
let projector: MessageProjector;
@@ -70,6 +71,7 @@ describe('MessageProjector', () => {
emitMessageReaction: jest.fn(),
};
webhookService = { dispatch: jest.fn().mockResolvedValue(undefined) };
+ hookManager = { execute: jest.fn().mockResolvedValue(undefined) };
engines = new EngineRegistry();
engine = {} as IWhatsAppEngine;
engines.set('s1', engine);
@@ -79,7 +81,7 @@ describe('MessageProjector', () => {
engines,
eventsGateway as unknown as EventsGateway,
webhookService as unknown as WebhookService,
- { execute: jest.fn().mockResolvedValue(undefined) } as unknown as HookManager,
+ hookManager as unknown as HookManager,
{} as unknown as StatusStoreService,
{ resolveSenderPhone: jest.fn().mockResolvedValue(null) } as unknown as SessionLidResolver,
);
@@ -249,6 +251,40 @@ describe('MessageProjector', () => {
});
describe('persistHistoryMessages', () => {
+ it('updates plugin indexes after a history revoke without dispatching live events', async () => {
+ const row = {
+ id: 'db-id',
+ waMessageId: 'WA1',
+ chatId: '[email protected]',
+ direction: MessageDirection.INCOMING,
+ type: 'revoked',
+ body: '',
+ metadata: null,
+ timestamp: 1_700_000_000,
+ };
+ messageRepository.find.mockResolvedValueOnce([{ waMessageId: 'WA1', type: 'text' }]).mockResolvedValueOnce([row]);
+ const builder = {
+ insert: jest.fn().mockReturnThis(),
+ values: jest.fn().mockReturnThis(),
+ orIgnore: jest.fn().mockReturnThis(),
+ execute: jest.fn().mockResolvedValue({}),
+ };
+ Object.assign(messageRepository, { createQueryBuilder: jest.fn().mockReturnValue(builder) });
+ hookManager.execute.mockRejectedValueOnce(new Error('index unavailable'));
+ const result = await projector.persistHistoryMessages('s1', engine, [
+ historyMessage({ type: 'revoked', fromMe: false, body: '' }),
+ ]);
+ await settle();
+ expect(result).toEqual([expect.objectContaining({ id: 'WA1', type: 'revoked', body: '' })]);
+ expect(hookManager.execute).toHaveBeenCalledWith(
+ 'message:persisted',
+ { sessionId: 's1', message: row },
+ { sessionId: 's1', source: 'SessionService' },
+ );
+ expect(webhookService.dispatch).not.toHaveBeenCalled();
+ expect(eventsGateway.emitMessage).not.toHaveBeenCalled();
+ });
+
it('skips rows that cannot become a valid message row, and queries nothing when none survive', async () => {
await projector.persistHistoryMessages('s1', engine, [
historyMessage({ id: '' }), // no id -> cannot de-dup
@@ -286,7 +322,7 @@ describe('MessageProjector', () => {
expect(dedupIds(messageRepository.find)).toEqual(['DUP']);
});
- it('skips history older than the MESSAGE_RETENTION_DAYS window', async () => {
+ it('checks old history for revocation without reinserting content outside retention', async () => {
const prev = process.env.MESSAGE_RETENTION_DAYS;
process.env.MESSAGE_RETENTION_DAYS = '30';
try {
@@ -298,7 +334,8 @@ describe('MessageProjector', () => {
historyMessage({ id: 'NEW', timestamp: nowSec - 29 * 86_400 }),
]);
- expect(dedupIds(messageRepository.find)).toEqual(['NEW']);
+ expect(dedupIds(messageRepository.find)).toEqual(['OLD', 'NEW']);
+ expect(messageRepository.create).not.toHaveBeenCalled();
} finally {
if (prev === undefined) delete process.env.MESSAGE_RETENTION_DAYS;
else process.env.MESSAGE_RETENTION_DAYS = prev;
diff --git a/src/modules/session/message-projector.service.ts b/src/modules/session/message-projector.service.ts
index e4fec9a38..8b77dff97 100644
--- a/src/modules/session/message-projector.service.ts
+++ b/src/modules/session/message-projector.service.ts
@@ -8,7 +8,7 @@ import { Message, MessageDirection, MessageStatus } from '../message/entities/me
import { EngineRegistry } from '../../engine/engine-registry.service';
import { KeyedMutationQueue } from '../../common/utils/keyed-mutation-queue';
import { SessionLidResolver } from './session-lid-resolver.service';
-import { buildMessageMetadata, storableWaMessageId } from './message-row.mapper';
+import { buildMessageMetadata, REVOKED_ROW_PATCH, storableWaMessageId } from './message-row.mapper';
import { MessageMutationProjector } from './message-mutation-projector';
import { updateMessageMetadata } from '../message/message-metadata';
import { persistHistoryMessages } from './message-history-projector';
@@ -59,20 +59,6 @@ import { isMessagePayload } from '../../core/hooks/hook-results';
*/
export const ACK_RECONCILE_DELAY_MS = 750;
-/**
- * What a revoke leaves of a stored message: the placeholder WhatsApp itself shows. Body, archived-media
- * pointers and metadata (inline media, quote, reactions, buttons) are all cleared, so the row carries
- * nothing of what the sender took back. The archived file, now unreferenced, is reaped by the chat-media
- * orphan sweep.
- */
-const REVOKED_ROW_PATCH = {
- body: '',
- type: 'revoked',
- metadata: null,
- mediaPath: null,
- mediaMimetype: null,
-} as unknown as QueryDeepPartialEntity<Message>;
-
/**
* Delay before the single retry of a message insert that failed transiently (lock contention, a
* dropped connection, a pool timeout). The engine delivers each message once, so without the retry
@@ -909,9 +895,20 @@ export class MessageProjector {
}
/** History backfill persist, extracted to message-history-projector.ts (stateless function). */
- persistHistoryMessages(id: string, engine: IWhatsAppEngine, messages: IncomingMessage[]): Promise<void> {
- return persistHistoryMessages(this.messageRepository, this.configService, id, messages, this.logger, () =>
- this.engines.isLive(id, engine),
+ persistHistoryMessages(id: string, engine: IWhatsAppEngine, messages: IncomingMessage[]): Promise<IncomingMessage[]> {
+ return persistHistoryMessages(
+ this.messageRepository,
+ this.configService,
+ id,
+ messages,
+ this.logger,
+ () => this.engines.isLive(id, engine),
+ row => {
+ if (!this.engines.isLive(id, engine)) return;
+ void this.hookManager
+ .execute('message:persisted', { sessionId: id, message: row }, { sessionId: id, source: 'SessionService' })
+ .catch(() => undefined);
+ },
);
}
diff --git a/src/modules/session/message-row.mapper.ts b/src/modules/session/message-row.mapper.ts
index 6d5aa5e77..cb2d6b338 100644
--- a/src/modules/session/message-row.mapper.ts
+++ b/src/modules/session/message-row.mapper.ts
@@ -1,4 +1,15 @@
import type { IncomingMessage } from '../../engine/interfaces/whatsapp-engine.interface';
+import type { QueryDeepPartialEntity } from 'typeorm';
+import type { Message } from '../message/entities/message.entity';
+
+/** Clear content and archive pointers while retaining the revoked message's identity. */
+export const REVOKED_ROW_PATCH = {
+ body: '',
+ type: 'revoked',
+ metadata: null,
+ mediaPath: null,
+ mediaMimetype: null,
+} as unknown as QueryDeepPartialEntity<Message>;
/**
* Message types whose rows must show a media placeholder even when the payload carried none.
diff --git a/src/modules/session/session-engine-event-wiring.ts b/src/modules/session/session-engine-event-wiring.ts
index b1bf8c95c..9d28ec823 100644
--- a/src/modules/session/session-engine-event-wiring.ts
+++ b/src/modules/session/session-engine-event-wiring.ts
@@ -234,10 +234,10 @@ export class SessionEngineEventWiring {
host.handleEngineReady(id, engine, phone, pushName);
},
onMessage: (message): void => host.messages.handleInboundMessage(id, engine, message),
- onHistoryMessages: (messages): void => {
+ onHistoryMessages: messages => {
if (!host.isLiveEngine(id, engine)) return;
// Persist for the chat view only; no dispatch (these predate the live session).
- void host.messages
+ return host.messages
.persistHistoryMessages(id, engine, messages)
.catch(err => this.logger.error(`Failed to persist history messages for ${id}`, String(err)));
},