Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(session): let callers name which messages a read receipt covers

m7fz793639e6dcfc9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6be08db98..742f06b6e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- `POST /sessions/{sessionId}/chats/read` accepts an optional `messageIds` array (up to 100) naming exactly which messages to acknowledge. Baileys acknowledges individual messages, so without it only the newest message still held in memory got a receipt: a burst left its earlier messages unread, and a session restarted since the message arrived had nothing to acknowledge and answered `false` under a `200`. Omitting the field keeps the previous behaviour, and the whatsapp-web.js engine ignores it because its own receipt is chat-level.
+
### Fixed
- The dashboard CSP nonce is substituted at every occurrence in the served document, not only the first. One placeholder exists today, so a second would have been left reading the literal text and its script refused by the browser.
diff --git a/openapi.json b/openapi.json
index 8d4b75aae..876cc3f2b 100644
--- a/openapi.json
+++ b/openapi.json
@@ -10261,6 +10261,17 @@
"type": "string",
"description": "Chat ID in the active engine's native format (e.g. [email protected] on whatsapp-web.js)",
"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.",
+ "example": [
+ "3EB0C767D26B8A3F1A2B",
+ "3EB0C767D26B8A3F1A2C"
+ ],
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
}
},
"required": [
diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.ts
index 19f48e6a0..1abbb3c72 100644
--- a/src/engine/adapters/baileys-contacts.ts
+++ b/src/engine/adapters/baileys-contacts.ts
@@ -318,16 +318,26 @@ export class BaileysContacts {
return this.host.listChats();
}
- async sendSeen(chatId: string): Promise<boolean> {
+ async sendSeen(chatId: string, messageIds?: string[]): Promise<boolean> {
this.host.ensureReady();
- const last = this.host.lastMessage(chatId);
- if (!last) {
+ // Baileys acknowledges individual messages, not chats. Caller-supplied IDs are what make this
+ // correct: the in-memory fallback below 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 (returning a silent false under a 200).
+ // A caller that persists inbound message IDs has both, so it can name exactly what to mark.
+ const keys: WAMessageKey[] = messageIds?.length
+ ? messageIds.map(id => ({ remoteJid: this.host.toEngineJid(chatId), id, fromMe: false }))
+ : (() => {
+ const last = this.host.lastMessage(chatId);
+ return last ? [last.key] : [];
+ })();
+ if (keys.length === 0) {
return false; // nothing known to mark read
}
// readMessages reaches fetchPrivacySettings, which destructures the query result and throws a
// raw TypeError on an unanswered one — no Boom, so nothing downstream can classify it. Marking
// a chat read is idempotent, so bounding it is safe: a repeat costs nothing.
- await this.confirmed(this.sock().readMessages([last.key]), 'the read receipt');
+ await this.confirmed(this.sock().readMessages(keys), 'the read receipt');
return true;
}
diff --git a/src/engine/adapters/baileys-send-seen.spec.ts b/src/engine/adapters/baileys-send-seen.spec.ts
index 992a4c658..a72f26624 100644
--- a/src/engine/adapters/baileys-send-seen.spec.ts
+++ b/src/engine/adapters/baileys-send-seen.spec.ts
@@ -40,6 +40,39 @@ describe('sendSeen', () => {
await expect(contacts({ readMessages }, 500).sendSeen('[email protected]')).resolves.toBe(true);
});
+ it('acknowledges every supplied message, not just the newest one', async () => {
+ // The whole point of the caller-supplied list: a burst of three inbound messages used to leave
+ // the first two unread forever, because only lastMessage() was ever acknowledged.
+ const readMessages = jest.fn().mockResolvedValue(undefined);
+ await expect(contacts({ readMessages }, 500).sendSeen('[email protected]', ['M1', 'M2', 'M3'])).resolves.toBe(true);
+ expect(readMessages).toHaveBeenCalledWith([
+ { remoteJid: '[email protected]', id: 'M1', fromMe: false },
+ { remoteJid: '[email protected]', id: 'M2', fromMe: false },
+ { remoteJid: '[email protected]', id: 'M3', fromMe: false },
+ ]);
+ });
+
+ it('marks supplied messages even when the store has nothing cached', async () => {
+ // 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 = {
+ ensureReady: () => undefined,
+ getSocket: () => ({ readMessages }) as unknown as WASocket,
+ logger: { warn: jest.fn(), debug: jest.fn(), info: jest.fn(), error: jest.fn() },
+ lastMessage: () => null,
+ toEngineJid: (j: string) => j,
+ } as unknown as BaileysContactsHost;
+ await expect(new BaileysContacts(host, 500).sendSeen('[email protected]', ['M9'])).resolves.toBe(true);
+ expect(readMessages).toHaveBeenCalledWith([{ remoteJid: '[email protected]', id: 'M9', fromMe: false }]);
+ });
+
+ it('falls back to the cached last message when the caller supplies an empty list', 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 = {
ensureReady: () => undefined,
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 2f78c75ea..616b10d99 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -509,8 +509,8 @@ export class BaileysAdapter implements IWhatsAppEngine {
return this.messaging.subscribeToPresence(chatId);
}
- async sendSeen(chatId: string): Promise<boolean> {
- return this.contacts.sendSeen(chatId);
+ async sendSeen(chatId: string, messageIds?: string[]): Promise<boolean> {
+ return this.contacts.sendSeen(chatId, messageIds);
}
async markUnread(chatId: string): Promise<boolean> {
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 20d0cdd4f..d6fa18e09 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -889,6 +889,8 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
return this.chats.getChats();
}
+ // messageIds is dropped on purpose: whatsapp-web.js exposes only a chat-level sendSeen, which
+ // already marks every message in the chat.
sendSeen(chatId: string): Promise<boolean> {
return this.chats.sendSeen(chatId);
}
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index 2a1ef12e8..7a2557159 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -1297,7 +1297,12 @@ export interface CatalogCapability {
export interface ChatCapability {
getChats(): Promise<ChatSummary[]>;
- sendSeen(chatId: string): Promise<boolean>;
+ /**
+ * `messageIds` names exactly which messages to acknowledge. Engines that acknowledge per
+ * message (Baileys) need it to mark a burst, or anything at all after a restart; engines with a
+ * chat-level receipt (whatsapp-web.js) ignore it.
+ */
+ sendSeen(chatId: string, messageIds?: string[]): Promise<boolean>;
markUnread(chatId: string): Promise<boolean>;
diff --git a/src/modules/session/dto/mark-chat-read.dto.ts b/src/modules/session/dto/mark-chat-read.dto.ts
index 08511923e..4755a8d8e 100644
--- a/src/modules/session/dto/mark-chat-read.dto.ts
+++ b/src/modules/session/dto/mark-chat-read.dto.ts
@@ -1,5 +1,5 @@
-import { ApiProperty } from '@nestjs/swagger';
-import { IsNotEmpty, IsString, Matches } from 'class-validator';
+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
+import { ArrayMaxSize, IsArray, IsNotEmpty, IsOptional, IsString, Matches } from 'class-validator';
export class MarkChatReadDto {
@ApiProperty({
@@ -15,4 +15,23 @@ export class MarkChatReadDto {
message: 'chatId must be a valid chat JID in the form localpart@host',
})
chatId!: string;
+
+ @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 ' +
+ '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.',
+ type: [String],
+ example: ['3EB0C767D26B8A3F1A2B', '3EB0C767D26B8A3F1A2C'],
+ })
+ @IsOptional()
+ @IsArray()
+ // Bounded so one request cannot hand the engine an unbounded key list to round-trip; a caller with
+ // more than this to acknowledge is catching up on history, not marking a conversation read.
+ @ArrayMaxSize(100)
+ @IsString({ each: true })
+ @IsNotEmpty({ each: true })
+ messageIds?: string[];
}
diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.ts
index b43955db4..f0e62ee16 100644
--- a/src/modules/session/session.controller.ts
+++ b/src/modules/session/session.controller.ts
@@ -469,7 +469,7 @@ export class SessionController {
@Param('sessionId', ParseUUIDPipe) id: string,
@Body() dto: MarkChatReadDto,
): Promise<{ success: boolean }> {
- const success = await this.sessionService.sendSeen(id, dto.chatId);
+ const success = await this.sessionService.sendSeen(id, dto.chatId, dto.messageIds);
return { success };
}
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 657f619d6..73713e650 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -5151,10 +5151,25 @@ describe('SessionService', () => {
const result = await service.sendSeen('sess-uuid-1', '[email protected]');
- expect(mockEngine.sendSeen).toHaveBeenCalledWith('[email protected]');
+ // Second argument is the optional messageIds, absent here — the engine falls back to the
+ // newest message it still holds.
+ expect(mockEngine.sendSeen).toHaveBeenCalledWith('[email protected]', undefined);
expect(result).toBe(true);
});
+ it('should forward caller-supplied message IDs to the engine', async () => {
+ const session = createMockSession();
+ (repository.findOne as jest.Mock).mockResolvedValue(session);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ await service.start('sess-uuid-1');
+ mockEngine.sendSeen.mockResolvedValue(true);
+
+ await service.sendSeen('sess-uuid-1', '[email protected]', ['M1', 'M2']);
+
+ expect(mockEngine.sendSeen).toHaveBeenCalledWith('[email protected]', ['M1', 'M2']);
+ });
+
it('should throw BadRequestException when session is not started', async () => {
const session = createMockSession();
(repository.findOne as jest.Mock).mockResolvedValue(session);
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index f0cce08ea..3c48ff734 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -664,11 +664,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return this.presence.get(id, chatId);
}
- async sendSeen(id: string, chatId: string): Promise<boolean> {
+ async sendSeen(id: string, chatId: string, messageIds?: string[]): Promise<boolean> {
await this.findOne(id); // Verify session exists
const engine = this.requireEngine(id);
- return engine.sendSeen(chatId);
+ return engine.sendSeen(chatId, messageIds);
}
async markUnread(id: string, chatId: string): Promise<boolean> {