Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): dispatch message.reaction even when the row is missing
Yudhi Armyndharis77c5e4b9aad6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a72782421..4578dd177 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed- **A WhatsApp-initiated unlink now clears a session's stored credentials once rather than twice** — whatsapp-web.js can raise the logout event more than once for a single unlink and nothing deduplicated it, so the repeats raced each other and a still-open browser into the `ENOTEMPTY` failure the removal now carries the retry budget to survive.+- **A reaction to a message the gateway never stored no longer vanishes** — the `message.reaction` webhook and the dashboard stream were both gated on the stored row, so a reaction to an ephemeral message, or to one that arrived before the session went live, was dropped with no error and no log.- **A data import now carries each session's ownership lease by its remaining time instead of its original deadline** — a restore re-applied the deadline unchanged, so one that ran longer than a claim had left committed that claim as expired, including claims held by other nodes whose engines never stopped.- **A refused data import no longer offers a retry that stops live engines** — the one refusal whose retry is destructive now carries `IMPORT_WOULD_ORPHAN_ENGINES` and the dashboard matches it positively, so a refusal that only asks the operator to wait can no longer present a confirm whose OK re-runs the replace-all with `stopOrphans=true`.- **A data import is refused with `409` when another transaction holds the connection** — on SQLite it would otherwise nest inside that transaction and commit into it rather than to disk, so a restore reported as successful could vanish with that transaction's rollback.diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex e25f64062..9408a6d16 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -416,12 +416,18 @@ export function Chats() {);const handleIncomingMessageReaction = useCallback(- (event: { sessionId: string; messageId: string; reactions: Record<string, string> }) => {+ (event: { sessionId: string; messageId: string; reactions?: Record<string, string> }) => {if (event.sessionId !== selectedSessionId) return;// Reactions update `metadata.reactions` while preserving `metadata.media` / `metadata.quotedMessage`,// so we must read the prior message and deep-merge — `updateMessage`'s shallow merge would clobber// the rest of metadata.+ //+ // `reactions` is absent when the gateway holds no stored copy of the message to snapshot from (an+ // ephemeral message, or one that predates the session going live). Absent means "unknown", not+ // "none", so the known map has to survive — overwriting it would drop the optimistic reaction the+ // user just added under the local `me` key. Folding in the single reported change instead would+ // double-count that same reaction under its real sender id, so we keep what we have.const caches = queryClient.getQueriesData<ChatMessageView[]>({queryKey: ['messages', event.sessionId],});@@ -433,7 +439,7 @@ export function Chats() {const next = list.slice();next[idx] = {...target,- metadata: { ...(target.metadata || {}), reactions: event.reactions },+ metadata: { ...(target.metadata || {}), reactions: event.reactions ?? target.metadata?.reactions },};queryClient.setQueryData(key, next);}diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex ea4d2b044..8d0a085d9 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -6104,7 +6104,7 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve| `message.ack` | A delivery/read receipt updates an outbound message | `{ id, messageId, status, ack }` — `status` is the canonical state (`pending`/`sent`/`delivered`/`read`/`failed`); `ack` is the deprecated legacy integer derived from it || `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.reaction` | A reaction is added, changed, or removed | `{ messageId, chatId, reaction, senderId, reactions? }` — `reactions` is the post-apply `{ senderId: emoji }` snapshot, omitted when the gateway holds no stored copy of the message to compute it from (an ephemeral message, or one predating the session going live); treat it as unknown rather than empty and keep the map you already hold. `reaction` is empty when removed || `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 }` |diff --git a/src/modules/session/message-mutation-projector.ts b/src/modules/session/message-mutation-projector.tsindex ce67a454d..1f0481393 100644--- a/src/modules/session/message-mutation-projector.ts+++ b/src/modules/session/message-mutation-projector.ts@@ -54,29 +54,40 @@ export class MessageMutationProjector {if (!event.messageId) return;const msg = await this.messageRepository.findOne({ where: { sessionId: id, waMessageId: event.messageId } });- if (!msg) return;- const metadata = msg.metadata || {};- const reactions = (metadata.reactions as Record<string, string>) || {};- if (!event.reaction) {- delete reactions[event.senderId];- } else {- reactions[event.senderId] = event.reaction;+ // The stored copy is best-effort — a message is absent whenever it was never persisted (an+ // ephemeral one under STORE_EPHEMERAL_MESSAGES=false, or one that arrived before the session+ // went live) — but the notification is not: `message.reaction` is a declared webhook event and+ // the dashboard stream is the point of it, the same contract handleMessageRevoked states.+ let reactions: Record<string, string> | undefined;+ if (msg) {+ const metadata = msg.metadata || {};+ reactions = (metadata.reactions as Record<string, string>) || {};+ if (!event.reaction) {+ delete reactions[event.senderId];+ } else {+ reactions[event.senderId] = event.reaction;+ }+ 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 — 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 }, {+ metadata,+ } as QueryDeepPartialEntity<Message>);}- 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 — 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 }, {- metadata,- } as QueryDeepPartialEntity<Message>);- this.eventsGateway.emitMessageReaction(id, { ...event, reactions });- // Webhook parity with the WebSocket broadcast: same payload (event + post-apply snapshot), so a- // webhook-only consumer observes reactions too. Idempotency for this event is salted per dispatch.- void this.webhookService.dispatch(id, 'message.reaction', { ...event, reactions });+ // `reactions` is the post-apply snapshot of EVERY reaction on the message and consumers REPLACE+ // their copy with it, so this one reaction must not stand in for the whole set — that would read+ // as the other senders having withdrawn theirs. Omitted means "no stored copy to snapshot",+ // which is the truth; present keeps today's contract byte for byte.+ const payload = reactions ? { ...event, reactions } : { ...event };+ this.eventsGateway.emitMessageReaction(id, payload);+ // Webhook parity with the WebSocket broadcast: same payload, so a webhook-only consumer observes+ // reactions too. Idempotency for this event is salted per dispatch.+ void this.webhookService.dispatch(id, 'message.reaction', payload);} catch (err) {this.logger.error(`Failed to update message reaction: ${event.messageId}`, String(err));}diff --git a/src/modules/session/message-projector.service.spec.ts b/src/modules/session/message-projector.service.spec.tsindex 649eb4ca5..c6df7dbc4 100644--- a/src/modules/session/message-projector.service.spec.ts+++ b/src/modules/session/message-projector.service.spec.ts@@ -25,6 +25,12 @@ const dedupIds = (find: jest.Mock, call = 0): string[] => {return calls[call][0].where.waMessageId._value;};+// The payload a webhook dispatch carried, reached without an `any` hop — same reason as dedupIds.+const dispatchPayload = (dispatch: jest.Mock, call = 0): Record<string, unknown> => {+ const calls = dispatch.mock.calls as Array<[string, string, Record<string, unknown>]>;+ return calls[call][2];+};+const historyMessage = (over: Partial<IncomingMessage> = {}): IncomingMessage =>({id: 'WA1',@@ -39,7 +45,12 @@ const historyMessage = (over: Partial<IncomingMessage> = {}): IncomingMessage =>describe('MessageProjector', () => {let messageRepository: { find: jest.Mock; findOne: jest.Mock; create: jest.Mock; update: jest.Mock };- let eventsGateway: { emitMessage: jest.Mock; emitMessageSent: jest.Mock; emitMessageRevoked: jest.Mock };+ let eventsGateway: {+ emitMessage: jest.Mock;+ emitMessageSent: jest.Mock;+ emitMessageRevoked: jest.Mock;+ emitMessageReaction: jest.Mock;+ };let webhookService: { dispatch: jest.Mock };let engines: EngineRegistry;let engine: IWhatsAppEngine;@@ -52,7 +63,12 @@ describe('MessageProjector', () => {create: jest.fn((x: unknown) => x),update: jest.fn().mockResolvedValue({ affected: 1 }),};- eventsGateway = { emitMessage: jest.fn(), emitMessageSent: jest.fn(), emitMessageRevoked: jest.fn() };+ eventsGateway = {+ emitMessage: jest.fn(),+ emitMessageSent: jest.fn(),+ emitMessageRevoked: jest.fn(),+ emitMessageReaction: jest.fn(),+ };webhookService = { dispatch: jest.fn().mockResolvedValue(undefined) };engines = new EngineRegistry();engine = {} as IWhatsAppEngine;@@ -125,6 +141,72 @@ describe('MessageProjector', () => {expect(messageRepository.findOne).not.toHaveBeenCalled();});++ it('still notifies consumers when the reacted message has no stored row', async () => {+ // Same contract as handleMessageRevoked: the stored copy is best-effort, but message.reaction is+ // a declared webhook event and the dashboard stream is the point of it. A row is absent whenever+ // the message was never persisted — an ephemeral message under STORE_EPHEMERAL_MESSAGES=false,+ // or one that arrived before the session went live.+ messageRepository.findOne.mockResolvedValue(null);++ projector.applyReactionQueued('s1', {+ messageId: 'WA1',+ chatId: '[email protected]',+ senderId: '[email protected]',+ reaction: '👍',+ });++ await settle();+ await settle();++ expect(webhookService.dispatch).toHaveBeenCalledWith('s1', 'message.reaction', expect.anything());+ expect(eventsGateway.emitMessageReaction).toHaveBeenCalledTimes(1);+ });++ it('omits the reactions snapshot when there is no stored row to compute it from', async () => {+ // `reactions` is the post-apply snapshot of EVERY reaction on the message, and consumers replace+ // their copy with it. Without the row that snapshot is unknowable, and sending this one reaction+ // as if it were the whole set would tell them the other senders had withdrawn theirs. Absent+ // means "we hold no copy", which is the truth.+ messageRepository.findOne.mockResolvedValue(null);++ projector.applyReactionQueued('s1', {+ messageId: 'WA1',+ chatId: '[email protected]',+ senderId: '[email protected]',+ reaction: '👍',+ });++ await settle();+ await settle();++ const payload = dispatchPayload(webhookService.dispatch);+ expect(payload).not.toHaveProperty('reactions');+ expect(payload).toMatchObject({ messageId: 'WA1', senderId: '[email protected]', reaction: '👍' });+ });++ it('still carries the full snapshot, and still writes it, when the row IS there', async () => {+ // The other half of the branch above: making the snapshot conditional must not make it optional+ // in the case that has always produced it. A prior sender's reaction survives in the map.+ messageRepository.findOne.mockResolvedValue({ metadata: { reactions: { '[email protected]': '❤️' } } });++ projector.applyReactionQueued('s1', {+ messageId: 'WA1',+ chatId: '[email protected]',+ senderId: '[email protected]',+ reaction: '👍',+ });++ await settle();+ await settle();++ const payload = dispatchPayload(webhookService.dispatch);+ expect(payload.reactions).toEqual({ '[email protected]': '❤️', '[email protected]': '👍' });+ expect(messageRepository.update).toHaveBeenCalledWith(+ { sessionId: 's1', waMessageId: 'WA1' },+ { metadata: { reactions: { '[email protected]': '❤️', '[email protected]': '👍' } } },+ );+ });});describe('handleMessageRevoked', () => {