Skip to content

The agent that grows with you

feat(whatsapp): log delivery and read status of sent messages to gateway.log

Victor Kyriazakos31d5f1d44d35
diff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.py
index 86ec7b8e78e..fe890b0879e 100644
--- a/plugins/platforms/whatsapp/adapter.py
+++ b/plugins/platforms/whatsapp/adapter.py
@@ -1019,6 +1019,9 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
async with self._bridge_req("get", "messages", 30) as resp:
if resp.status == 200:
for msg_data in await resp.json():
+ if msg_data.get("event") == "delivery_status":
+ self._log_delivery_status(msg_data)
+ continue
event = await self._build_message_event(msg_data)
if event:
# Fire-and-forget: a slow bridge /read must not delay dispatch.
@@ -1036,6 +1039,16 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
await asyncio.sleep(5)
await asyncio.sleep(1) # Poll interval
+ def _log_delivery_status(self, data: dict[str, Any]) -> None:
+ """One gateway.log line per delivery/read status change of a message Hermes sent (Baileys
+ ``messages.update`` for DMs, ``message-receipt.update`` per recipient in groups)."""
+ logger.info(
+ "[%s] WhatsApp delivery status: message=%s chat=%s status=%s%s at=%s%s", self.name,
+ data.get("messageId"), data.get("chatId"), data.get("status"),
+ f" recipient={data['recipientId']}" if data.get("recipientId") else "", data.get("timestamp"),
+ f" error={data['error']}" if data.get("error") else "",
+ )
+
async def _send_read_receipt(self, data: dict[str, Any]) -> None:
key = data.get("readReceiptKey")
if not self._send_read_receipts or not self._http_session or not isinstance(key, dict):
diff --git a/scripts/whatsapp-bridge/bridge.js b/scripts/whatsapp-bridge/bridge.js
index 8ae3bceaee8..a5dbac3cae5 100644
--- a/scripts/whatsapp-bridge/bridge.js
+++ b/scripts/whatsapp-bridge/bridge.js
@@ -43,6 +43,7 @@ import {
buildTextSendPayload,
createBoundedMessageStore,
createQuotedMediaCache,
+ deliveryStatusEvent,
extractBridgeEvent,
getMessageContent,
inboundReadReceiptKeys,
@@ -375,6 +376,15 @@ function rememberSentId(id) {
recentlySentIds.remember(id);
}
+function enqueueDeliveryStatus(args) {
+ const event = deliveryStatusEvent({ ...args, isOwnSend: id => recentlySentIds.has(id) });
+ if (!event) return;
+ messageQueue.push(event);
+ if (messageQueue.length > MAX_QUEUE_SIZE) {
+ messageQueue.shift();
+ }
+}
+
let sock = null;
let connectionState = 'disconnected';
@@ -469,8 +479,13 @@ async function startSocket() {
}
});
+ sock.ev.on('message-receipt.update', (receipts) => {
+ for (const { key, receipt } of receipts || []) enqueueDeliveryStatus({ key, receipt });
+ });
+
sock.ev.on('messages.update', async (updates) => {
for (const { key, update } of updates || []) {
+ if (update?.status !== undefined) enqueueDeliveryStatus({ key, update });
if (!update?.pollUpdates) continue;
const pollCreationId = key?.id || update.pollUpdates?.[0]?.pollCreationMessageKey?.id;
const pollCreation = messageStore.get(pollCreationId);
diff --git a/scripts/whatsapp-bridge/bridge_helpers.js b/scripts/whatsapp-bridge/bridge_helpers.js
index d8f78cb8b3d..6cd2db63387 100644
--- a/scripts/whatsapp-bridge/bridge_helpers.js
+++ b/scripts/whatsapp-bridge/bridge_helpers.js
@@ -608,6 +608,47 @@ export function inboundReadReceiptKeys({ key, enabled }) {
return [key];
}
+// proto.WebMessageInfo.Status values (Baileys). PENDING is our own local state, never a receipt.
+const DELIVERY_STATUS_NAMES = { 0: 'error', 2: 'server_ack', 3: 'delivered', 4: 'read', 5: 'played' };
+const RECEIPT_TIMESTAMP_STATUS = [
+ ['playedTimestamp', 'played'], ['readTimestamp', 'read'], ['receiptTimestamp', 'delivered'],
+];
+
+/**
+ * Delivery/read status of a message Hermes sent, as a queue event for the adapter to log.
+ * `messages.update` carries `update.status` for 1:1 chats; `message-receipt.update` carries a
+ * per-recipient `receipt` for groups. Returns null for anything that is not a status change of
+ * one of our own sends (`isOwnSend(id)`), so human messages on the linked phone are never logged.
+ */
+export function deliveryStatusEvent({ key, update, receipt, isOwnSend }) {
+ if (!key?.fromMe || !key.id || !isOwnSend(key.id)) return null;
+ let status;
+ let at;
+ let recipientId = '';
+ if (receipt) {
+ const hit = RECEIPT_TIMESTAMP_STATUS.find(([field]) => receipt[field]);
+ if (!hit) return null;
+ [, status] = hit;
+ at = Number(receipt[hit[0]]) || 0;
+ recipientId = normalizeWhatsAppId(receipt.userJid || '');
+ } else {
+ status = DELIVERY_STATUS_NAMES[update?.status];
+ if (!status) return null;
+ at = Number(update.messageTimestamp) || 0;
+ }
+ const event = {
+ event: 'delivery_status',
+ messageId: key.id,
+ chatId: normalizeWhatsAppId(key.remoteJid || ''),
+ status,
+ timestamp: at || Math.floor(Date.now() / 1000),
+ };
+ if (recipientId) event.recipientId = recipientId;
+ const error = status === 'error' ? update?.messageStubParameters?.[0] : undefined;
+ if (error) event.error = String(error);
+ return event;
+}
+
export function mediaPayloadForFile({ buffer, filePath, mediaType, caption, fileName }) {
const ext = filePath.toLowerCase().split('.').pop();
const type = mediaType || inferMediaType(ext);
diff --git a/scripts/whatsapp-bridge/delivery_status.test.mjs b/scripts/whatsapp-bridge/delivery_status.test.mjs
new file mode 100644
index 00000000000..e61f73db1ed
--- /dev/null
+++ b/scripts/whatsapp-bridge/delivery_status.test.mjs
@@ -0,0 +1,62 @@
+/**
+ * Delivery/read status events for messages Hermes sent (logged to gateway.log by the adapter).
+ */
+
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { proto } from '@whiskeysockets/baileys';
+
+import { deliveryStatusEvent } from './bridge_helpers.js';
+
+const Status = proto.WebMessageInfo.Status;
+const own = new Set(['sent-1']);
+const isOwnSend = id => own.has(id);
+const dmKey = { id: 'sent-1', remoteJid: '[email protected]', fromMe: true };
+
+test('each 1:1 status change of our own send becomes one event', () => {
+ const names = [];
+ for (const status of [Status.SERVER_ACK, Status.DELIVERY_ACK, Status.READ, Status.PLAYED]) {
+ const event = deliveryStatusEvent({ key: dmKey, update: { status, messageTimestamp: 1760000000 }, isOwnSend });
+ assert.equal(event.event, 'delivery_status');
+ assert.equal(event.messageId, 'sent-1');
+ assert.equal(event.chatId, '[email protected]');
+ assert.equal(event.timestamp, 1760000000);
+ names.push(event.status);
+ }
+ assert.deepEqual(names, ['server_ack', 'delivered', 'read', 'played']);
+});
+
+test('a failed send carries the error code', () => {
+ const event = deliveryStatusEvent({
+ key: dmKey, update: { status: Status.ERROR, messageStubParameters: ['463'] }, isOwnSend,
+ });
+ assert.equal(event.status, 'error');
+ assert.equal(event.error, '463');
+});
+
+test('group receipts name the recipient and the furthest state', () => {
+ const key = { id: 'sent-1', remoteJid: '[email protected]', fromMe: true };
+ const read = deliveryStatusEvent({
+ key, receipt: { userJid: '[email protected]', readTimestamp: 1760000100 }, isOwnSend,
+ });
+ assert.deepEqual(
+ { status: read.status, recipientId: read.recipientId, timestamp: read.timestamp },
+ { status: 'read', recipientId: '[email protected]', timestamp: 1760000100 },
+ );
+ const delivered = deliveryStatusEvent({
+ key, receipt: { userJid: '[email protected]', receiptTimestamp: 1760000050 }, isOwnSend,
+ });
+ assert.equal(delivered.status, 'delivered');
+});
+
+test('nothing is reported for messages Hermes did not send', () => {
+ const update = { status: Status.READ };
+ // Typed by a human on the linked phone: fromMe but not one of our sends.
+ assert.equal(deliveryStatusEvent({ key: { ...dmKey, id: 'human-typed' }, update, isOwnSend }), null);
+ // Inbound message (another device of ours read it).
+ assert.equal(deliveryStatusEvent({ key: { ...dmKey, fromMe: false }, update, isOwnSend }), null);
+ // Poll vote / edit / stub updates carry no status.
+ assert.equal(deliveryStatusEvent({ key: dmKey, update: { pollUpdates: [] }, isOwnSend }), null);
+ assert.equal(deliveryStatusEvent({ key: dmKey, update: { status: Status.PENDING }, isOwnSend }), null);
+ assert.equal(deliveryStatusEvent({ key: dmKey, receipt: { userJid: '[email protected]' }, isOwnSend }), null);
+});
diff --git a/tests/gateway/test_whatsapp_delivery_status_log.py b/tests/gateway/test_whatsapp_delivery_status_log.py
new file mode 100644
index 00000000000..45e18344774
--- /dev/null
+++ b/tests/gateway/test_whatsapp_delivery_status_log.py
@@ -0,0 +1,73 @@
+"""Delivery/read status of messages Hermes sends on WhatsApp is logged to gateway.log, one line per change.
+
+Coatue request: Baileys already reports `messages.update` status (and per-recipient group receipts),
+but the bridge only forwarded poll updates, so operators could not see whether a reply was delivered
+or read. The bridge now queues a `delivery_status` event; the adapter logs it and never treats it as
+an inbound message.
+"""
+
+import asyncio
+import logging
+from unittest.mock import AsyncMock
+
+import pytest
+
+from gateway.config import PlatformConfig
+
+
+class _Resp:
+ def __init__(self, payload):
+ self.status, self._payload = 200, payload
+
+ async def json(self):
+ return self._payload
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *exc):
+ return False
+
+
+async def test_delivery_status_is_logged_to_gateway_log_and_never_dispatched(caplog):
+ from hermes_logging import COMPONENT_PREFIXES
+ from plugins.platforms.whatsapp.adapter import WhatsAppAdapter
+
+ adapter = WhatsAppAdapter(PlatformConfig(enabled=True, extra={}))
+ batch = [
+ {"event": "delivery_status", "messageId": "3EB0A1", "chatId": "[email protected]",
+ "status": "read", "timestamp": 1760000000},
+ {"event": "delivery_status", "messageId": "3EB0A2", "chatId": "[email protected]",
+ "status": "delivered", "recipientId": "[email protected]", "timestamp": 1760000050},
+ {"event": "delivery_status", "messageId": "3EB0A3", "chatId": "[email protected]",
+ "status": "error", "error": "463", "timestamp": 1760000060},
+ ]
+
+ def _bridge_req(method, path, timeout, **kwargs):
+ assert (method, path) == ("get", "messages")
+ adapter._running = False # one poll, then the loop exits after its 1s interval
+ return _Resp(batch)
+
+ adapter._http_session = object()
+ adapter._bridge_req = _bridge_req
+ adapter._running = True
+ adapter._check_managed_bridge_exit = AsyncMock(return_value=None)
+ adapter._build_message_event = AsyncMock(return_value=None)
+ adapter.handle_message = AsyncMock()
+
+ with caplog.at_level(logging.INFO, logger="plugins.platforms.whatsapp.adapter"):
+ await asyncio.wait_for(adapter._poll_messages(), timeout=10)
+
+ tag = f"[{adapter.name}] WhatsApp delivery status:"
+ lines = [r.getMessage() for r in caplog.records if r.name == "plugins.platforms.whatsapp.adapter"
+ and "delivery status" in r.getMessage()]
+ assert lines == [
+ f"{tag} message=3EB0A1 [email protected] status=read at=1760000000",
+ f"{tag} message=3EB0A2 [email protected] status=delivered [email protected] at=1760000050",
+ f"{tag} message=3EB0A3 [email protected] status=error at=1760000060 error=463",
+ ]
+ # gateway.log takes every plugins.platforms.* logger (hermes_logging component prefixes).
+ assert any("plugins.platforms.whatsapp.adapter".startswith(p) for p in COMPONENT_PREFIXES["gateway"])
+ adapter._build_message_event.assert_not_awaited()
+ adapter.handle_message.assert_not_awaited()
diff --git a/website/docs/user-guide/messaging/whatsapp.md b/website/docs/user-guide/messaging/whatsapp.md
index 23b33ff06e3..fd69d7af519 100644
--- a/website/docs/user-guide/messaging/whatsapp.md
+++ b/website/docs/user-guide/messaging/whatsapp.md
@@ -248,6 +248,12 @@ whatsapp:
When `send_read_receipts` is `true`, the adapter marks policy-accepted inbound messages as read after DM/group/mention filtering passes. Rejected messages (e.g., from non-allowlisted senders) are not marked read. Disabled by default for privacy. Changing this setting automatically restarts the bridge subprocess on the next connection.
+Delivery and read status of the messages Hermes sends is logged to `gateway.log`, one line per status change (`server_ack`, `delivered`, `read`, `played`, or `error` with WhatsApp's error code). In groups, each recipient's receipt is its own line with `recipient=`. Messages typed by a person on the linked phone are not logged.
+
+```
+[WhatsApp] WhatsApp delivery status: message=3EB0A1 [email protected] status=read at=1760000000
+```
+
---
## Message Formatting & Delivery