Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): send a read receipt for the newest received message

Yudhi Armyndharis909d89a05a1c
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 901f5cfae..1066a54f6 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -931,7 +931,7 @@ Mark a chat as read/seen.
| `chatId` | string | Yes | `@IsString`; `@IsNotEmpty`; `@Matches(/^[^\s@]+@[^\s@]+$/)` (localpart@host, no whitespace) | Engine-native JID, e.g. `[email protected]` (wwebjs) or `[email protected]` (Baileys) |
| `messageIds` | string[] | No | `@IsArray`; `@ArrayNotEmpty`; `@ArrayMaxSize(100)`; each a non-empty token with no whitespace | Messages to acknowledge. Omit the field to acknowledge only the newest message; an empty array is rejected. |
-Baileys acknowledges individual messages rather than chats, and the receipt enumerates ids instead of carrying a read-up-to watermark. Without `messageIds` only the newest message the engine still holds in memory gets a receipt, so a burst leaves its earlier messages unread and a session restarted since the message arrived has nothing to acknowledge at all. Each supplied id is resolved through the message store, which is what carries the `participant` a group receipt needs. Ignored by whatsapp-web.js, whose own `sendSeen` is chat-level.
+Baileys acknowledges individual messages rather than chats, and the receipt enumerates ids instead of carrying a read-up-to watermark. Without `messageIds` only the newest received message the engine still holds in memory gets a receipt, so a burst leaves its earlier messages unread and a session restarted since the message arrived has nothing to acknowledge at all. Each supplied id is resolved through the message store, which is what carries the `participant` a group receipt needs. Ignored by whatsapp-web.js, whose own `sendSeen` is chat-level.
```json
{ "chatId": "[email protected]", "messageIds": ["3EB0C767D26B8A3F1A2B", "3EB0C767D26B8A3F1A2C"] }
@@ -946,9 +946,10 @@ Baileys acknowledges individual messages rather than chats, and the receipt enum
Returns HTTP `200`, matching the OpenAPI contract.
> **`success: false` is a real outcome on the Baileys engine.** The read receipt is sent against the
-> chat's last known message, so a chat the session has seen no message in is reported as declined
-> rather than marked read. The whatsapp-web.js engine reads the chat from the page and needs no local
-> history, so it never produces this outcome.
+> newest message the chat received, so a chat the session has received no message in (one holding
+> only the account's own sends included) is reported as declined rather than marked read. The
+> whatsapp-web.js engine reads the chat from the page and needs no local history, so it never
+> produces this outcome.
**Errors:** `400` validation, or session not started · `401` · `403` · `404` session not found · `409` the session is not connected (engine exists but is not `ready`) · `503` WhatsApp did not answer within the request budget, or the engine’s browser page died — the change may or may not have been applied
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index 8c4204132..3513c34bb 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -237,8 +237,8 @@ curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/chats/read
-d '{ "chatId": "[email protected]", "messageIds": ["3EB0C767D26B8A3F1A2B"] }'
```
-`messageIds` is optional and holds up to 100 ids. Omit it and only the newest message the engine still
-holds in memory is acknowledged, which on Baileys leaves the earlier messages of a burst unread.
+`messageIds` is optional and holds up to 100 ids. Omit it and only the newest received message the engine
+still holds in memory is acknowledged, which on Baileys leaves the earlier messages of a burst unread.
#### POST /api/sessions/:sessionId/chats/unread
diff --git a/openapi.json b/openapi.json
index 68b1eab9e..999ff5c3f 100644
--- a/openapi.json
+++ b/openapi.json
@@ -1130,7 +1130,7 @@
},
"responses": {
"200": {
- "description": "Returns `{ success }`. `false` means the engine declined to act: the Baileys engine sends the read receipt against the chat's last known message, so a chat it has seen no message in is reported as declined rather than marked read. The whatsapp-web.js engine reads the chat from the page and needs no local history.",
+ "description": "Returns `{ success }`. `false` means the engine declined to act: the Baileys engine sends the read receipt against the newest message the chat received, so a chat it has received no message in (one holding only the account's own sends included) is reported as declined rather than marked read. The whatsapp-web.js engine reads the chat from the page and needs no local history.",
"content": {
"application/json": {
"schema": {
@@ -10743,7 +10743,7 @@
"example": "[email protected]"
},
"messageIds": {
- "description": "Specific message IDs to mark read. Baileys acknowledges individual messages, so without this only the newest message the engine still holds in memory gets a receipt — a burst leaves its earlier messages unread forever, and a restarted session has no message to acknowledge at all. Callers that persist inbound message IDs should send them here. Ignored by whatsapp-web.js, whose own sendSeen is chat-level.",
+ "description": "Specific message IDs to mark read. Baileys acknowledges individual messages, so without this only the newest received message the engine still holds in memory gets a receipt — a burst leaves its earlier messages unread forever, and a restarted session has no message to acknowledge at all. Callers that persist inbound message IDs should send them here. Ignored by whatsapp-web.js, whose own sendSeen is chat-level.",
"maxItems": 100,
"minItems": 1,
"example": [
diff --git a/sdk/go/types_chat.go b/sdk/go/types_chat.go
index 4a7f6bfc5..9ede2bdad 100644
--- a/sdk/go/types_chat.go
+++ b/sdk/go/types_chat.go
@@ -40,8 +40,9 @@ type SubscribePresenceRequest struct {
type MarkChatReadRequest struct {
ChatID string `json:"chatId"`
// MessageIDs are the messages to acknowledge (at most 100; an empty list is refused). Baileys
- // acknowledges individual messages, so without this only the newest message the engine still
- // holds in memory gets a receipt. Ignored by whatsapp-web.js, whose own sendSeen is chat-level.
+ // acknowledges individual messages, so without this only the newest received message the
+ // engine still holds in memory gets a receipt. Ignored by whatsapp-web.js, whose own sendSeen
+ // is chat-level.
//
// A POINTER because the three states differ on the wire and a plain slice cannot tell two of
// them apart: nil omits the key (acknowledge the newest), &[]string{} sends [] (the server
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/MarkChatReadRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/MarkChatReadRequest.java
index d46dc497f..f6a9ff890 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/MarkChatReadRequest.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/MarkChatReadRequest.java
@@ -20,8 +20,9 @@ public record MarkChatReadRequest(String chatId, List<String> messageIds) {
/**
* Messages to acknowledge (at most 100; an empty list is refused). Baileys acknowledges
- * individual messages, so without this only the newest message the engine still holds in
- * memory gets a receipt. Ignored by whatsapp-web.js, whose own sendSeen is chat-level.
+ * individual messages, so without this only the newest received message the engine still
+ * holds in memory gets a receipt. Ignored by whatsapp-web.js, whose own sendSeen is
+ * chat-level.
*/
public Builder messageIds(List<String> v) {
this.messageIds = v;
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index 8a0e8e263..75be2545b 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -1059,8 +1059,9 @@ export interface SubscribePresenceRequest {
export interface MarkChatReadRequest extends MarkChatRequest {
/**
* Specific message IDs to acknowledge. Baileys acknowledges individual messages, so without this
- * only the newest message the engine still holds in memory gets a receipt: a burst leaves its
- * earlier messages unread forever, and a restarted session has no message to acknowledge at all.
+ * only the newest received message the engine still holds in memory gets a receipt: a burst
+ * leaves its earlier messages unread forever, and a restarted session has no message to
+ * acknowledge at all.
* Callers that persist inbound message IDs should send them here. Ignored by whatsapp-web.js,
* whose own sendSeen is chat-level. At most 100 per request; an empty array is rejected.
*/
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index ed25bd9c6..f06d01e3a 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -987,8 +987,9 @@ class MarkChatReadRequest(TypedDict):
# Body for mark_read.
chatId: Jid
# Messages to acknowledge (at most 100; an empty list is refused). Baileys acknowledges
- # individual messages, so without this only the newest message the engine still holds in
- # memory gets a receipt. Ignored by whatsapp-web.js, whose own sendSeen is chat-level.
+ # individual messages, so without this only the newest received message the engine still
+ # holds in memory gets a receipt. Ignored by whatsapp-web.js, whose own sendSeen is
+ # chat-level.
messageIds: NotRequired[list[str]]
diff --git a/src/core/agent-tools/tools/session.tools.ts b/src/core/agent-tools/tools/session.tools.ts
index 2868a71ce..d3a9bf4f8 100644
--- a/src/core/agent-tools/tools/session.tools.ts
+++ b/src/core/agent-tools/tools/session.tools.ts
@@ -104,7 +104,7 @@ export function sessionTools(session: SessionService): AnyToolDescriptor[] {
.optional()
.describe(
'Specific message IDs to acknowledge. Baileys acknowledges individual messages, so without ' +
- 'this only the newest message still held in memory gets a receipt.',
+ 'this only the newest received message still held in memory gets a receipt.',
),
}),
handler: input =>
diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.ts
index e716c7003..eca824f33 100644
--- a/src/engine/adapters/baileys-contacts.ts
+++ b/src/engine/adapters/baileys-contacts.ts
@@ -24,11 +24,13 @@ export interface BaileysContactsHost {
resolvePhone(contactId: string): string | null;
listChats(): ChatSummary[];
/**
- * The chat's last known message (the handle readMessages/chatModify need), or null when none.
+ * The chat's last known message (the handle chatModify needs), or null when none.
* `jid` is the id the chat itself is keyed under, which for a lid-migrated contact is its lid
* whatever id was passed.
*/
lastMessage(chatId: string): { key: WAMessageKey; timestamp: number; jid: string } | null;
+ /** The newest message the chat received, the one a read receipt can acknowledge, or null when none. */
+ lastInboundMessage(chatId: string): { key: WAMessageKey; timestamp: number } | null;
/**
* Stored copies of the named messages, in whatever order the store returns them. Ids the store
* has never seen are absent, so neither the length nor the order tracks the input. `undefined`
@@ -344,14 +346,14 @@ export class BaileysContacts {
}
/**
- * The keys a read receipt should acknowledge: the messages the caller named, or the chat's newest
- * one when it named none.
+ * The keys a read receipt should acknowledge: the messages the caller named, or the newest one the
+ * chat received when it named none.
*
* Baileys acknowledges individual messages, not chats, and the receipt node enumerates ids rather
* than carrying a read-up-to watermark. Caller-supplied ids are what make that correct: the
- * lastMessage fallback holds only the newest message, so a burst of three inbound messages left
- * the first two permanently unread, and a session that restarted since the message arrived had
- * nothing to acknowledge at all (a silent false under a 200).
+ * lastInboundMessage fallback holds only the newest message, so a burst of three inbound messages
+ * left the first two permanently unread, and a session that restarted since the message arrived
+ * had nothing to acknowledge at all (a silent false under a 200).
*
* Named ids are resolved through the message store rather than synthesised, because the receipt
* needs the whole key. A synthesised key carries no `participant`, so a group receipt names no
@@ -364,7 +366,9 @@ export class BaileysContacts {
// null as well as undefined: the REST body rejects an explicit null, but this is the engine
// boundary and an internal caller reaching it with one used to dereference it below as a 500.
if (messageIds === undefined || messageIds === null) {
- const last = this.host.lastMessage(chatId);
+ // The newest RECEIVED message, not the preview: after an API reply the preview is an own key,
+ // which Baileys drops from the receipt, so the call would answer true having sent nothing.
+ const last = this.host.lastInboundMessage(chatId);
return last ? [last.key] : [];
}
if (messageIds.length === 0) {
diff --git a/src/engine/adapters/baileys-send-seen.spec.ts b/src/engine/adapters/baileys-send-seen.spec.ts
index 0634807ac..8bc109432 100644
--- a/src/engine/adapters/baileys-send-seen.spec.ts
+++ b/src/engine/adapters/baileys-send-seen.spec.ts
@@ -32,7 +32,7 @@ function makeHost(overrides: Partial<Record<keyof BaileysContactsHost, unknown>>
findContact: () => null,
resolvePhone: () => null,
listChats: () => [],
- lastMessage: () => ({ key: { id: 'M1', remoteJid: '[email protected]' }, timestamp: 1 }),
+ lastInboundMessage: () => ({ key: { id: 'M1', remoteJid: '[email protected]' }, timestamp: 1 }),
getStoredMessages: () => Promise.resolve([]),
toEngineJid,
...overrides,
@@ -196,7 +196,10 @@ describe('sendSeen', () => {
// The restart case: the in-memory store is empty, so the old code returned false under a 200
// and no receipt was ever sent. A caller that persisted the IDs is not subject to that.
const readMessages = jest.fn().mockResolvedValue(undefined);
- const host = makeHost({ getSocket: () => ({ readMessages }) as unknown as WASocket, lastMessage: () => null });
+ const host = makeHost({
+ getSocket: () => ({ readMessages }) as unknown as WASocket,
+ lastInboundMessage: () => null,
+ });
await expect(new BaileysContacts(host, 500).sendSeen('[email protected]', ['M9'])).resolves.toBe(true);
expect(readMessages).toHaveBeenCalledWith([{ remoteJid: '[email protected]', id: 'M9', fromMe: false }]);
});
@@ -219,14 +222,14 @@ describe('sendSeen', () => {
expect(readMessages).not.toHaveBeenCalled();
});
- it('falls back to the cached last message when no list is supplied', async () => {
+ it('falls back to the newest received message when no list is supplied', async () => {
const readMessages = jest.fn().mockResolvedValue(undefined);
await expect(contacts({ readMessages }, 500).sendSeen('[email protected]')).resolves.toBe(true);
expect(readMessages).toHaveBeenCalledWith([{ id: 'M1', remoteJid: '[email protected]' }]);
});
- it('still short-circuits when there is no last message to mark', async () => {
- const host = makeHost({ getSocket: () => ({}) as unknown as WASocket, lastMessage: () => null });
+ it('still short-circuits when no received message is known', async () => {
+ const host = makeHost({ getSocket: () => ({}) as unknown as WASocket, lastInboundMessage: () => null });
await expect(new BaileysContacts(host, 15).sendSeen('[email protected]')).resolves.toBe(false);
});
});
diff --git a/src/engine/adapters/baileys-session-store.spec.ts b/src/engine/adapters/baileys-session-store.spec.ts
index 801f63ed4..935864f84 100644
--- a/src/engine/adapters/baileys-session-store.spec.ts
+++ b/src/engine/adapters/baileys-session-store.spec.ts
@@ -654,6 +654,20 @@ describe('BaileysSessionStore', () => {
expect(s.lastMessage('[email protected]')?.jid).toBe(LID);
});
+ it('tracks the newest received message apart from the preview, for a read receipt', () => {
+ store.upsertChats([{ id: PHONE }]);
+ expect(store.lastInboundMessage('[email protected]')).toBeNull();
+ store.recordMessage(msg(PHONE, 'IN', 100));
+ store.recordMessage(msg('[email protected]', 'OUT', 200, true));
+ expect(store.lastMessage('[email protected]')?.key.id).toBe('OUT');
+ expect(store.lastInboundMessage('[email protected]')).toEqual({
+ key: { remoteJid: PHONE, fromMe: false, id: 'IN' },
+ timestamp: 100,
+ });
+ store.recordMessage(msg(PHONE, 'IN_OLDER', 50));
+ expect(store.lastInboundMessage(PHONE)?.key.id).toBe('IN');
+ });
+
it('keeps one entry when a chat with no record yet is addressed in both dialects', () => {
store.recordMessage(msg('[email protected]', 'OUT', 100, true));
store.recordKeyLidMappings({ remoteJid: LID, remoteJidAlt: PHONE });
diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.ts
index 904c3c1e8..895718078 100644
--- a/src/engine/adapters/baileys-session-store.ts
+++ b/src/engine/adapters/baileys-session-store.ts
@@ -181,6 +181,13 @@ export class BaileysSessionStore {
private readonly contacts: LruMap<string, BaileysContact>;
private readonly chats: LruMap<string, Chat>;
private readonly lastMessages: LruMap<string, LastMessage>;
+ /**
+ * The newest message each chat RECEIVED, kept apart from the preview because a read receipt can
+ * only acknowledge a message the other side sent: Baileys drops an own key from the receipt, so
+ * answering with the preview after an API reply sent nothing while the route reported success.
+ * An evicted entry reads null, which the receipt path answers as "nothing known".
+ */
+ private readonly lastInbound: LruMap<string, { key: WAMessageKey; timestamp: number }>;
private readonly lidToPn: LruMap<string, string>;
/**
* Per-chat disappearing-messages timer (seconds) learned from inbound messages (#473), the reliable
@@ -216,6 +223,7 @@ export class BaileysSessionStore {
this.contacts = new LruMap(maxEntries, contact => Boolean(contact.name));
this.chats = new LruMap(maxEntries);
this.lastMessages = new LruMap(maxEntries);
+ this.lastInbound = new LruMap(maxEntries);
this.lidToPn = new LruMap(maxEntries);
// Double-keyed (raw + neutral JID per chat), so it needs two slots per chat to cover the same span.
this.ephemeralByChat = new LruMap(maxEntries * 2);
@@ -338,6 +346,10 @@ export class BaileysSessionStore {
this.recordEphemeralFromMessage(chatId, msg);
const key = this.chatKey(chatId);
const timestamp = this.toUnixSeconds(msg.messageTimestamp);
+ if (!msg.key.fromMe) {
+ const inbound = this.lastInbound.get(key);
+ if (!inbound || inbound.timestamp < timestamp) this.lastInbound.set(key, { key: msg.key, timestamp });
+ }
const existing = this.lastMessages.get(key);
if (existing && existing.timestamp >= timestamp) {
return; // keep the newest
@@ -519,6 +531,11 @@ export class BaileysSessionStore {
return m ? { key: m.key, timestamp: m.timestamp, jid } : null;
}
+ /** The newest message the chat received (not one this account sent), or null when none is known. */
+ lastInboundMessage(chatId: string): { key: WAMessageKey; timestamp: number } | null {
+ return this.lastInbound.get(this.chatKey(chatId)) ?? null;
+ }
+
/**
* The chat's disappearing-messages timer in seconds (#473), or `undefined` when no timer is known.
* Only a positive value is returned: `0` / `null` / absent all mean "no known timer", so the caller
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 8b647d472..735607a6e 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -6045,6 +6045,40 @@ describe('BaileysAdapter sendSeen + markUnread + deleteChat', () => {
]);
});
+ it.each([
+ ['@c.us', '[email protected]'],
+ ['@s.whatsapp.net', '[email protected]'],
+ ])('sendSeen after an API reply to %s acknowledges the received message', async (_l, chatId) => {
+ fakeSock.sendMessage.mockImplementation((jid: string) =>
+ Promise.resolve({
+ key: { id: 'OUT', remoteJid: jid, fromMe: true },
+ message: { extendedTextMessage: { text: 'reply' } },
+ messageTimestamp: 1700000100,
+ }),
+ );
+ const adapter = await readyWithMessage();
+ fakeSock.fire('chats.upsert', [{ id: '[email protected]' }]);
+ await adapter.sendTextMessage(chatId, 'reply');
+ expect(await adapter.sendSeen(chatId)).toBe(true);
+ expect(fakeSock.readMessages).toHaveBeenCalledWith([
+ { remoteJid: '[email protected]', fromMe: false, id: 'M1' },
+ ]);
+ expect(await adapter.getChats()).toEqual([expect.objectContaining({ lastMessage: 'reply' })]);
+ });
+
+ it('sendSeen returns false when the only known message is an own send', async () => {
+ fakeSock.sendMessage.mockResolvedValue({
+ key: { id: 'OUT', remoteJid: '[email protected]', fromMe: true },
+ messageTimestamp: 1700000100,
+ });
+ const adapter = newAdapter();
+ await adapter.initialize({});
+ fakeSock.fire('connection.update', { connection: 'open' });
+ await adapter.sendTextMessage('[email protected]', 'hello');
+ expect(await adapter.sendSeen('[email protected]')).toBe(false);
+ expect(fakeSock.readMessages).not.toHaveBeenCalled();
+ });
+
it('sendSeen returns false when no last message is known', async () => {
const adapter = newAdapter();
await adapter.initialize({});
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index c7301562f..151175c8c 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -164,6 +164,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
resolvePhone: contactId => this.sessionStore.resolvePhone(contactId),
listChats: () => this.sessionStore.listChats(),
lastMessage: chatId => this.sessionStore.lastMessage(chatId),
+ lastInboundMessage: chatId => this.sessionStore.lastInboundMessage(chatId),
upsertContacts: records => this.sessionStore.upsertContacts(records),
upsertChats: records => this.sessionStore.upsertChats(records),
extractEphemeralDuration: msg => this.sessionStore.extractEphemeralDuration(msg),
diff --git a/src/modules/session/dto/mark-chat-read.dto.ts b/src/modules/session/dto/mark-chat-read.dto.ts
index 662b43e56..3e35c57e4 100644
--- a/src/modules/session/dto/mark-chat-read.dto.ts
+++ b/src/modules/session/dto/mark-chat-read.dto.ts
@@ -36,7 +36,7 @@ export class MarkChatReadDto {
@ApiPropertyOptional({
description:
'Specific message IDs to mark read. Baileys acknowledges individual messages, so without this ' +
- 'only the newest message the engine still holds in memory gets a receipt — a burst leaves its ' +
+ 'only the newest received message the engine still holds in memory gets a receipt — a burst leaves its ' +
'earlier messages unread forever, and a restarted session has no message to acknowledge at all. ' +
'Callers that persist inbound message IDs should send them here. Ignored by whatsapp-web.js, ' +
'whose own sendSeen is chat-level.',
diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.ts
index 6deadddc0..cbc3f04b5 100644
--- a/src/modules/session/session.controller.ts
+++ b/src/modules/session/session.controller.ts
@@ -536,9 +536,10 @@ export class SessionController {
status: 200,
description:
'Returns `{ success }`. `false` means the engine declined to act: the Baileys engine sends the ' +
- "read receipt against the chat's last known message, so a chat it has seen no message in is " +
- 'reported as declined rather than marked read. The whatsapp-web.js engine reads the chat from ' +
- 'the page and needs no local history.',
+ 'read receipt against the newest message the chat received, so a chat it has received no ' +
+ "message in (one holding only the account's own sends included) is reported as declined " +
+ 'rather than marked read. The whatsapp-web.js engine reads the chat from the page and needs no ' +
+ 'local history.',
type: SessionActionResponseDto,
})
@ApiResponse({ status: 400, description: 'Session not ready' })