Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(events): carry chatId in delivery events (#1773)
Yudhi Armyndharisdbfab8972eb6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e5f779771..d80224d50 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- Carry `chatId` in `message.ack` and `message.failed` payloads so a webhook `chatId` filter scopes delivery events per chat.- Filter stored messages by time, direction, type or message reference, with stable message-time pagination.- Expose poll choices and selection mode in message events, stored messages, history, and dashboard chats.- Expose optional last-message types in chat lists and SDKs.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex ff5d4eb17..1ba75aef4 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -4792,14 +4792,14 @@ Create a webhook for the session.**Request body** — `CreateWebhookDto`-| Field | Type | Required | Constraints | Description |-| ---------- | ---------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| url | string | yes | `@IsUrl({ require_tld: false, require_protocol: true, protocols: ['http', 'https'] })` (allows hostnames without a dot, e.g. `http://localhost:3000`), `@MaxCodePoints(2048)`; also run through the SSRF guard, which can reject with `400`. | Webhook URL to receive events. |-| events | string[] | no | `@IsArray`, `@ArrayMinSize(1)`, `@IsIn([...WEBHOOK_EVENTS, '*'], { each: true })` | Event names to subscribe to (see allowed set above). Defaults to `["message.received"]` when omitted. |-| secret | string | no | `@IsString`, `@MinLength(16)`, `@MaxCodePoints(255)` | HMAC-SHA256 signing key. **Write-only** — never returned by a webhook route (not returned by `GET /api/infra/export-data` either). Used for `X-OpenWA-Signature`. Defaults to `null`. |-| headers | Record<string,string> | no | `@IsHeaderMap()`: flat object (not array), ≤50 entries, names match `/^[A-Za-z0-9-]+$/` and are unique ignoring case, values are strings ≤1024 chars with no C0 control/DEL (CR/LF injection guard) and nothing above U+00FF (Latin-1 only). | Custom headers added to deliveries. **Write-only** — never returned by a webhook route (not returned by `GET /api/infra/export-data` either). At delivery, `content-type`, `user-agent` and `x-openwa-*` names are stripped, and so are the connection-level names the HTTP client owns: `connection`, `content-length`, `expect`, `keep-alive`, `te`, `trailer`, `transfer-encoding` and `upgrade`. Defaults to `{}`. |-| filters | WebhookFilters \| null | no | `@IsValidWebhookFilters()`, i.e. `{ conditions: [...] }`; each condition `{ field, operator('is'\|'isNot'\|'contains'\|'equals'), value(string\|string[]\|boolean), caseSensitive?:boolean }`; bounds: max 20 conditions, 100 values/condition, 1000-char text values. Message fields: `sender`, `recipient`, `chatId`, `body`, `type`, `isGroup`, `kind`, `fromMe`, `hasMedia`, `mentions`. An id-valued condition accepts a bare phone number, but a group must be written as its full `<id>@g.us` JID: bare digits canonicalise to `@c.us` and match no group. | Optional AND pre-filter; **all** conditions must match for the webhook to fire. Omit/null = fire on every subscribed event. Defaults to `null`. ⚠️ A condition whose field is DEFINED for the event family but absent from that event's payload does not scope the event, it decides it outright: an `is`, `contains` or `equals` condition cannot match and suppresses the event, while an `isNot` condition passes it, and so does a boolean field compared with `false`, because an absent boolean reads as `false` (a field with no definition for the family is skipped instead). `message.ack`/`message.failed` carry `{ id, messageId, status, ack }` and `message.reaction` carries `{ messageId, chatId, reaction, senderId }`, none of which has a sender or body, so a `sender` `is` filter silently drops all three and a `sender` `isNot` filter delivers all three. `message.ack`/`message.failed` carry no `chatId` either, so a `chatId` `isNot` exclusion does not keep that chat's acks and failures out. Scope the subscription with `events[]` rather than relying on a filter to be inert. Set `LOG_LEVEL=debug` to see each suppression and the payload fields that were available. |-| retryCount | number (int) | no | `@IsInt`, `@Min(0)`, `@Max(5)` | Total delivery attempts per event, including the first: `0` and `1` both mean a single attempt with no retry. An event that exhausts them is recorded in `GET /api/webhooks/delivery-failures`; the webhook stays active. Defaults to `3`. |+| Field | Type | Required | Constraints | Description |+| ---------- | ---------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| url | string | yes | `@IsUrl({ require_tld: false, require_protocol: true, protocols: ['http', 'https'] })` (allows hostnames without a dot, e.g. `http://localhost:3000`), `@MaxCodePoints(2048)`; also run through the SSRF guard, which can reject with `400`. | Webhook URL to receive events. |+| events | string[] | no | `@IsArray`, `@ArrayMinSize(1)`, `@IsIn([...WEBHOOK_EVENTS, '*'], { each: true })` | Event names to subscribe to (see allowed set above). Defaults to `["message.received"]` when omitted. |+| secret | string | no | `@IsString`, `@MinLength(16)`, `@MaxCodePoints(255)` | HMAC-SHA256 signing key. **Write-only** — never returned by a webhook route (not returned by `GET /api/infra/export-data` either). Used for `X-OpenWA-Signature`. Defaults to `null`. |+| headers | Record<string,string> | no | `@IsHeaderMap()`: flat object (not array), ≤50 entries, names match `/^[A-Za-z0-9-]+$/` and are unique ignoring case, values are strings ≤1024 chars with no C0 control/DEL (CR/LF injection guard) and nothing above U+00FF (Latin-1 only). | Custom headers added to deliveries. **Write-only** — never returned by a webhook route (not returned by `GET /api/infra/export-data` either). At delivery, `content-type`, `user-agent` and `x-openwa-*` names are stripped, and so are the connection-level names the HTTP client owns: `connection`, `content-length`, `expect`, `keep-alive`, `te`, `trailer`, `transfer-encoding` and `upgrade`. Defaults to `{}`. |+| filters | WebhookFilters \| null | no | `@IsValidWebhookFilters()`, i.e. `{ conditions: [...] }`; each condition `{ field, operator('is'\|'isNot'\|'contains'\|'equals'), value(string\|string[]\|boolean), caseSensitive?:boolean }`; bounds: max 20 conditions, 100 values/condition, 1000-char text values. Message fields: `sender`, `recipient`, `chatId`, `body`, `type`, `isGroup`, `kind`, `fromMe`, `hasMedia`, `mentions`. An id-valued condition accepts a bare phone number, but a group must be written as its full `<id>@g.us` JID: bare digits canonicalise to `@c.us` and match no group. | Optional AND pre-filter; **all** conditions must match for the webhook to fire. Omit/null = fire on every subscribed event. Defaults to `null`. ⚠️ A condition whose field is DEFINED for the event family but absent from that event's payload does not scope the event, it decides it outright: an `is`, `contains` or `equals` condition cannot match and suppresses the event, while an `isNot` condition passes it, and so does a boolean field compared with `false`, because an absent boolean reads as `false` (a field with no definition for the family is skipped instead). `message.ack`/`message.failed` carry `{ id, messageId, status, ack, chatId? }` and `message.reaction` carries `{ messageId, chatId, reaction, senderId }`, none of which has a sender or body, so a `sender` `is` filter silently drops all three and a `sender` `isNot` filter delivers all three. The `chatId` on an ack or failure is the conversation the acked message belongs to, present whenever the engine's update names the chat (both engines do on the live path), so a `chatId` condition scopes acks and failures to that chat; on a payload without it the generic absent-field rule above applies. Scope the subscription with `events[]` rather than relying on a filter to be inert. Set `LOG_LEVEL=debug` to see each suppression and the payload fields that were available. |+| retryCount | number (int) | no | `@IsInt`, `@Min(0)`, `@Max(5)` | Total delivery attempts per event, including the first: `0` and `1` both mean a single attempt with no retry. An event that exhausts them is recorded in `GET /api/webhooks/delivery-failures`; the webhook stays active. Defaults to `3`. |```json{@@ -7197,8 +7197,8 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `message.received` | An inbound message arrives | The full message object: `id`, `from`, `to`, `body`, `type`, `timestamp` (epoch **seconds**), `isGroup`, `kind` (user-facing chat discriminator of `chatId` — `individual\|group\|channel\|status\|broadcast\|unknown`), `fromMe`, `chatId`, `media{mimetype,filename?,data?,omitted?,sizeBytes?}` (media messages only), `contact{…}` (plus optional `senderPhone` for `@lid` senders, `order{orderId,token?}` / `product{productId,…}` on `order` / `product` messages, `buttons:[{id,text}]` on a WhatsApp Business prompt that offers choices, and `button{id,text?}` when the sender tapped one; **Baileys only**) || `message.sent` | An outbound message is created/sent from this session | Same message object shape as `message.received` |-| `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.ack` | A delivery/read receipt updates an outbound message | `{ id, messageId, status, ack, chatId? }` — `status` is the canonical state (`pending`/`sent`/`delivered`/`read`/`failed`); `ack` is the deprecated legacy integer derived from it; `chatId` is the conversation the acked message belongs to, present whenever the engine's update names the chat (both engines do on the live path) |+| `message.failed` | A receipt resolves to `failed` (dispatched in addition to `message.ack`) | `{ id, messageId, status: "failed", ack: -1, chatId? }`; `chatId` follows the same rules as `message.ack` || `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, 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) |diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex dc15b0175..a3fb5fbbf 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -769,11 +769,16 @@ export class BaileysEvents {return (isDelete && inGroup) || overlap(author(target), author(envelope));}- handleMessagesUpdate(updates: Array<{ key?: { id?: string | null }; update?: { status?: number | null } }>): void {+ handleMessagesUpdate(+ updates: Array<{ key?: { id?: string | null; remoteJid?: string | null }; update?: { status?: number | null } }>,+ ): void {for (const u of updates) {const status = mapBaileysStatus(u.update?.status);if (status && u.key?.id) {- this.host.getOnMessageAck()?.(u.key.id, status);+ // Canonicalize the update's chat exactly as the inbound mapper does, so an ack's chatId+ // matches the chatId of the message events it accompanies.+ const chatId = u.key.remoteJid ? this.host.toNeutralJid(u.key.remoteJid) : undefined;+ this.host.getOnMessageAck()?.(u.key.id, status, chatId);}}}diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 16a2fda89..03977b605 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -2761,7 +2761,19 @@ describe('BaileysAdapter inbound fan-out', () => {const adapter = newAdapter();await adapter.initialize({ onMessageAck });fakeSock.fire('messages.update', [{ key: { id: 'OUT1' }, update: { status: 3 } }]);- expect(onMessageAck).toHaveBeenCalledWith('OUT1', 'delivered');+ expect(onMessageAck).toHaveBeenCalledWith('OUT1', 'delivered', undefined);+ });++ it('carries the update key chat on onMessageAck, canonicalized', async () => {+ const onMessageAck = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessageAck });+ fakeSock.fire('messages.update', [+ { key: { id: 'OUT2', remoteJid: '[email protected]' }, update: { status: 2 } },+ { key: { id: 'OUT3', remoteJid: '[email protected]' }, update: { status: 3 } },+ ]);+ expect(onMessageAck).toHaveBeenCalledWith('OUT2', 'sent', '[email protected]');+ expect(onMessageAck).toHaveBeenCalledWith('OUT3', 'delivered', '[email protected]');});it('inbound image: downloads media and exposes base64 + caption as body', async () => {diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex a197b5050..4b193df65 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -5747,7 +5747,23 @@ describe('WhatsAppWebJsAdapter message_ack (unreadable id)', () => {client.emit('message_ack', { id: { _serialized: 'ACKED_MSG' } }, 3);- expect(onMessageAck).toHaveBeenCalledWith('ACKED_MSG', expect.any(String));+ expect(onMessageAck).toHaveBeenCalledWith('ACKED_MSG', expect.any(String), undefined);+ });++ it('derives the acked message chat as Message._getChatId does', () => {+ // Acks ride outbound messages, so the chat is the recipient; the direction flag keeps an+ // inbound-shaped payload on its sender, the same derivation the revoked handler uses.+ const { onMessageAck, client } = wireAckHandler();++ client.emit(+ 'message_ack',+ { id: { _serialized: 'ACKED_OUT' }, fromMe: true, from: '[email protected]', to: '[email protected]' },+ 3,+ );+ client.emit('message_ack', { id: { _serialized: 'ACKED_IN' }, fromMe: false, from: '[email protected]', to: '[email protected]' }, 2);++ expect(onMessageAck).toHaveBeenCalledWith('ACKED_OUT', expect.any(String), '[email protected]');+ expect(onMessageAck).toHaveBeenCalledWith('ACKED_IN', expect.any(String), '[email protected]');});it('reads a renamed `$1` id when the dependency has not normalized it', () => {@@ -5757,7 +5773,7 @@ describe('WhatsAppWebJsAdapter message_ack (unreadable id)', () => {client.emit('message_ack', { id: { $1: 'ACKED_RENAMED' } }, 3);- expect(onMessageAck).toHaveBeenCalledWith('ACKED_RENAMED', expect.any(String));+ expect(onMessageAck).toHaveBeenCalledWith('ACKED_RENAMED', expect.any(String), undefined);});it('drops an ack whose id cannot be read instead of passing undefined on', () => {diff --git a/src/engine/adapters/wwebjs-message-events.ts b/src/engine/adapters/wwebjs-message-events.tsindex 3c7ee8c13..8e58dd2bb 100644--- a/src/engine/adapters/wwebjs-message-events.ts+++ b/src/engine/adapters/wwebjs-message-events.ts@@ -137,8 +137,11 @@ export function registerWwebjsMessageEvents(client: Client, host: WwebjsEngineHoreturn;}// Map the whatsapp-web.js MessageAck integer to the neutral DeliveryStatus here, at the- // adapter boundary, so no downstream consumer ever sees engine-specific ack codes.- host.getCallbacks().onMessageAck?.(ackId, wwebjsAckToDeliveryStatus(ack));+ // adapter boundary, so no downstream consumer ever sees engine-specific ack codes. The chat is+ // derived as Message._getChatId derives it (the same direction flag the revoked handler uses),+ // so the ack's chatId matches the chatId of the message it belongs to.+ const ackChatId = msg.fromMe ? msg.to : msg.from;+ host.getCallbacks().onMessageAck?.(ackId, wwebjsAckToDeliveryStatus(ack), ackChatId || undefined);});client.on('message_revoke_everyone', (after, before) => {diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex c0d31e92b..c24efd5f1 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -808,8 +808,11 @@ export interface EngineEventCallbacks {/*** Fired when the delivery status of an outgoing message advances. The adapter maps its native* delivery signal to the neutral `DeliveryStatus`, so consumers never see engine-specific codes.+ * `chatId` is the conversation the acked message belongs to, canonicalized the same way the+ * inbound mappers canonicalize `IncomingMessage.chatId`; undefined when the engine's update+ * carries no chat, and the emitted payload then omits the field rather than guess.*/- onMessageAck?: (messageId: string, status: DeliveryStatus) => void;+ onMessageAck?: (messageId: string, status: DeliveryStatus, chatId?: string) => void;onMessageRevoked?: (message: RevokedMessage) => void;onMessageReaction?: (event: ReactionEvent) => void;onMessageEdited?: (message: EditedMessage) => void;diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex 49c52cbfb..0a62c148b 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -863,10 +863,14 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate/*** Emit a live delivery-status update. The payload mirrors the `message.ack` webhook exactly- * (`id`, `messageId`, neutral `status`, and the deprecated legacy numeric `ack`) so a socket- * client and a webhook consumer see the same shape.+ * (`id`, `messageId`, neutral `status`, the deprecated legacy numeric `ack`, and `chatId` when+ * the engine's update named the chat) so a socket client and a webhook consumer see the same+ * shape.*/- emitMessageAck(sessionId: string, data: { id: string; messageId: string; status: DeliveryStatus; ack: number }) {+ emitMessageAck(+ sessionId: string,+ data: { id: string; messageId: string; status: DeliveryStatus; ack: number; chatId?: string },+ ) {this.emitToRooms(sessionId, 'message.ack', data);}diff --git a/src/modules/session/message-projector.service.spec.ts b/src/modules/session/message-projector.service.spec.tsindex 195be52cd..833acfe18 100644--- a/src/modules/session/message-projector.service.spec.ts+++ b/src/modules/session/message-projector.service.spec.ts@@ -1325,4 +1325,37 @@ describe('MessageProjector (inbound projection)', () => {expect(eventsGateway.emitMessageSent).toHaveBeenCalledWith(SESSION_ID, sent);});});++ describe('handleMessageAck payload', () => {+ it('carries the chat the engine named, on the socket and on both webhook events', () => {+ const engine = makeEngine();+ engines.set(SESSION_ID, engine);++ projector.handleMessageAck(SESSION_ID, engine, 'M1', 'delivered', '[email protected]');+ projector.handleMessageAck(SESSION_ID, engine, 'M2', 'failed', '[email protected]');++ const expected = { id: 'M1', messageId: 'M1', status: 'delivered', ack: 2, chatId: '[email protected]' };+ expect(eventsGateway.emitMessageAck).toHaveBeenCalledWith(SESSION_ID, expected);+ expect(webhookService.dispatch).toHaveBeenCalledWith(SESSION_ID, 'message.ack', expected);+ expect(webhookService.dispatch).toHaveBeenCalledWith(SESSION_ID, 'message.failed', {+ id: 'M2',+ messageId: 'M2',+ status: 'failed',+ ack: -1,+ chatId: '[email protected]',+ });+ });++ it('omits chatId when the engine update carried no chat', () => {+ const engine = makeEngine();+ engines.set(SESSION_ID, engine);++ projector.handleMessageAck(SESSION_ID, engine, 'M1', 'delivered');++ // Exact equality: the payload has no chatId key at all, not an undefined one.+ const bare = { id: 'M1', messageId: 'M1', status: 'delivered', ack: 2 };+ expect(eventsGateway.emitMessageAck).toHaveBeenCalledWith(SESSION_ID, bare);+ expect(webhookService.dispatch).toHaveBeenCalledWith(SESSION_ID, 'message.ack', bare);+ });+ });});diff --git a/src/modules/session/message-projector.service.ts b/src/modules/session/message-projector.service.tsindex 94fbb99a3..e4fec9a38 100644--- a/src/modules/session/message-projector.service.ts+++ b/src/modules/session/message-projector.service.ts@@ -766,7 +766,13 @@ export class MessageProjector {}/** Engine callback body, lifted out of initializeEngine so the wiring table stays readable. */- handleMessageAck(id: string, engine: IWhatsAppEngine, messageId: string, status: DeliveryStatus): void {+ handleMessageAck(+ id: string,+ engine: IWhatsAppEngine,+ messageId: string,+ status: DeliveryStatus,+ chatId?: string,+ ): void {if (!this.engines.isLive(id, engine)) return;this.logger.debug(`Message ack: ${messageId} -> ${status}`, {sessionId: id,@@ -822,8 +828,16 @@ export class MessageProjector {// One ack payload, emitted identically over the socket and the webhook so a client coded// against either channel sees the same shape. `id` mirrors the field every other message.*// event carries (and the idempotency-key resolver reads). `ack` is a deprecated legacy field- // kept for backward compatibility — new consumers should read the neutral `status`.- const ackPayload = { id: messageId, messageId, status, ack: deliveryStatusToAck(status) };+ // kept for backward compatibility — new consumers should read the neutral `status`. `chatId`+ // rides along when the engine's update names the chat, so a webhook `chatId` condition scopes+ // ack and failure events to that chat instead of suppressing them outright.+ const ackPayload = {+ id: messageId,+ messageId,+ status,+ ack: deliveryStatusToAck(status),+ ...(chatId ? { chatId } : {}),+ };// Push the live delivery/read tick to the dashboard over the websocket.this.eventsGateway.emitMessageAck(id, ackPayload);diff --git a/src/modules/session/session-engine-event-wiring.ts b/src/modules/session/session-engine-event-wiring.tsindex 0788ac580..b1bf8c95c 100644--- a/src/modules/session/session-engine-event-wiring.ts+++ b/src/modules/session/session-engine-event-wiring.ts@@ -242,7 +242,8 @@ export class SessionEngineEventWiring {.catch(err => this.logger.error(`Failed to persist history messages for ${id}`, String(err)));},onMessageCreate: (message): void => host.messages.handleOwnSendEcho(id, engine, message),- onMessageAck: (messageId, status): void => host.messages.handleMessageAck(id, engine, messageId, status),+ onMessageAck: (messageId, status, chatId): void =>+ host.messages.handleMessageAck(id, engine, messageId, status, chatId),onMessageRevoked: (message): void => host.messages.handleMessageRevoked(id, engine, message),onMessageReaction: (event): void => {if (!host.isLiveEngine(id, engine)) return;diff --git a/src/modules/webhook/filters/filter-evaluator.spec.ts b/src/modules/webhook/filters/filter-evaluator.spec.tsindex 4c33bc614..93ca0e26f 100644--- a/src/modules/webhook/filters/filter-evaluator.spec.ts+++ b/src/modules/webhook/filters/filter-evaluator.spec.ts@@ -243,27 +243,34 @@ describe('evaluateFilters', () => {expect(evaluateFilters(deny, 'message.received', msg({ chatId: '[email protected]' }))).toBe(true);});- // The ack and failure events carry no conversation at all: their payload is the shape the- // projector builds, `{ id, messageId, status, ack }`. A chatId condition therefore SUPPRESSES- // them rather than scoping them, which is a real surprise for anyone allowlisting a group, so- // it is pinned here and warned about in docs/06 rather than left to be discovered.- it('suppresses message.ack and message.failed, whose payload carries no conversation', () => {+ // The ack and failure events carry the conversation whenever the engine's update names the+ // chat (both engines do on the live path), so a chatId condition SCOPES them like any other+ // message event. When the chat is unknown the generic absent-field rule decides instead: `is`+ // suppresses and `isNot` passes. Both directions are pinned here and stated in docs/06.+ it('scopes message.ack and message.failed to the chat their payload carries', () => {// Real pairings: deliveryStatusToAck maps delivered to 2 and failed to -1, and message.failed// is a copy of the same object, so the fixture must not invent a status/ack pair of its own.- const ackPayload = { id: 'M1', messageId: 'M1', status: 'delivered', ack: 2 };- const failedPayload = { id: 'M1', messageId: 'M1', status: 'failed', ack: -1 };+ const ackPayload = { id: 'M1', messageId: 'M1', status: 'delivered', ack: 2, chatId: '[email protected]' };+ const failedPayload = { id: 'M1', messageId: 'M1', status: 'failed', ack: -1, chatId: '[email protected]' };const allow = filters({ field: 'chatId', operator: 'is', value: ['[email protected]'] });- expect(evaluateFilters(allow, 'message.ack', ackPayload)).toBe(false);- expect(evaluateFilters(allow, 'message.failed', failedPayload)).toBe(false);+ expect(evaluateFilters(allow, 'message.ack', ackPayload)).toBe(true);+ expect(evaluateFilters(allow, 'message.failed', failedPayload)).toBe(true);- // And the exclusion direction delivers them, for the same reason: the field is not there.+ // The exclusion direction now keeps that chat's acks and failures out.const deny = filters({ field: 'chatId', operator: 'isNot', value: ['[email protected]'] });- expect(evaluateFilters(deny, 'message.ack', ackPayload)).toBe(true);- expect(evaluateFilters(deny, 'message.failed', failedPayload)).toBe(true);- // An absent boolean reads as false, so `is false` passes both as well.+ expect(evaluateFilters(deny, 'message.ack', ackPayload)).toBe(false);+ expect(evaluateFilters(deny, 'message.failed', failedPayload)).toBe(false);+ });++ it('still applies the absent-field rule to an ack whose chat is unknown', () => {+ const noChat = { id: 'M1', messageId: 'M1', status: 'delivered', ack: 2 };+ const allow = filters({ field: 'chatId', operator: 'is', value: ['[email protected]'] });+ const deny = filters({ field: 'chatId', operator: 'isNot', value: ['[email protected]'] });+ expect(evaluateFilters(allow, 'message.ack', noChat)).toBe(false);+ expect(evaluateFilters(deny, 'message.ack', noChat)).toBe(true);+ // An absent boolean reads as false, so `is false` passes it as well.const notGroup = filters({ field: 'isGroup', operator: 'is', value: false });- expect(evaluateFilters(notGroup, 'message.ack', ackPayload)).toBe(true);- expect(evaluateFilters(notGroup, 'message.failed', failedPayload)).toBe(true);+ expect(evaluateFilters(notGroup, 'message.ack', noChat)).toBe(true);});it('scopes message.revoked / edited payloads that only carry chatId', () => {diff --git a/src/modules/webhook/filters/filter-types.ts b/src/modules/webhook/filters/filter-types.tsindex 09d5c1346..96e2b1f78 100644--- a/src/modules/webhook/filters/filter-types.ts+++ b/src/modules/webhook/filters/filter-types.ts@@ -102,10 +102,11 @@ export const FILTER_FIELDS: Record<string, FieldDefinition[]> = {{// Conversation JID (DM or group). Carried by the message events proper: `IncomingMessage`// declares `chatId` required, and the edited, reaction and revoked events set it explicitly.- // NOT by `message.ack` and `message.failed`, whose payload is `{ id, messageId, status, ack }`,- // so a chatId condition never scopes those two: an `is` condition suppresses every one of them- // and an `isNot` condition lets every one through. Scope the subscription with `events[]`- // instead (docs/06 carries the same warning for `sender`).+ // `message.ack` and `message.failed` carry it too when the engine's update names the chat+ // (both engines do on the live path), so a chatId condition scopes those two to that chat.+ // A payload whose chat is unknown falls under the generic absent-field rule: an `is`+ // condition suppresses it and an `isNot` condition passes it (docs/06 states the rule for+ // `sender` the same way).// Deliberately without a fall back to `from`, which is the sender on a DM and this session on// an outbound message, so it would silently scope the filter to the wrong conversation.field: 'chatId',