Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): resolve read receipts through the message store
m7fz74d7f98799e20
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 742f06b6e..dc865c210 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,7 +9,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### 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.+- `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`. Each id is resolved through the message store, so a group receipt carries the `participant` that attributes it. Omitting the field keeps the previous behaviour, an empty array is refused with a `400` rather than silently acknowledging the newest message, and the whatsapp-web.js engine ignores the field because its own receipt is chat-level. The `SessionMarkChatRead` agent tool takes the same list.++### Changed++- `POST /sessions/{sessionId}/chats/unread` publishes its own `MarkChatUnreadDto` instead of sharing `MarkChatReadDto` with the read route. The request body is unchanged (`chatId` alone), but a client generated from the contract sees the schema under a new name. Sharing the class would have advertised `messageIds` on a route that discards it.### Fixeddiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 41d036c0f..2a0dada86 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -836,12 +836,15 @@ Mark a chat as read/seen.**Request body** — `MarkChatReadDto`-| Field | Type | Required | Constraints | Description |-| -------- | ------ | -------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |-| `chatId` | string | Yes | `@IsString`; `@IsNotEmpty`; `@Matches(/^[^\s@]+@[^\s@]+$/)` (localpart@host, no whitespace) | Engine-native JID, e.g. `[email protected]` (wwebjs) or `[email protected]` (Baileys) |+| Field | Type | Required | Constraints | Description |+| ------------ | -------- | -------- | --------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |+| `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.```json-{ "chatId": "[email protected]" }+{ "chatId": "[email protected]", "messageIds": ["3EB0C767D26B8A3F1A2B", "3EB0C767D26B8A3F1A2C"] }```**Response** `200`@@ -871,12 +874,14 @@ Mark a chat as unread.| ----------- | ------ | ------------ || `sessionId` | string | Session UUID |-**Request body** — `MarkChatReadDto` (reused)+**Request body** — `MarkChatUnreadDto`| Field | Type | Required | Constraints | Description || -------- | ------ | -------- | ----------------------------------------------------------- | ----------------------------------------- || `chatId` | string | Yes | `@IsString`; `@IsNotEmpty`; `@Matches(/^[^\s@]+@[^\s@]+$/)` | Engine-native JID, e.g. `[email protected]` |+This route takes `chatId` alone. It previously shared `MarkChatReadDto`, which is why the two are described separately now that the read body carries `messageIds`.+```json{ "chatId": "[email protected]" }```diff --git a/docs/07-api-collection.md b/docs/07-api-collection.mdindex 0f047c9e5..5e1acd41f 100644--- a/docs/07-api-collection.md+++ b/docs/07-api-collection.md@@ -214,9 +214,12 @@ Mark a chat as read/seen (OPERATOR).curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/chats/read" \-H "X-API-Key: $API_KEY" \-H "Content-Type: application/json" \- -d '{ "chatId": "[email protected]" }'+ -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.+#### POST /api/sessions/:sessionId/chats/unreadMark a chat as unread (OPERATOR).diff --git a/openapi.json b/openapi.jsonindex 876cc3f2b..fcd120859 100644--- a/openapi.json+++ b/openapi.json@@ -1237,7 +1237,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/MarkChatReadDto"+ "$ref": "#/components/schemas/MarkChatUnreadDto"}}}@@ -10264,6 +10264,7 @@},"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.",+ "maxItems": 100,"example": ["3EB0C767D26B8A3F1A2B","3EB0C767D26B8A3F1A2C"@@ -10379,6 +10380,19 @@"observedAt"]},+ "MarkChatUnreadDto": {+ "type": "object",+ "properties": {+ "chatId": {+ "type": "string",+ "description": "Chat ID in the active engine's native format (e.g. [email protected] on whatsapp-web.js)",+ "example": "[email protected]"+ }+ },+ "required": [+ "chatId"+ ]+ },"ArchiveChatDto": {"type": "object","properties": {diff --git a/scripts/check-contract-shapes.mjs b/scripts/check-contract-shapes.mjsindex 48ef83c5e..534ec0e4f 100644--- a/scripts/check-contract-shapes.mjs+++ b/scripts/check-contract-shapes.mjs@@ -85,7 +85,8 @@ const MAPPINGS = {GroupSubjectRequest: 'GroupSubjectDto',GroupSummary: 'GroupSummaryDto',JoinGroupRequest: 'JoinGroupDto',- MarkChatRequest: 'MarkChatReadDto',+ MarkChatReadRequest: 'MarkChatReadDto',+ MarkChatRequest: 'MarkChatUnreadDto',MessageListResponse: 'MessageListResponseDto',MessageRecord: 'MessageListItemDto',MessageResponse: 'MessageResponseDto',@@ -164,7 +165,7 @@ const MAPPINGS = {* these floors as pairs are added makes the shrink loud.*/const MINIMUM_MAPPED = {- 'sdk/javascript/src/types.ts': 78,+ 'sdk/javascript/src/types.ts': 79,'dashboard/src/services/api.ts': 20,'sdk/python/openwa/types.py': 73,'sdk/go': 74,diff --git a/sdk/javascript/src/resources/chats.ts b/sdk/javascript/src/resources/chats.tsindex bece30025..61da4559b 100644--- a/sdk/javascript/src/resources/chats.ts+++ b/sdk/javascript/src/resources/chats.ts@@ -17,6 +17,7 @@ import type {ChatSummary,DeleteChatRequest,MarkChatRequest,+ MarkChatReadRequest,ChatPresence,SendChatStateRequest,SuccessResult,@@ -67,7 +68,7 @@ export class ChatsResource {}/** Mark a chat as read/seen. */- markRead(sessionId: string, body: MarkChatRequest): Promise<SuccessResult> {+ markRead(sessionId: string, body: MarkChatReadRequest): Promise<SuccessResult> {return this.client.request<SuccessResult>({method: 'POST',path: `/api/sessions/${encodeSegment(sessionId)}/chats/read`,diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.tsindex f940b305c..a77e31041 100644--- a/sdk/javascript/src/types.ts+++ b/sdk/javascript/src/types.ts@@ -968,10 +968,23 @@ export interface TransferChannelOwnershipRequest {newOwnerId: Jid;}+/** Body for {@link ChatsResource.markUnread} and {@link ChatsResource.subscribePresence}. */export interface MarkChatRequest {chatId: Jid;}+/** Body for {@link ChatsResource.markRead}. */+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.+ * 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.+ */+ messageIds?: string[];+}+export type ChatState = 'typing' | 'recording' | 'paused';export interface SendChatStateRequest {diff --git a/src/core/agent-tools/tools/session.tools.spec.ts b/src/core/agent-tools/tools/session.tools.spec.tsindex 5a001b0e9..84cbf657b 100644--- a/src/core/agent-tools/tools/session.tools.spec.ts+++ b/src/core/agent-tools/tools/session.tools.spec.ts@@ -90,10 +90,20 @@ describe('sessionTools', () => {sessionId: 's1',chatId: '[email protected]',});- expect(sendSeen).toHaveBeenCalledWith('s1', '[email protected]');+ expect(sendSeen).toHaveBeenCalledWith('s1', '[email protected]', undefined);expect(out).toEqual({ success: true });});+ it('SessionMarkChatRead forwards the message ids it was given', async () => {+ const sendSeen = jest.fn().mockResolvedValue(true);+ await run(makeTools({ sendSeen } as unknown as SessionService).get('SessionMarkChatRead')!, {+ sessionId: 's1',+ chatId: '[email protected]',+ messageIds: ['M1', 'M2'],+ });+ expect(sendSeen).toHaveBeenCalledWith('s1', '[email protected]', ['M1', 'M2']);+ });+it('SessionMarkChatUnread maps the markUnread result to a success field', async () => {const markUnread = jest.fn().mockResolvedValue(true);const out = await run(makeTools({ markUnread } as unknown as SessionService).get('SessionMarkChatUnread')!, {diff --git a/src/core/agent-tools/tools/session.tools.ts b/src/core/agent-tools/tools/session.tools.tsindex 0d9767a52..916d203e8 100644--- a/src/core/agent-tools/tools/session.tools.ts+++ b/src/core/agent-tools/tools/session.tools.ts@@ -2,6 +2,7 @@ import { z } from 'zod';import { ApiKeyRole } from '../../../modules/auth/entities/api-key.entity';import type { SessionService } from '../../../modules/session/session.service';import { SessionResponseDto } from '../../../modules/session/dto/session-response.dto';+import { MARK_READ_MESSAGE_IDS_MAX } from '../../../modules/session/dto/mark-chat-read.dto';import { defineTool, type AnyToolDescriptor } from '../tool-descriptor';const sessionId = z.string().min(1).describe('Session UUID (the session id, not the name)');@@ -89,8 +90,18 @@ export function sessionTools(session: SessionService): AnyToolDescriptor[] {inputSchema: z.object({sessionId,chatId: z.string().describe('Chat JID (e.g. [email protected])'),+ messageIds: z+ .array(z.string())+ .nonempty()+ .max(MARK_READ_MESSAGE_IDS_MAX)+ .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.',+ ),}),- handler: input => session.sendSeen(input.sessionId, input.chatId).then(success => ({ success })),+ handler: input =>+ session.sendSeen(input.sessionId, input.chatId, input.messageIds).then(success => ({ success })),}),defineTool({name: 'SessionMarkChatUnread',diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex 1abbb3c72..c176bef37 100644--- a/src/engine/adapters/baileys-contacts.ts+++ b/src/engine/adapters/baileys-contacts.ts@@ -1,4 +1,4 @@-import type { WAMessageKey, WASocket } from '@whiskeysockets/baileys';+import type { WAMessage, WAMessageKey, WASocket } from '@whiskeysockets/baileys';import { ChatSummary, Contact, MediaInput } from '../interfaces/whatsapp-engine.interface';import { resolveMediaBuffer } from './baileys-messaging';import { type createLogger } from '../../common/services/logger.service';@@ -23,6 +23,12 @@ export interface BaileysContactsHost {listChats(): ChatSummary[];/** The chat's last known message (the handle readMessages/chatModify need), or null when none. */lastMessage(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`+ * when the session was built without a message store.+ */+ getStoredMessages(messageIds: string[]): Promise<WAMessage[]> | undefined;/** Fold a neutral @c.us id to the engine @s.whatsapp.net form used as the app-state index key. */toEngineJid(jid: string): string;/** Fold an engine jid back to the neutral dialect before it crosses the engine boundary. */@@ -320,17 +326,7 @@ export class BaileysContacts {async sendSeen(chatId: string, messageIds?: string[]): Promise<boolean> {this.host.ensureReady();- // 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] : [];- })();+ const keys = await this.receiptKeys(chatId, messageIds);if (keys.length === 0) {return false; // nothing known to mark read}@@ -341,6 +337,37 @@ export class BaileysContacts {return true;}+ /**+ * The keys a read receipt should acknowledge: the messages the caller named, or the chat's newest+ * one 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).+ *+ * 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+ * sender; its hardcoded `fromMe: false` is wrong for an id that belongs to an outbound message;+ * and its jid is whichever dialect the caller happened to send. The stored key has all three+ * right. Ids the store has never seen — history backfill is emitted but not persisted — keep the+ * synthesised key, which is what the 1:1 case ran on before.+ */+ private async receiptKeys(chatId: string, messageIds?: string[]): Promise<WAMessageKey[]> {+ if (messageIds === undefined) {+ const last = this.host.lastMessage(chatId);+ return last ? [last.key] : [];+ }+ if (messageIds.length === 0) {+ return []; // an explicit empty list asks for nothing to be acknowledged, not for the newest+ }+ const remoteJid = this.host.toEngineJid(chatId);+ const stored = (await this.host.getStoredMessages(messageIds)) ?? [];+ const keyById = new Map(stored.filter(msg => msg.key?.id).map(msg => [msg.key.id as string, msg.key]));+ return messageIds.map(id => keyById.get(id) ?? { remoteJid, id, fromMe: false });+ }+async markUnread(chatId: string): Promise<boolean> {this.host.ensureReady();const last = this.host.lastMessage(chatId);diff --git a/src/engine/adapters/baileys-message-store.service.spec.ts b/src/engine/adapters/baileys-message-store.service.spec.tsindex 65e5fa167..273f43a96 100644--- a/src/engine/adapters/baileys-message-store.service.spec.ts+++ b/src/engine/adapters/baileys-message-store.service.spec.ts@@ -181,6 +181,39 @@ describe('BaileysMessageStoreService', () => {await expect(service.put('s1', msg('M1'))).rejects.toThrow('disk full');});+ describe('getMessages', () => {+ it('returns the batch in one query, skipping ids it has never seen', async () => {+ await seedSession('s1');+ await service.put('s1', msg('M1'));+ await service.put('s1', msg('M2'));+ const found = await service.getMessages('s1', ['M1', 'MISSING', 'M2']);+ expect(found.map(m => m.key.id).sort()).toEqual(['M1', 'M2']);+ });++ it('stays scoped to its own session', async () => {+ await seedSession('s1');+ await seedSession('s2');+ await service.put('s2', msg('M1'));+ expect(await service.getMessages('s1', ['M1'])).toEqual([]);+ });++ it('short-circuits on an empty or all-falsy id list instead of querying', async () => {+ // An empty In() clause is a SQL syntax error on some drivers and matches everything on others.+ const find = jest.spyOn(repo, 'find');+ expect(await service.getMessages('s1', [])).toEqual([]);+ expect(await service.getMessages('s1', [''])).toEqual([]);+ expect(find).not.toHaveBeenCalled();+ });++ it('round-trips binary fields the same way getMessage does', async () => {+ await seedSession('s1');+ await service.put('s1', msg('M1'));+ const [found] = await service.getMessages('s1', ['M1']);+ // mediaKey is off the public WAMessage type, like the fixture that wrote it.+ expect(Buffer.isBuffer((found as unknown as { mediaKey: unknown }).mediaKey)).toBe(true);+ });+ });+it('clearSession removes only that session', async () => {await seedSession('s1');await seedSession('s2');diff --git a/src/engine/adapters/baileys-message-store.service.ts b/src/engine/adapters/baileys-message-store.service.tsindex 1f4bb623d..5d3d210ca 100644--- a/src/engine/adapters/baileys-message-store.service.ts+++ b/src/engine/adapters/baileys-message-store.service.ts@@ -1,6 +1,6 @@import { Injectable } from '@nestjs/common';import { InjectRepository } from '@nestjs/typeorm';-import { Repository } from 'typeorm';+import { In, Repository } from 'typeorm';import type * as BaileysLib from '@whiskeysockets/baileys';import type { WAMessage } from '@whiskeysockets/baileys';import { BaileysStoredMessage } from './baileys-stored-message.entity';@@ -99,6 +99,21 @@ export class BaileysMessageStoreService implements BaileysMessageStore {return JSON.parse(row.serializedMessage, BufferJSON.reviver) as WAMessage;}+ async getMessages(sessionId: string, messageIds: string[]): Promise<WAMessage[]> {+ // One query for the whole batch: the read-receipt path resolves up to a hundred ids at a time,+ // and a findOne apiece would be a hundred sequential round trips for a single request.+ const ids = messageIds.filter(Boolean);+ if (ids.length === 0) {+ return [];+ }+ const rows = await this.repo.find({ where: { sessionId, waMessageId: In(ids) } });+ if (rows.length === 0) {+ return [];+ }+ const { BufferJSON } = await this.loadLib();+ return rows.map(row => JSON.parse(row.serializedMessage, BufferJSON.reviver) as WAMessage);+ }+async clearSession(sessionId: string): Promise<void> {await this.repo.delete({ sessionId });}diff --git a/src/engine/adapters/baileys-send-seen.spec.ts b/src/engine/adapters/baileys-send-seen.spec.tsindex a72f26624..b9e735399 100644--- a/src/engine/adapters/baileys-send-seen.spec.ts+++ b/src/engine/adapters/baileys-send-seen.spec.ts@@ -1,4 +1,4 @@-import type { WASocket } from '@whiskeysockets/baileys';+import type { WAMessage, WASocket } from '@whiskeysockets/baileys';import { BaileysContacts, BaileysContactsHost } from './baileys-contacts';import { EngineTransportError } from '../../common/errors/engine-transport.error';@@ -12,10 +12,19 @@ import { EngineTransportError } from '../../common/errors/engine-transport.error*/const never = (): Promise<never> => new Promise<never>(() => undefined);-function contacts(sock: Record<string, jest.Mock>, budgetMs: number): BaileysContacts {- const host = {+/**+ * The real fold, not an identity stub. A stub that returned its argument unchanged let the whole+ * suite pass with the `toEngineJid` call deleted outright, and left the fallback case asserting+ * `@s.whatsapp.net` while the supplied-id cases asserted `@c.us` for the same chat.+ */+const toEngineJid = (jid: string): string => {+ const [userPart, host] = jid.split('@');+ return host === 'c.us' || host === 's.whatsapp.net' ? `${userPart}@s.whatsapp.net` : jid;+};++function makeHost(overrides: Partial<Record<keyof BaileysContactsHost, unknown>>): BaileysContactsHost {+ return {ensureReady: () => undefined,- getSocket: () => sock as unknown as WASocket,logger: { warn: jest.fn(), debug: jest.fn(), info: jest.fn(), error: jest.fn() },normalizedSelfJid: () => '[email protected]',listContacts: () => [],@@ -23,11 +32,19 @@ function contacts(sock: Record<string, jest.Mock>, budgetMs: number): BaileysConresolvePhone: () => null,listChats: () => [],lastMessage: () => ({ key: { id: 'M1', remoteJid: '[email protected]' }, timestamp: 1 }),- toEngineJid: (j: string) => j,+ getStoredMessages: () => Promise.resolve([]),+ toEngineJid,+ ...overrides,} as unknown as BaileysContactsHost;- return new BaileysContacts(host, budgetMs);}+function contacts(sock: Record<string, jest.Mock>, budgetMs: number): BaileysContacts {+ return new BaileysContacts(makeHost({ getSocket: () => sock as unknown as WASocket }), budgetMs);+}++/** A stored message as the message store hands it back: the whole key, not a synthesised one. */+const stored = (key: WAMessage['key']): WAMessage => ({ key, message: {}, messageTimestamp: 1 });+describe('sendSeen', () => {it('reports an unanswered read receipt instead of a bare 500', async () => {await expect(contacts({ readMessages: jest.fn(never) }, 15).sendSeen('[email protected]')).rejects.toBeInstanceOf(@@ -46,9 +63,53 @@ describe('sendSeen', () => {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 },+ { remoteJid: '[email protected]', id: 'M1', fromMe: false },+ { remoteJid: '[email protected]', id: 'M2', fromMe: false },+ { remoteJid: '[email protected]', id: 'M3', fromMe: false },+ ]);+ });++ it('carries the participant on a group receipt, which a synthesised key cannot', async () => {+ // A group receipt with no `participant` names no sender, so WhatsApp cannot attribute it and+ // the message stays unread on the sender's side while the API answers success: true.+ const readMessages = jest.fn().mockResolvedValue(undefined);+ const host = makeHost({+ getSocket: () => ({ readMessages }) as unknown as WASocket,+ getStoredMessages: () =>+ Promise.resolve([+ stored({ id: 'G1', remoteJid: '[email protected]', fromMe: false, participant: '[email protected]' }),+ ]),+ });+ await expect(new BaileysContacts(host, 500).sendSeen('[email protected]', ['G1'])).resolves.toBe(true);+ expect(readMessages).toHaveBeenCalledWith([+ { id: 'G1', remoteJid: '[email protected]', fromMe: false, participant: '[email protected]' },+ ]);+ });++ it('takes fromMe from the stored key rather than assuming inbound', async () => {+ const readMessages = jest.fn().mockResolvedValue(undefined);+ const host = makeHost({+ getSocket: () => ({ readMessages }) as unknown as WASocket,+ getStoredMessages: () =>+ Promise.resolve([stored({ id: 'O1', remoteJid: '[email protected]', fromMe: true })]),+ });+ await expect(new BaileysContacts(host, 500).sendSeen('[email protected]', ['O1'])).resolves.toBe(true);+ expect(readMessages).toHaveBeenCalledWith([{ id: 'O1', remoteJid: '[email protected]', fromMe: true }]);+ });++ it('synthesises a key only for ids the store has never seen', async () => {+ // History-sync backfill is emitted but never persisted, so a legitimate id can miss. Falling+ // back keeps the 1:1 case working instead of silently dropping the message from the receipt.+ const readMessages = jest.fn().mockResolvedValue(undefined);+ const host = makeHost({+ getSocket: () => ({ readMessages }) as unknown as WASocket,+ getStoredMessages: () =>+ Promise.resolve([stored({ id: 'K1', remoteJid: '[email protected]', fromMe: true })]),+ });+ await expect(new BaileysContacts(host, 500).sendSeen('[email protected]', ['K1', 'MISSING'])).resolves.toBe(true);+ expect(readMessages).toHaveBeenCalledWith([+ { id: 'K1', remoteJid: '[email protected]', fromMe: true },+ { remoteJid: '[email protected]', id: 'MISSING', fromMe: false },]);});@@ -56,30 +117,37 @@ 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 = {- ensureReady: () => undefined,+ const host = makeHost({ getSocket: () => ({ readMessages }) as unknown as WASocket, lastMessage: () => null });+ await expect(new BaileysContacts(host, 500).sendSeen('[email protected]', ['M9'])).resolves.toBe(true);+ expect(readMessages).toHaveBeenCalledWith([{ remoteJid: '[email protected]', id: 'M9', fromMe: false }]);+ });++ it('works without a message store at all', async () => {+ const readMessages = jest.fn().mockResolvedValue(undefined);+ const host = makeHost({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;+ getStoredMessages: () => undefined,+ });await expect(new BaileysContacts(host, 500).sendSeen('[email protected]', ['M9'])).resolves.toBe(true);- expect(readMessages).toHaveBeenCalledWith([{ remoteJid: '[email protected]', id: 'M9', fromMe: false }]);+ 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 () => {+ it('acknowledges nothing when the caller supplies an empty list', async () => {+ // An empty list is a caller that computed its unread set and found none. Folding it into the+ // no-list branch would acknowledge the newest message, which is the opposite of the request.const readMessages = jest.fn().mockResolvedValue(undefined);- await expect(contacts({ readMessages }, 500).sendSeen('[email protected]', [])).resolves.toBe(true);+ await expect(contacts({ readMessages }, 500).sendSeen('[email protected]', [])).resolves.toBe(false);+ expect(readMessages).not.toHaveBeenCalled();+ });++ it('falls back to the cached last 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 = {- ensureReady: () => undefined,- getSocket: () => ({}) as unknown as WASocket,- logger: { warn: jest.fn(), debug: jest.fn(), info: jest.fn(), error: jest.fn() },- lastMessage: () => null,- } as unknown as BaileysContactsHost;+ const host = makeHost({ getSocket: () => ({}) as unknown as WASocket, lastMessage: () => null });await expect(new BaileysContacts(host, 15).sendSeen('[email protected]')).resolves.toBe(false);});});diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 029ac4d70..5e790a664 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -150,6 +150,7 @@ import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';const fakeStore = {put: jest.fn().mockResolvedValue(undefined),getMessage: jest.fn(),+ getMessages: jest.fn().mockResolvedValue([]),clearSession: jest.fn().mockResolvedValue(undefined),};diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 616b10d99..f577fde50 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -153,6 +153,7 @@ export class BaileysAdapter implements IWhatsAppEngine {toEngineJid: jid => this.sessionStore.toEngineJid(jid),getEphemeralExpiration: chatId => this.sessionStore.getEphemeralExpiration(chatId),getStoredMessage: messageId => this.config.messageStore?.getMessage(this.config.dbSessionId, messageId),+ getStoredMessages: messageIds => this.config.messageStore?.getMessages(this.config.dbSessionId, messageIds),recordLidMapping: (lid, pn) =>this.sessionStore.addLidMappings([{ lid: `${lid.split('@')[0].split(':')[0]}@lid`, pn }]),mapMessage: (msg, contentType, opts) => this.events.mapMessage(msg, contentType, opts),diff --git a/src/engine/builtin/baileys/index.spec.ts b/src/engine/builtin/baileys/index.spec.tsindex c1c9d3f6f..f4c6bd450 100644--- a/src/engine/builtin/baileys/index.spec.ts+++ b/src/engine/builtin/baileys/index.spec.ts@@ -59,7 +59,7 @@ describe('BaileysPlugin.createEngine (opaque config)', () => {});it('passes the message store to the adapter', () => {- const store = { put: jest.fn(), getMessage: jest.fn(), clearSession: jest.fn() };+ const store = { put: jest.fn(), getMessage: jest.fn(), getMessages: jest.fn(), clearSession: jest.fn() };const plugin = new BaileysPlugin(store);plugin.createEngine({ sessionId: 'sess-1' });expect(BaileysAdapter).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'sess-1', messageStore: store }));diff --git a/src/engine/types/baileys.types.ts b/src/engine/types/baileys.types.tsindex 418aa697b..dfa2d11ce 100644--- a/src/engine/types/baileys.types.ts+++ b/src/engine/types/baileys.types.ts@@ -10,6 +10,11 @@ export interface BaileysMessageStore {put(sessionId: string, msg: WAMessage): Promise<void>;/** Look up a previously-seen message by its id, or null. */getMessage(sessionId: string, messageId: string): Promise<WAMessage | null>;+ /**+ * Look up many messages in one query. Ids the store has never seen are simply absent from the+ * result, so the caller cannot assume the order or the length matches its input.+ */+ getMessages(sessionId: string, messageIds: string[]): Promise<WAMessage[]>;/** Remove all stored messages for a session (called on logout). */clearSession(sessionId: string): Promise<void>;}diff --git a/src/modules/session/dto/index.ts b/src/modules/session/dto/index.tsindex 42b372d44..ceb019f79 100644--- a/src/modules/session/dto/index.ts+++ b/src/modules/session/dto/index.ts@@ -2,6 +2,7 @@ export * from './create-session.dto';export * from './session-config.dto';export * from './session-response.dto';export * from './mark-chat-read.dto';+export * from './mark-chat-unread.dto';export * from './archive-chat.dto';export * from './mute-chat.dto';export * from './pin-chat.dto';diff --git a/src/modules/session/dto/mark-chat-read.dto.spec.ts b/src/modules/session/dto/mark-chat-read.dto.spec.tsindex f62f04268..24a88ff3f 100644--- a/src/modules/session/dto/mark-chat-read.dto.spec.ts+++ b/src/modules/session/dto/mark-chat-read.dto.spec.ts@@ -1,6 +1,6 @@import { validateSync } from 'class-validator';import { plainToInstance } from 'class-transformer';-import { MarkChatReadDto } from './mark-chat-read.dto';+import { MARK_READ_MESSAGE_IDS_MAX, MarkChatReadDto } from './mark-chat-read.dto';const errorCount = (chatId: unknown): number => validateSync(plainToInstance(MarkChatReadDto, { chatId })).length;@@ -21,3 +21,35 @@ describe('MarkChatReadDto chatId validation', () => {},);});++const messageIdErrors = (messageIds: unknown): number =>+ validateSync(plainToInstance(MarkChatReadDto, { chatId: '[email protected]', messageIds })).length;++describe('MarkChatReadDto messageIds validation', () => {+ it('accepts the field being absent — it is what every pre-existing caller sends', () => {+ expect(validateSync(plainToInstance(MarkChatReadDto, { chatId: '[email protected]' })).length).toBe(0);+ });++ it('accepts a list of ids', () => {+ expect(messageIdErrors(['3EB0C767D26B8A3F1A2B', '3EB0C767D26B8A3F1A2C'])).toBe(0);+ });++ it('rejects an empty list rather than reading it as "the newest message"', () => {+ // The engine treats a missing list as "acknowledge the newest message". A caller that computed+ // its unread set and got none back must not land in that branch.+ expect(messageIdErrors([])).toBeGreaterThan(0);+ });++ it('accepts a full batch and rejects one over the cap', () => {+ const id = (n: number): string => `MSG${n}`;+ expect(messageIdErrors(Array.from({ length: MARK_READ_MESSAGE_IDS_MAX }, (_, i) => id(i)))).toBe(0);+ expect(messageIdErrors(Array.from({ length: MARK_READ_MESSAGE_IDS_MAX + 1 }, (_, i) => id(i)))).toBeGreaterThan(0);+ });++ it.each([[[' ']], [['']], [['has space']], [['ok', ' ']], [[123]], ['not-an-array']])(+ 'rejects a malformed entry: %j',+ messageIds => {+ expect(messageIdErrors(messageIds)).toBeGreaterThan(0);+ },+ );+});diff --git a/src/modules/session/dto/mark-chat-read.dto.ts b/src/modules/session/dto/mark-chat-read.dto.tsindex 4755a8d8e..d47648721 100644--- a/src/modules/session/dto/mark-chat-read.dto.ts+++ b/src/modules/session/dto/mark-chat-read.dto.ts@@ -1,5 +1,12 @@import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';-import { ArrayMaxSize, IsArray, IsNotEmpty, IsOptional, IsString, Matches } from 'class-validator';+import { ArrayMaxSize, ArrayNotEmpty, IsArray, IsNotEmpty, IsOptional, IsString, Matches } from 'class-validator';++/**+ * Ceiling on one request's receipt batch, so a single call cannot hand the engine an unbounded key+ * list to round-trip. A caller with more than this to acknowledge is catching up on history rather+ * than marking a conversation read.+ */+export const MARK_READ_MESSAGE_IDS_MAX = 100;export class MarkChatReadDto {@ApiProperty({@@ -24,14 +31,23 @@ export class MarkChatReadDto {'Callers that persist inbound message IDs should send them here. Ignored by whatsapp-web.js, ' +'whose own sendSeen is chat-level.',type: [String],+ // @ArrayMaxSize is runtime-only; @nestjs/swagger does not derive maxItems from it, so without+ // this the published schema advertises an unbounded array and a caller batching more than the+ // cap discovers the limit as a 400.+ maxItems: MARK_READ_MESSAGE_IDS_MAX,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)+ // An empty array asks for nothing to be acknowledged. Rejected rather than accepted, because the+ // engine reads a missing list as "the newest message" and the two must not collapse: a caller that+ // computed its unread set and got none back would otherwise acknowledge a message it never named.+ @ArrayNotEmpty()+ @ArrayMaxSize(MARK_READ_MESSAGE_IDS_MAX)@IsString({ each: true })@IsNotEmpty({ each: true })+ // Engine-neutral structural check: a message id is one non-whitespace token. @IsNotEmpty alone+ // accepts ' ', which would reach sendNode as a receipt key.+ @Matches(/^\S{1,128}$/, { each: true, message: 'each messageIds entry must be a non-empty id with no whitespace' })messageIds?: string[];}diff --git a/src/modules/session/dto/mark-chat-unread.dto.ts b/src/modules/session/dto/mark-chat-unread.dto.tsnew file mode 100644index 000000000..4d8ca6d69--- /dev/null+++ b/src/modules/session/dto/mark-chat-unread.dto.ts@@ -0,0 +1,22 @@+import { ApiProperty } from '@nestjs/swagger';+import { IsNotEmpty, IsString, Matches } from 'class-validator';++/**+ * Deliberately separate from {@link MarkChatReadDto}, which the unread route used to share. The read+ * route accepts `messageIds`; the unread route has nothing to do with them and ignores them, so+ * sharing the class published a field on `POST /chats/unread` that it silently discarded.+ */+export class MarkChatUnreadDto {+ @ApiProperty({+ description: "Chat ID in the active engine's native format (e.g. [email protected] on whatsapp-web.js)",+ example: '[email protected]',+ })+ @IsString()+ @IsNotEmpty()+ // Engine-neutral structural check (localpart@host, no whitespace) so a different engine's JID+ // scheme (e.g. Baileys [email protected]) is accepted too; the adapter normalises further.+ @Matches(/^[^\s@]+@[^\s@]+$/, {+ message: 'chatId must be a valid chat JID in the form localpart@host',+ })+ chatId!: string;+}diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex f0e62ee16..7f5b9aab0 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -21,6 +21,7 @@ import {SessionResponseDto,QRCodeResponseDto,MarkChatReadDto,+ MarkChatUnreadDto,SubscribePresenceDto,SetOwnPresenceDto,ChatPresenceResponseDto,@@ -572,7 +573,7 @@ export class SessionController {@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })async markChatUnread(@Param('sessionId', ParseUUIDPipe) id: string,- @Body() dto: MarkChatReadDto,+ @Body() dto: MarkChatUnreadDto,): Promise<{ success: boolean }> {const success = await this.sessionService.markUnread(id, dto.chatId);return { success };