Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): key chat writes so the phone applies them

Rezk Jörg Sebening904e93c71fc3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index df94bcee4..2e1b86cfd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -31,6 +31,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Refuse media exports and file counts when local directories cannot be fully enumerated.
- Normalize CRLF line endings in SDK contract parsers so Windows checkouts do not produce false contract mismatches (#1885).
- Exclude local repository metadata from Java SDK Maven Central bundles built with Maven 3.10 (#1879).
+- Index Baileys clear, delete, archive and unread changes by the same chat jid as their message key, and send an own group message's key without its participant, so the phone applies a clear or delete instead of ignoring it (#1891).
+- Key Baileys chat writes and read receipts to the gateway's stored newest message of a chat with no message since the session started, and archive or mark unread a chat with no known message at all; clear and delete still decline then (#1891).
## [0.25.0] - 2026-10-15
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index d0f8823c8..73948d756 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -986,7 +986,7 @@ Mark a chat as read/seen.
| `chatId` | string | Yes | `@IsString`; `@IsNotEmpty`; `@MaxLength(255)`; `@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 received 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 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.
+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 gets a receipt: the one the engine holds in memory, else, for a session restarted since it arrived, the newest received message the gateway stored. A burst therefore leaves its earlier messages unread. 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"] }
@@ -1001,8 +1001,8 @@ 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
-> 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
+> newest message the chat received, in memory or stored, so a chat with neither (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, but it still
> answers `success: false` for a chat the page cannot find or when the page declines the read.
@@ -1028,6 +1028,8 @@ Mark a chat as unread.
This route takes `chatId` alone. It previously shared `MarkChatReadDto`, which is why the two are described separately now that the read body carries `messageIds`.
+On Baileys the mark is keyed to the chat's newest message: the one held in memory, else the newest one the gateway stored. With neither it is sent without one, which WhatsApp applies to a chat in the list; for an archived chat the phone ignores that, so the route answers `success: false` there instead.
+
```json
{ "chatId": "[email protected]" }
```
@@ -1063,9 +1065,9 @@ Delete every message in a chat, keeping the chat itself in the list.
On success the gateway also removes its stored copies of the chat's messages (rows, inline and archived media, search entries) and emits `message:deleted` for each. Changes made on the phone are not mirrored.
-> **`success: false` is a real outcome**, as with `chats/archive`: an unknown chat on
-> whatsapp-web.js, or on Baileys a chat with no known history — the clear is an app-state
-> modification keyed to the chat's last message.
+> **`success: false` is a real outcome**: an unknown chat on whatsapp-web.js, or on Baileys a chat
+> with no message in memory or stored — the clear is an app-state modification keyed to the chat's
+> last message, and the gateway never guesses one.
**Errors:** `400` session not ready · `401` missing/invalid API key · `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
@@ -1098,10 +1100,10 @@ Archive or unarchive a chat.
{ "success": true }
```
-> **`success: false` is a real outcome here, not an error.** On the Baileys engine the archive is an
-> app-state modification keyed to the chat's **last message**, so a chat with no known history
-> cannot be archived at all — the same limitation `chats/delete` and `chats/unread` already carry on
-> that engine. Rather than fail with a 500, the endpoint reports `success: false`.
+> On the Baileys engine the archive is an app-state modification keyed to the chat's **last
+> message**: the one held in memory, else the newest one the gateway stored. A chat with neither,
+> one that had no traffic since the session started and none stored, is archived without one, which
+> WhatsApp applies as well.
> **No `chat.archived` webhook fires for your own archive.** Baileys emits no event for a change the
> account itself made (remote-device archives arrive later via chat-update diffing), and
@@ -1234,6 +1236,9 @@ Returns HTTP `200`, matching the OpenAPI contract.
On success the gateway also removes its stored copies of the chat's messages (rows, inline and archived media, search entries) and emits `message:deleted` for each. Changes made on the phone are not mirrored.
+> **`success: false` is a real outcome**, as with the clear: on Baileys the delete is keyed to the
+> chat's last message, in memory or stored, and a chat with neither is not deleted.
+
**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
#### POST /api/sessions/:sessionId/chats/typing
diff --git a/openapi.json b/openapi.json
index 860ec7985..3e33ba4f3 100644
--- a/openapi.json
+++ b/openapi.json
@@ -2103,7 +2103,7 @@
},
"responses": {
"200": {
- "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.",
+ "description": "Returns `{ success }`. `false` means the engine declined to act: the Baileys engine sends the read receipt against the newest message the chat received that it holds in memory, else the newest received one the gateway stored, so a chat with neither (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": {
@@ -2610,7 +2610,7 @@
],
"responses": {
"200": {
- "description": "Returns `{ success }`. `false` means the engine declined to act — an unknown chat, or on the Baileys engine a chat with no known history, since the change is keyed to its last message.",
+ "description": "Returns `{ success }`. `false` means the engine declined to act — an unknown chat, or on the Baileys engine a chat with no message in memory or stored, since the clear is keyed to its last message.",
"content": {
"application/json": {
"schema": {
@@ -2712,7 +2712,7 @@
},
"responses": {
"200": {
- "description": "Returns `{ success }`. `false` means the engine declined to act — on the Baileys engine a chat with no known history cannot be archived, since the change is keyed to its last message.",
+ "description": "Returns `{ success }`. `false` means the engine declined to act. The Baileys engine keys the change to the chat's newest message in memory, else the newest stored one, else sends it without one, which WhatsApp applies as well.",
"content": {
"application/json": {
"schema": {
diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.ts
index 45f685c05..b9fd09840 100644
--- a/src/engine/adapters/baileys-contacts.ts
+++ b/src/engine/adapters/baileys-contacts.ts
@@ -1,5 +1,10 @@
import type { WAMessage, WAMessageKey, WASocket } from '@whiskeysockets/baileys';
-import { ChatSummary, Contact, MediaInput } from '../interfaces/whatsapp-engine.interface';
+import {
+ ChatSummary,
+ Contact,
+ MediaInput,
+ type StoredChatMessageLookup,
+} from '../interfaces/whatsapp-engine.interface';
import { assertReadableImage, resolveMediaBuffer } from './baileys-messaging';
import { type createLogger } from '../../common/services/logger.service';
import { BAILEYS_QUERY_BUDGET_MS, withQueryDeadline } from './baileys-query-deadline';
@@ -39,6 +44,8 @@ export interface BaileysContactsHost {
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;
+ /** The `<lid>@lid` known for a 1:1 chat or a person under any spelling of it, or null (always for a group). */
+ lidOf(jid: string): string | 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`
@@ -370,9 +377,9 @@ export class BaileysContacts {
return this.host.listChats();
}
- async sendSeen(chatId: string, messageIds?: string[]): Promise<boolean> {
+ async sendSeen(chatId: string, messageIds?: string[], stored?: StoredChatMessageLookup): Promise<boolean> {
this.host.ensureReady();
- const keys = await this.receiptKeys(chatId, messageIds);
+ const keys = await this.receiptKeys(chatId, messageIds, stored);
if (keys.length === 0) {
return false; // nothing known to mark read
}
@@ -400,14 +407,22 @@ export class BaileysContacts {
* 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[]> {
+ private async receiptKeys(
+ chatId: string,
+ messageIds?: string[],
+ storedLast?: StoredChatMessageLookup,
+ ): Promise<WAMessageKey[]> {
// 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) {
// 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.
+ // After a restart memory holds none until the next one arrives; the gateway's stored copy
+ // stands in, rebuilt the way a chat write keys it.
const last = this.host.lastInboundMessage(chatId);
- return last ? [last.key] : [];
+ if (last) return [last.key];
+ const target = await this.storedTarget(chatId, storedLast, { receivedOnly: true });
+ return target ? [target.key] : [];
}
if (messageIds.length === 0) {
return []; // an explicit empty list asks for nothing to be acknowledged, not for the newest
@@ -433,48 +448,123 @@ export class BaileysContacts {
return messageIds.map(id => keyById.get(id) ?? { remoteJid, id, fromMe: false });
}
- async markUnread(chatId: string): Promise<boolean> {
- this.host.ensureReady();
+ /**
+ * The message a chat write is keyed to, and the jid that indexes the patch, made to agree (#1891).
+ *
+ * The phone applies a clear or delete only when both name the chat the way it holds it: a 1:1 chat
+ * by its `<lid>@lid` whenever one is known, else its phone jid, and a group by its id. A message
+ * keyed by its lid on a chat the session lists under the phone jid named two different chats, which
+ * the server accepted and the phone ignored. An own group message carries no `participant` (the
+ * phone ignores the range with one); a received one needs its sender, which Baileys requires.
+ *
+ * The message is the newest one this session holds in memory, else (none, or one that yields no
+ * usable key) the newest the gateway stored (`stored`), which is what a chat with no traffic since
+ * the session started has. Null when neither yields a usable key.
+ */
+ private async chatWriteRange(
+ chatId: string,
+ stored?: StoredChatMessageLookup,
+ ): Promise<{ jid: string; lastMessages: { key: WAMessageKey; messageTimestamp: number }[] } | null> {
const last = this.host.lastMessage(chatId);
- if (!last) {
- return false; // Baileys' unread toggle needs the last message; can't synthesize it
+ const target =
+ (last && this.toTarget(chatId, last.key, last.timestamp)) ??
+ (await this.storedTarget(chatId, stored, { receivedOnly: false }));
+ return target ? { jid: target.jid, lastMessages: [{ key: target.key, messageTimestamp: target.timestamp }] } : null;
+ }
+
+ /** The stored newest message of the chat as a key the chat writes can use, or null. */
+ private async storedTarget(
+ chatId: string,
+ stored: StoredChatMessageLookup | undefined,
+ { receivedOnly }: { receivedOnly: boolean },
+ ): Promise<{ jid: string; key: WAMessageKey; timestamp: number } | null> {
+ if (!stored) return null;
+ let row: Awaited<ReturnType<StoredChatMessageLookup>>;
+ try {
+ row = await stored();
+ } catch (err) {
+ this.host.logger.warn('Could not read the stored last message of a chat', {
+ chatId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ return null;
+ }
+ if (!row || (receivedOnly && row.fromMe)) return null;
+ return this.toTarget(
+ chatId,
+ { remoteJid: this.host.chatJid(chatId), fromMe: row.fromMe, id: row.id, participant: row.author },
+ row.timestamp,
+ );
+ }
+
+ /** Rebuild `key` for the chat as {@link chatWriteRange} describes; null when it cannot be used. */
+ private toTarget(
+ chatId: string,
+ key: WAMessageKey,
+ timestamp: number,
+ ): { jid: string; key: WAMessageKey; timestamp: number } | null {
+ if (!key.id || !timestamp) return null;
+ const chatJid = this.host.chatJid(chatId);
+ const group = parseWaId(chatJid).kind === 'group';
+ const fromMe = key.fromMe === true;
+ let jid = chatJid;
+ if (!group) {
+ const messageJid = key.remoteJid ?? chatJid;
+ jid = this.host.lidOf(messageJid) ?? this.host.lidOf(chatJid) ?? this.host.toEngineJid(messageJid);
+ }
+ let participant: string | undefined;
+ if (group && !fromMe) {
+ if (!key.participant) return null;
+ participant = this.host.lidOf(key.participant) ?? this.host.toEngineJid(key.participant);
}
+ return { jid, key: { remoteJid: jid, fromMe, id: key.id, ...(participant ? { participant } : {}) }, timestamp };
+ }
+
+ /** Whether the session lists the chat as archived. */
+ private isArchived(chatId: string): boolean {
+ const id = this.host.toNeutralJid(this.host.chatJid(chatId));
+ return this.host.listChats().some(chat => chat.id === id && chat.archived === true);
+ }
+
+ /**
+ * Without a known message the mark goes out with no range, which the phone applies to a chat in the
+ * list; an archived chat ignores it there, so that case is reported as not done.
+ */
+ async markUnread(chatId: string, stored?: StoredChatMessageLookup): Promise<boolean> {
+ this.host.ensureReady();
+ const range = await this.chatWriteRange(chatId, stored);
+ if (!range && this.isArchived(chatId)) return false;
await this.confirmed(
this.sock().chatModify(
- { markRead: false, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },
- last.jid,
+ { markRead: false, lastMessages: range?.lastMessages ?? [] },
+ range?.jid ?? this.host.chatJid(chatId),
),
'the unread mark',
);
return true;
}
- async clearChatMessages(chatId: string): Promise<boolean> {
+ async clearChatMessages(chatId: string, stored?: StoredChatMessageLookup): Promise<boolean> {
this.host.ensureReady();
- const last = this.host.lastMessage(chatId);
- if (!last) {
- return false; // Baileys' clear needs the last message; can't synthesize it
+ const range = await this.chatWriteRange(chatId, stored);
+ if (!range) {
+ return false; // the clear removes messages up to the one it is keyed to; never guess one
}
await this.confirmed(
- this.sock().chatModify(
- { clear: true, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },
- last.jid,
- ),
+ this.sock().chatModify({ clear: true, lastMessages: range.lastMessages }, range.jid),
'the chat clear',
);
return true;
}
- async archiveChat(chatId: string, archive: boolean): Promise<boolean> {
+ /** Without a known message the change goes out with no range, which WhatsApp applies as well. */
+ async archiveChat(chatId: string, archive: boolean, stored?: StoredChatMessageLookup): Promise<boolean> {
this.host.ensureReady();
- const last = this.host.lastMessage(chatId);
- if (!last) {
- return false; // Baileys' archive toggle needs the last message; can't synthesize it
- }
+ const range = await this.chatWriteRange(chatId, stored);
await this.confirmed(
this.sock().chatModify(
- { archive, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },
- last.jid,
+ { archive, lastMessages: range?.lastMessages ?? [] },
+ range?.jid ?? this.host.chatJid(chatId),
),
'the archive change',
);
@@ -498,17 +588,14 @@ export class BaileysContacts {
return true;
}
- async deleteChat(chatId: string): Promise<boolean> {
+ async deleteChat(chatId: string, stored?: StoredChatMessageLookup): Promise<boolean> {
this.host.ensureReady();
- const last = this.host.lastMessage(chatId);
- if (!last) {
- return false; // Baileys' delete needs the last message; can't synthesize it
+ const range = await this.chatWriteRange(chatId, stored);
+ if (!range) {
+ return false; // the delete removes messages up to the one it is keyed to; never guess one
}
await this.confirmed(
- this.sock().chatModify(
- { delete: true, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },
- last.jid,
- ),
+ this.sock().chatModify({ delete: true, lastMessages: range.lastMessages }, range.jid),
'the chat delete',
);
return true;
diff --git a/src/engine/adapters/baileys-remaining-writes.spec.ts b/src/engine/adapters/baileys-remaining-writes.spec.ts
index 2c954f814..f95e39cab 100644
--- a/src/engine/adapters/baileys-remaining-writes.spec.ts
+++ b/src/engine/adapters/baileys-remaining-writes.spec.ts
@@ -25,6 +25,8 @@ function contacts(sock: Record<string, jest.Mock>, budgetMs: number): BaileysCon
listChats: () => [],
lastMessage: () => LAST,
toEngineJid: (j: string) => j,
+ chatJid: (j: string) => j,
+ lidOf: () => null,
} as unknown as BaileysContactsHost;
return new BaileysContacts(host, budgetMs);
}
diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.ts
index 8a6436399..00abace64 100644
--- a/src/engine/adapters/baileys-session-store.ts
+++ b/src/engine/adapters/baileys-session-store.ts
@@ -471,6 +471,18 @@ export class BaileysSessionStore {
return twins.find(k => this.chats.has(k)) ?? twins.find(k => this.lastMessages.has(k)) ?? this.toEngineJid(jid);
}
+ /**
+ * The `<lid>@lid` this session knows for a 1:1 chat or a person, under any spelling of it, or null
+ * when none is known (and always for a group). WhatsApp keys a lid-migrated contact's chat by its lid.
+ */
+ lidOf(jid: string): string | null {
+ for (const twin of this.chatTwins(jid)) {
+ const parsed = parseWaId(twin);
+ if (parsed.kind === 'lid') return `${parsed.userPart}@lid`;
+ }
+ return null;
+ }
+
/** Every spelling of one chat this session can connect: the id, its engine form, and its lid or phone twin. */
private chatTwins(jid: string): string[] {
const parsed = parseWaId(jid);
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index a2c7ad6f6..d1427c182 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -171,6 +171,7 @@ import {
IncomingCallEvent,
IncomingMessage,
InboundOutcome,
+ StoredChatMessage,
} from '../interfaces/whatsapp-engine.interface';
import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';
@@ -6988,12 +6989,14 @@ describe('BaileysAdapter sendSeen + markUnread + deleteChat', () => {
);
});
- it('markUnread returns false when no last message is known', async () => {
+ // WhatsApp applies an unread mark with no range to a chat in the list (#1891), so a chat the session
+ // knows no message of is still marked.
+ it('markUnread marks a chat with no known message without a range', async () => {
const adapter = newAdapter();
await adapter.initialize({});
fakeSock.fire('connection.update', { connection: 'open' });
- expect(await adapter.markUnread('[email protected]')).toBe(false);
- expect(fakeSock.chatModify).not.toHaveBeenCalled();
+ expect(await adapter.markUnread('[email protected]')).toBe(true);
+ expect(fakeSock.chatModify).toHaveBeenCalledWith({ markRead: false, lastMessages: [] }, '[email protected]');
});
it('deleteChat revokes the chat via chatModify with the last message', async () => {
@@ -7210,14 +7213,13 @@ describe('BaileysAdapter sendSeen + markUnread + deleteChat', () => {
);
});
- it('archiveChat returns false for a chat with no known history, rather than throwing', async () => {
- // The app-state modification is keyed to the chat's last message; there is nothing to
- // synthesize one from, so this is a defined outcome the endpoint reports as success:false.
+ // WhatsApp applies an archive with no range (#1891), so a chat with no known message is archived too.
+ it('archiveChat archives a chat with no known message without a range', async () => {
const adapter = newAdapter();
await adapter.initialize({});
fakeSock.fire('connection.update', { connection: 'open' });
- expect(await adapter.archiveChat('[email protected]', true)).toBe(false);
- expect(fakeSock.chatModify).not.toHaveBeenCalled();
+ expect(await adapter.archiveChat('[email protected]', true)).toBe(true);
+ expect(fakeSock.chatModify).toHaveBeenCalledWith({ archive: true, lastMessages: [] }, '[email protected]');
});
/**
@@ -7292,6 +7294,194 @@ describe('BaileysAdapter sendSeen + markUnread + deleteChat', () => {
});
});
+// #1891: the phone applies a chat write only when the patch index and the range key name the chat the
+// way it holds it, and a chat with no traffic since the session started is keyed to the gateway's
+// stored copy of its newest message. Each case below was checked against a phone.
+describe('BaileysAdapter chat writes keyed to a message (#1891)', () => {
+ beforeEach(() => {
+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };
+ fakeSock.resetEmitter();
+ jest.clearAllMocks();
+ });
+
+ const ready = async (): Promise<BaileysAdapter> => {
+ const adapter = newAdapter();
+ await adapter.initialize({});
+ fakeSock.fire('connection.update', { connection: 'open' });
+ return adapter;
+ };
+ const upsert = async (key: Record<string, unknown>, messageTimestamp = 1700000020): Promise<void> => {
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [{ key, message: { conversation: 'hi' }, messageTimestamp }],
+ });
+ await new Promise(r => setImmediate(r));
+ };
+ const lookup = (row: StoredChatMessage | null) => jest.fn(() => Promise.resolve(row));
+
+ it.each([
+ ['clearChatMessages', (a: BaileysAdapter) => a.clearChatMessages('[email protected]')],
+ ['deleteChat', (a: BaileysAdapter) => a.deleteChat('[email protected]')],
+ ['markUnread', (a: BaileysAdapter) => a.markUnread('[email protected]')],
+ ['archiveChat', (a: BaileysAdapter) => a.archiveChat('[email protected]', true)],
+ ])('%s indexes a phone-keyed chat by the lid its message is keyed by', async (_n, act) => {
+ const adapter = await ready();
+ fakeSock.fire('lid-mapping.update', { lid: '484848@lid', pn: '[email protected]' });
+ fakeSock.fire('chats.upsert', [{ id: '[email protected]' }]);
+ await upsert({ remoteJid: '484848@lid', remoteJidAlt: '[email protected]', fromMe: false, id: 'M1' });
+
+ await expect(act(adapter)).resolves.toBe(true);
+ expect(fakeSock.chatModify).toHaveBeenCalledWith(
+ expect.objectContaining({
+ lastMessages: [{ key: { remoteJid: '484848@lid', fromMe: false, id: 'M1' }, messageTimestamp: 1700000020 }],
+ }),
+ '484848@lid',
+ );
+ });
+
+ it('keys an own group message without its participant, and a received one with its sender', async () => {
+ const adapter = await ready();
+ await upsert({ remoteJid: '[email protected]', fromMe: true, id: 'OWN', participant: '777@lid' });
+ await adapter.clearChatMessages('[email protected]');
+ expect(fakeSock.chatModify).toHaveBeenLastCalledWith(
+ {
+ clear: true,
+ lastMessages: [{ key: { remoteJid: '[email protected]', fromMe: true, id: 'OWN' }, messageTimestamp: 1700000020 }],
+ },
+ );
+
+ await upsert({ remoteJid: '[email protected]', fromMe: false, id: 'IN', participant: '555@lid' }, 1700000030);
+ await adapter.clearChatMessages('[email protected]');
+ expect(fakeSock.chatModify).toHaveBeenLastCalledWith(
+ {
+ clear: true,
+ lastMessages: [
+ {
+ key: { remoteJid: '[email protected]', fromMe: false, id: 'IN', participant: '555@lid' },
+ messageTimestamp: 1700000030,
+ },
+ ],
+ },
+ );
+ });
+
+ it('falls back to the stored message when the one in memory is a received group message without its sender', async () => {
+ const adapter = await ready();
+ await upsert({ remoteJid: '[email protected]', fromMe: false, id: 'ANON' });
+ await expect(
+ adapter.clearChatMessages('[email protected]', lookup({ id: 'S1', fromMe: true, timestamp: 1690000000 })),
+ ).resolves.toBe(true);
+ expect(fakeSock.chatModify).toHaveBeenCalledWith(
+ {
+ clear: true,
+ lastMessages: [{ key: { remoteJid: '[email protected]', fromMe: true, id: 'S1' }, messageTimestamp: 1690000000 }],
+ },
+ );
+ });
+
+ it('keys a chat with no message in memory to the stored one, and asks the store only then', async () => {
+ const adapter = await ready();
+ const stored = lookup({ id: 'S1', fromMe: false, timestamp: 1690000000 });
+ await expect(adapter.clearChatMessages('[email protected]', stored)).resolves.toBe(true);
+ expect(fakeSock.chatModify).toHaveBeenCalledWith(
+ {
+ clear: true,
+ lastMessages: [
+ { key: { remoteJid: '[email protected]', fromMe: false, id: 'S1' }, messageTimestamp: 1690000000 },
+ ],
+ },
+ );
+
+ await upsert({ remoteJid: '[email protected]', fromMe: false, id: 'M1' });
+ stored.mockClear();
+ await adapter.deleteChat('[email protected]', stored);
+ expect(stored).not.toHaveBeenCalled();
+ });
+
+ it('keys a stored message by the lid of a lid-migrated chat, and a stored group message by its sender', async () => {
+ const adapter = await ready();
+ fakeSock.fire('lid-mapping.update', { lid: '484848@lid', pn: '[email protected]' });
+ await adapter.deleteChat('[email protected]', lookup({ id: 'S1', fromMe: true, timestamp: 1690000000 }));
+ expect(fakeSock.chatModify).toHaveBeenLastCalledWith(
+ {
+ delete: true,
+ lastMessages: [{ key: { remoteJid: '484848@lid', fromMe: true, id: 'S1' }, messageTimestamp: 1690000000 }],
+ },
+ '484848@lid',
+ );
+
+ await adapter.markUnread(
+ lookup({ id: 'G1', fromMe: false, author: '[email protected]', timestamp: 1690000001 }),
+ );
+ expect(fakeSock.chatModify).toHaveBeenLastCalledWith(
+ {
+ markRead: false,
+ lastMessages: [
+ {
+ key: { remoteJid: '[email protected]', fromMe: false, id: 'G1', participant: '[email protected]' },
+ messageTimestamp: 1690000001,
+ },
+ ],
+ },
+ );
+ });
+
+ it.each([
+ ['nothing stored', () => lookup(null)],
+ ['a lookup that fails', () => jest.fn(() => Promise.reject(new Error('db down')))],
+ ])('with %s, clear and delete decline and archive goes out without a range', async (_n, make) => {
+ const adapter = await ready();
+ await expect(adapter.clearChatMessages('[email protected]', make())).resolves.toBe(false);
+ await expect(adapter.deleteChat('[email protected]', make())).resolves.toBe(false);
+ expect(fakeSock.chatModify).not.toHaveBeenCalled();
+
+ await expect(adapter.archiveChat('[email protected]', false, make())).resolves.toBe(true);
+ expect(fakeSock.chatModify).toHaveBeenCalledWith({ archive: false, lastMessages: [] }, '[email protected]');
+ });
+
+ it('marks an archived chat unread only with a known message, since the phone ignores it without one', async () => {
+ const adapter = await ready();
+ fakeSock.fire('chats.upsert', [{ id: '[email protected]', archived: true }]);
+ await expect(adapter.markUnread('[email protected]', lookup(null))).resolves.toBe(false);
+ expect(fakeSock.chatModify).not.toHaveBeenCalled();
+
+ await expect(
+ adapter.markUnread('[email protected]', lookup({ id: 'S1', fromMe: true, timestamp: 1690000000 })),
+ ).resolves.toBe(true);
+ expect(fakeSock.chatModify).toHaveBeenCalledWith(
+ {
+ markRead: false,
+ lastMessages: [
+ { key: { remoteJid: '[email protected]', fromMe: true, id: 'S1' }, messageTimestamp: 1690000000 },
+ ],
+ },
+ );
+ });
+
+ it('acknowledges the newest stored received message when memory holds none, never an own one', async () => {
+ const adapter = await ready();
+ await expect(
+ adapter.sendSeen('[email protected]', undefined, lookup({ id: 'S1', fromMe: false, timestamp: 1690000000 })),
+ ).resolves.toBe(true);
+ expect(fakeSock.readMessages).toHaveBeenCalledWith([
+ { remoteJid: '[email protected]', fromMe: false, id: 'S1' },
+ ]);
+
+ fakeSock.readMessages.mockClear();
+ await expect(
+ adapter.sendSeen('[email protected]', undefined, lookup({ id: 'S2', fromMe: true, timestamp: 1690000001 })),
+ ).resolves.toBe(false);
+ expect(fakeSock.readMessages).not.toHaveBeenCalled();
+ });
+});
+
describe('BaileysAdapter status posting', () => {
beforeEach(() => {
fakeSock.user = { id: '628999:[email protected]', name: 'Me' };
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 0bfe39f8f..a53d451ea 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -47,6 +47,7 @@ import {
StatusResult,
ChatSummary,
StatusPostOptions,
+ StoredChatMessageLookup,
} from '../interfaces/whatsapp-engine.interface';
import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';
import { EngineRefusedError } from '../../common/errors/engine-refused.error';
@@ -185,6 +186,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
listChats: () => this.sessionStore.listChats(),
lastMessage: chatId => this.sessionStore.lastMessage(chatId),
lastInboundMessage: chatId => this.sessionStore.lastInboundMessage(chatId),
+ lidOf: jid => this.sessionStore.lidOf(jid),
upsertContacts: records => this.sessionStore.upsertContacts(records),
upsertChats: records => this.sessionStore.upsertChats(records),
removeChats: ids => this.sessionStore.removeChats(ids),
@@ -544,16 +546,16 @@ export class BaileysAdapter implements IWhatsAppEngine {
return this.messaging.subscribeToPresence(chatId);
}
- async sendSeen(chatId: string, messageIds?: string[]): Promise<boolean> {
- return this.contacts.sendSeen(chatId, messageIds);
+ async sendSeen(chatId: string, messageIds?: string[], stored?: StoredChatMessageLookup): Promise<boolean> {
+ return this.contacts.sendSeen(chatId, messageIds, stored);
}
- async markUnread(chatId: string): Promise<boolean> {
- return this.contacts.markUnread(chatId);
+ async markUnread(chatId: string, stored?: StoredChatMessageLookup): Promise<boolean> {
+ return this.contacts.markUnread(chatId, stored);
}
- async deleteChat(chatId: string): Promise<boolean> {
- return this.contacts.deleteChat(chatId);
+ async deleteChat(chatId: string, stored?: StoredChatMessageLookup): Promise<boolean> {
+ return this.contacts.deleteChat(chatId, stored);
}
async muteChat(chatId: string, muteUntil: number | null): Promise<void> {
@@ -564,12 +566,12 @@ export class BaileysAdapter implements IWhatsAppEngine {
return this.contacts.pinChat(chatId, pin);
}
- async archiveChat(chatId: string, archive: boolean): Promise<boolean> {
- return this.contacts.archiveChat(chatId, archive);
+ async archiveChat(chatId: string, archive: boolean, stored?: StoredChatMessageLookup): Promise<boolean> {
+ return this.contacts.archiveChat(chatId, archive, stored);
}
- async clearChatMessages(chatId: string): Promise<boolean> {
- return this.contacts.clearChatMessages(chatId);
+ async clearChatMessages(chatId: string, stored?: StoredChatMessageLookup): Promise<boolean> {
+ return this.contacts.clearChatMessages(chatId, stored);
}
// ----- Gated: unsupported on Baileys (reasons inline) -----
diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.ts
index 8c98244d0..0fcd97bb1 100644
--- a/src/engine/engine-capability-matrix.ts
+++ b/src/engine/engine-capability-matrix.ts
@@ -111,7 +111,7 @@ export const CURATED_CAPABILITY_EXCEPTIONS: Record<string, MethodCapability> = {
wwjs: { status: 'supported' },
baileys: { status: 'supported' },
evidence:
- "wwjs Client.archiveChat(chatId)/unarchiveChat(chatId) → Promise<boolean> (index.d.ts:46,328) — the CLIENT methods, not Chat.archive(), which resolves void; baileys chatModify({archive,lastMessages}, jid) (Types/Chat.d.ts:63-66) needs the chat's last message, so a chat with no known history resolves false rather than throwing",
+ "wwjs Client.archiveChat(chatId)/unarchiveChat(chatId) → Promise<boolean> (index.d.ts:46,328) — the CLIENT methods, not Chat.archive(), which resolves void; baileys chatModify({archive,lastMessages}, jid) (Types/Chat.d.ts:63-66) keyed to the chat's last message in memory, else the newest stored one, else sent with an empty range, which WhatsApp applies as well",
},
getBlockedContacts: {
wwjs: { status: 'supported' },
@@ -123,7 +123,7 @@ export const CURATED_CAPABILITY_EXCEPTIONS: Record<string, MethodCapability> = {
wwjs: { status: 'supported' },
baileys: { status: 'supported' },
evidence:
- 'wwjs Chat.clearMessages() → boolean (index.d.ts:1896); the injected sendClearChat returns false for an unknown chat (Injected/Utils.js:1220); baileys chatModify({clear:true,lastMessages}, jid) (Types/Chat.d.ts:75-78) — same last-message requirement as archiveChat, so a chat with no known history resolves false',
+ "wwjs Chat.clearMessages() → boolean (index.d.ts:1896); the injected sendClearChat returns false for an unknown chat (Injected/Utils.js:1220); baileys chatModify({clear:true,lastMessages}, jid) (Types/Chat.d.ts:75-78) — keyed to the chat's last message in memory or stored, so a chat with neither resolves false",
},
createGroup: {
wwjs: { status: 'not-available', rootCause: 'library-limitation' },
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index d150b2764..1d36144e9 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -1572,31 +1572,64 @@ export interface CatalogCapability {
sendCatalog(chatId: string, body?: string): Promise<MessageResult>;
}
+/**
+ * The newest message the gateway stored for a chat (the `messages` table), in the shape an engine
+ * that keys chat writes to a message needs to rebuild that message's key.
+ */
+export interface StoredChatMessage {
+ /** The WhatsApp message id. */
+ id: string;
+ fromMe: boolean;
+ /** The sender of a group message that is not from me, as stored (neutral dialect); absent otherwise. */
+ author?: string;
+ /** Epoch seconds. */
+ timestamp: number;
+}
+
+/**
+ * Reads the newest stored message of the chat a write is for, across the chat's id forms. Engines
+ * call it only when they know no message of the chat themselves, so a lookup costs nothing when it is
+ * not needed; it resolves null when the gateway stored none.
+ */
+export type StoredChatMessageLookup = () => Promise<StoredChatMessage | null>;
+
/**
* Chat-list management: enumeration and per-chat flags (seen, unread, archive, pin, mute,
* clear). These operate on the chat itself; pinning a message INSIDE a chat is
* MessageOperationsCapability.pinMessage.
+ *
+ * Baileys keys sendSeen, markUnread, archiveChat, clearChatMessages and deleteChat to a message of the
+ * chat, and holds the chat's messages only in memory since its session started. `stored` is the
+ * gateway's fallback for a chat with no message since then; whatsapp-web.js needs none and ignores it.
*/
export interface ChatCapability {
getChats(): Promise<ChatSummary[]>;
/**
* `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.
+ * message (Baileys) need it to mark a burst; without it they acknowledge the newest received
+ * message they know, else the newest received one `stored` finds. Engines with a chat-level
+ * receipt (whatsapp-web.js) ignore both.
*/
- sendSeen(chatId: string, messageIds?: string[]): Promise<boolean>;
+ sendSeen(chatId: string, messageIds?: string[], stored?: StoredChatMessageLookup): Promise<boolean>;
- markUnread(chatId: string): Promise<boolean>;
+ /**
+ * Resolves false when the engine cannot act. On Baileys an archived chat needs a known message to
+ * key the mark to; a chat that is not archived is marked without one.
+ */
+ markUnread(chatId: string, stored?: StoredChatMessageLookup): Promise<boolean>;
- deleteChat(chatId: string): Promise<boolean>;
+ /**
+ * Resolves false when the engine cannot act — on Baileys a chat with no known message at all, since
+ * the delete removes the messages up to the one it is keyed to and guessing that is not safe.
+ */
+ deleteChat(chatId: string, stored?: StoredChatMessageLookup): Promise<boolean>;
/**
- * Archive or unarchive a chat. Resolves false when the engine cannot act — on Baileys the
- * archive is an app-state modification keyed to the chat's last message, so a chat with no known
- * history cannot be archived at all. Same shape as deleteChat/markUnread, which share that limit.
+ * Archive or unarchive a chat. Baileys keys the change to a known message of the chat and sends it
+ * without one when none is known, which WhatsApp applies as well.
*/
- archiveChat(chatId: string, archive: boolean): Promise<boolean>;
+ archiveChat(chatId: string, archive: boolean, stored?: StoredChatMessageLookup): Promise<boolean>;
/**
* Pin or unpin a chat at the top of the chat list. Chat-level — distinct from `pinMessage`, which
@@ -1623,18 +1656,18 @@ export interface ChatCapability {
* Getting this backwards is silent — the send still answers 200 and the mute simply never applies,
* or lands tens of thousands of years out and reads as permanent.
*
- * Unlike archiveChat/clearChatMessages/deleteChat this has no "engine declined" outcome: the
- * Baileys `mute` app-state modification carries no `lastMessages`, so a chat with no known
- * history mutes like any other. That is why it resolves void rather than boolean.
+ * Unlike clearChatMessages/deleteChat this has no "engine declined" outcome: the Baileys `mute`
+ * app-state modification carries no `lastMessages`, so a chat with no known history mutes like
+ * any other. That is why it resolves void rather than boolean.
*/
muteChat(chatId: string, muteUntil: number | null): Promise<void>;
/**
* Delete every message in a chat while keeping the chat itself in the list. Resolves false when
- * the engine cannot act — an unknown chat on whatsapp-web.js, or (as with archiveChat) a chat
- * with no known history on Baileys, whose clear is keyed to the last message.
+ * the engine cannot act — an unknown chat on whatsapp-web.js, or (as with deleteChat) a chat with
+ * no known message at all on Baileys, whose clear is keyed to the last message.
*/
- clearChatMessages(chatId: string): Promise<boolean>;
+ clearChatMessages(chatId: string, stored?: StoredChatMessageLookup): Promise<boolean>;
}
/**
diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.ts
index 17147cb23..d819b9f50 100644
--- a/src/modules/session/session.controller.ts
+++ b/src/modules/session/session.controller.ts
@@ -603,10 +603,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 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.',
+ 'read receipt against the newest message the chat received that it holds in memory, else the ' +
+ 'newest received one the gateway stored, so a chat with neither (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' })
@@ -780,7 +780,8 @@ export class SessionController {
status: 200,
description:
'Returns `{ success }`. `false` means the engine declined to act — an unknown chat, or on the ' +
- 'Baileys engine a chat with no known history, since the change is keyed to its last message.',
+ 'Baileys engine a chat with no message in memory or stored, since the clear is keyed to its ' +
+ 'last message.',
type: SessionActionResponseDto,
})
@ApiResponse({ status: 400, description: 'Session not ready' })
@@ -809,8 +810,9 @@ export class SessionController {
@ApiResponse({
status: 200,
description:
- 'Returns `{ success }`. `false` means the engine declined to act — on the Baileys engine a ' +
- 'chat with no known history cannot be archived, since the change is keyed to its last message.',
+ 'Returns `{ success }`. `false` means the engine declined to act. The Baileys engine keys the ' +
+ "change to the chat's newest message in memory, else the newest stored one, else sends it " +
+ 'without one, which WhatsApp applies as well.',
type: SessionActionResponseDto,
})
@ApiResponse({ status: 400, description: 'Session not ready' })
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index a5aa348e4..2d8caffd0 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -71,6 +71,7 @@ import {
GroupEvent,
IncomingCallEvent,
InboundTicket,
+ StoredChatMessageLookup,
} from '../../engine/interfaces/whatsapp-engine.interface';
import { BaileysSessionStore } from '../../engine/adapters/baileys-session-store';
import {
@@ -8045,8 +8046,8 @@ describe('SessionService', () => {
const result = await service.sendSeen('sess-uuid-1', '[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);
+ // newest message it still holds, else to the stored lookup it is handed.
+ expect(mockEngine.sendSeen).toHaveBeenCalledWith('[email protected]', undefined, expect.any(Function));
expect(result).toBe(true);
});
@@ -8060,7 +8061,7 @@ describe('SessionService', () => {
await service.sendSeen('sess-uuid-1', '[email protected]', ['M1', 'M2']);
- expect(mockEngine.sendSeen).toHaveBeenCalledWith('[email protected]', ['M1', 'M2']);
+ expect(mockEngine.sendSeen).toHaveBeenCalledWith('[email protected]', ['M1', 'M2'], expect.any(Function));
});
it('should throw BadRequestException when session is not started', async () => {
@@ -8084,7 +8085,7 @@ describe('SessionService', () => {
const result = await service.markUnread('sess-uuid-1', '[email protected]');
- expect(mockEngine.markUnread).toHaveBeenCalledWith('[email protected]');
+ expect(mockEngine.markUnread).toHaveBeenCalledWith('[email protected]', expect.any(Function));
expect(result).toBe(true);
});
@@ -8124,7 +8125,7 @@ describe('SessionService', () => {
const result = await service.deleteChat('sess-uuid-1', '[email protected]');
- expect(mockEngine.deleteChat).toHaveBeenCalledWith('[email protected]');
+ expect(mockEngine.deleteChat).toHaveBeenCalledWith('[email protected]', expect.any(Function));
expect(result).toBe(true);
});
@@ -8278,6 +8279,35 @@ describe('SessionService', () => {
expect(deletedHooks()).toHaveLength(0);
});
+ // #1891: the engine can key a write to the stored newest message, and still decline or fail.
+ it.each([
+ ['clearChatMessages', 'declines', (id: string, chat: string) => service.clearChatMessages(id, chat)],
+ ['deleteChat', 'fails', (id: string, chat: string) => service.deleteChat(id, chat)],
+ ] as const)(
+ '%s keeps the stored rows when the engine read the stored message and then %s',
+ async (method, outcome, run) => {
+ (messageRepository.findOne as jest.Mock).mockResolvedValueOnce({
+ waMessageId: 'S1',
+ direction: MessageDirection.INCOMING,
+ timestamp: 1690000000,
+ });
+ mockEngine[method].mockImplementationOnce(async (_chat: string, stored?: StoredChatMessageLookup) => {
+ await stored?.();
+ if (outcome === 'fails') throw new Error('timed out');
+ return false;
+ });
+
+ const call = run('sess-uuid-1', '[email protected]');
+ if (outcome === 'fails') await expect(call).rejects.toThrow('timed out');
+ else await expect(call).resolves.toBe(false);
+
+ expect(messageRepository.findOne).toHaveBeenCalled();
+ expect(messageRepository.find).not.toHaveBeenCalled();
+ expect(messageRepository.delete).not.toHaveBeenCalled();
+ expect(deletedHooks()).toHaveLength(0);
+ },
+ );
+
it('a failed removal after the engine succeeded is logged and the call still succeeds', async () => {
(messageRepository.find as jest.Mock).mockRejectedValueOnce(new Error('db down'));
const logError = jest.spyOn((service as unknown as { logger: { error: jest.Mock } }).logger, 'error');
@@ -8292,6 +8322,90 @@ describe('SessionService', () => {
});
});
+ // ── the stored newest message a chat write falls back to (#1891) ──
+
+ describe('stored last message lookup', () => {
+ beforeEach(async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ await service.start('sess-uuid-1');
+ });
+
+ /** The lookup the service handed the engine for `run`, called once. */
+ const lookupOf = async (
+ method: 'markUnread' | 'clearChatMessages' | 'deleteChat' | 'sendSeen',
+ run: () => Promise<unknown>,
+ ): Promise<unknown> => {
+ mockEngine[method].mockResolvedValueOnce(false);
+ await run();
+ const calls = mockEngine[method].mock.calls as unknown[][];
+ const lookup = calls[calls.length - 1].find(arg => typeof arg === 'function') as StoredChatMessageLookup;
+ return lookup();
+ };
+ const whereOf = (): unknown =>
+ ((messageRepository.findOne as jest.Mock).mock.calls as [{ where: unknown }][])[0][0].where;
+
+ it("reads a 1:1 chat's newest stored message under every id form of it", async () => {
+ (lidMappingStore.findLidsForPhone as jest.Mock).mockResolvedValue(['999']);
+ (messageRepository.findOne as jest.Mock).mockResolvedValueOnce({
+ waMessageId: 'S1',
+ direction: MessageDirection.OUTGOING,
+ author: null,
+ timestamp: 1690000000,
+ });
+
+ await expect(lookupOf('markUnread', () => service.markUnread('sess-uuid-1', '[email protected]'))).resolves.toEqual({
+ id: 'S1',
+ fromMe: true,
+ timestamp: 1690000000,
+ });
+ const base = {
+ sessionId: 'sess-uuid-1',
+ chatId: In(['[email protected]', '[email protected]', '999@lid']),
+ waMessageId: Not(IsNull()),
+ timestamp: Not(IsNull()),
+ };
+ expect(whereOf()).toEqual([base]);
+ expect(messageRepository.findOne).toHaveBeenCalledWith(
+ expect.objectContaining({ order: { timestamp: 'DESC', createdAt: 'DESC' } }),
+ );
+ });
+
+ it('in a group, takes an own message or a received one with its sender', async () => {
+ (messageRepository.findOne as jest.Mock).mockResolvedValueOnce({
+ waMessageId: 'G1',
+ direction: MessageDirection.INCOMING,
+ author: '[email protected]',
+ timestamp: 1690000001,
+ });
+
+ await expect(
+ lookupOf('clearChatMessages', () => service.clearChatMessages('sess-uuid-1', '[email protected]')),
+ ).resolves.toEqual({ id: 'G1', fromMe: false, author: '[email protected]', timestamp: 1690000001 });
+ const base = {
+ sessionId: 'sess-uuid-1',
+ chatId: In(['[email protected]']),
+ waMessageId: Not(IsNull()),
+ timestamp: Not(IsNull()),
+ };
+ expect(whereOf()).toEqual([
+ { ...base, direction: MessageDirection.INCOMING, author: Not(IsNull()) },
+ { ...base, direction: MessageDirection.OUTGOING },
+ ]);
+ });
+
+ it('for a read receipt, takes only a received message', async () => {
+ await expect(lookupOf('sendSeen', () => service.sendSeen('sess-uuid-1', '[email protected]'))).resolves.toBeNull();
+ expect(whereOf()).toEqual([expect.objectContaining({ direction: MessageDirection.INCOMING })]);
+ });
+
+ it('is not read until the engine asks for it', async () => {
+ mockEngine.deleteChat.mockResolvedValueOnce(false);
+ await service.deleteChat('sess-uuid-1', '[email protected]');
+ expect(messageRepository.findOne).not.toHaveBeenCalled();
+ });
+ });
+
// ── sendChatState (typing/recording/paused) ───────────────────────
describe('sendChatState', () => {
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index ad82a3a36..4450d7282 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -51,13 +51,19 @@ import { SessionOwnershipService } from './session-ownership.service';
import { paginate, ListOptions, resolveListWindow } from '../../common/utils/paginate';
import { isTransientDbError, isUniqueViolation } from '../../common/utils/db-errors';
import { resolveFeatureFlags } from '../../config/feature-flags';
-import { IWhatsAppEngine, ChatSummary, ChatState } from '../../engine/interfaces/whatsapp-engine.interface';
+import {
+ IWhatsAppEngine,
+ ChatSummary,
+ ChatState,
+ type StoredChatMessageLookup,
+} from '../../engine/interfaces/whatsapp-engine.interface';
import { createLogger } from '../../common/services/logger.service';
import { ShutdownService } from '../../common/services/shutdown.service';
import { HookManager } from '../../core/hooks';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
import { resolveJidCandidates } from '../../engine/identity/jid-candidates';
-import { Message } from '../message/entities/message.entity';
+import { parseWaId } from '../../engine/identity/wa-id';
+import { Message, MessageDirection } from '../message/entities/message.entity';
import { ServerShuttingDownException, SessionStoppedException } from './session-engine-controls';
// Type-only: the module binds this class to PLUGIN_SESSION_PORT with a `useExisting` alias, which
// TypeScript does not check, so `implements` is what keeps the two in step.
@@ -1119,41 +1125,88 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
await this.findOne(id); // Verify session exists
const engine = this.requireEngine(id);
- return engine.sendSeen(chatId, messageIds);
+ return engine.sendSeen(chatId, messageIds, this.storedLastMessage(id, chatId, { receivedOnly: true }));
}
async markUnread(id: string, chatId: string): Promise<boolean> {
await this.findOne(id); // Verify session exists
const engine = this.requireEngine(id);
- return engine.markUnread(chatId);
+ return engine.markUnread(chatId, this.storedLastMessage(id, chatId));
+ }
+
+ /**
+ * The newest message the gateway stored for a chat, for an engine that keys chat writes to one and
+ * holds none for the chat itself (Baileys after a restart, #1891). The lookup runs only when the
+ * engine calls it, and covers every id form of the chat (the GET messages filter's rules).
+ *
+ * A received group message counts only with its sender, which the key needs; `receivedOnly` asks
+ * for the newest received message, the one a read receipt acknowledges.
+ */
+ private storedLastMessage(
+ sessionId: string,
+ chatId: string,
+ { receivedOnly = false }: { receivedOnly?: boolean } = {},
+ ): StoredChatMessageLookup {
+ return async () => {
+ const expanded = await resolveJidCandidates(chatId, {
+ resolveLid: lid => this.lidMappingStore.findPhoneForLid(lid),
+ lidsForPhone: phone => this.lidMappingStore.findLidsForPhone(phone),
+ });
+ const base = {
+ sessionId,
+ chatId: In([...new Set([chatId, ...expanded])]),
+ waMessageId: Not(IsNull()),
+ timestamp: Not(IsNull()),
+ };
+ const received = { ...base, direction: MessageDirection.INCOMING };
+ const where: FindOptionsWhere<Message>[] =
+ parseWaId(chatId).kind === 'group'
+ ? [
+ { ...received, author: Not(IsNull()) },
+ ...(receivedOnly ? [] : [{ ...base, direction: MessageDirection.OUTGOING }]),
+ ]
+ : [receivedOnly ? received : base];
+ const row = await this.messageRepository.findOne({
+ where,
+ order: { timestamp: 'DESC', createdAt: 'DESC' },
+ select: { id: true, waMessageId: true, direction: true, author: true, timestamp: true },
+ });
+ if (!row) return null;
+ return {
+ id: row.waMessageId,
+ fromMe: row.direction === MessageDirection.OUTGOING,
+ ...(row.author ? { author: row.author } : {}),
+ timestamp: row.timestamp,
+ };
+ };
}
/**
* Delete every message in a chat, keeping the chat itself. Resolves false when the engine could
- * not act — an unknown chat, or on Baileys a chat with no known history to key the change to.
- * On success the gateway's stored copies of the chat's messages are removed too.
+ * not act — an unknown chat, or on Baileys a chat with no message in memory or stored to key the
+ * change to. On success the gateway's stored copies of the chat's messages are removed too.
*/
async clearChatMessages(id: string, chatId: string): Promise<boolean> {
await this.findOne(id); // Verify session exists
const engine = this.requireEngine(id);
const cutoff = new Date();
- const ok = await engine.clearChatMessages(chatId);
+ const ok = await engine.clearChatMessages(chatId, this.storedLastMessage(id, chatId));
if (ok) await this.purgeStoredChat(id, chatId, cutoff);
return ok;
}
/**
- * Archive or unarchive a chat. Resolves false when the engine could not act — on Baileys a chat
- * with no known history has no last message to key the app-state modification to. That is a
- * defined outcome, not an error, so it is reported as `success: false` rather than a 500.
+ * Archive or unarchive a chat. Resolves false when the engine could not act. Baileys keys the
+ * change to the chat's newest message in memory, else the newest stored one, else sends it
+ * without one, which WhatsApp applies too.
*/
async archiveChat(id: string, chatId: string, archive: boolean): Promise<boolean> {
await this.findOne(id); // Verify session exists
const engine = this.requireEngine(id);
- return engine.archiveChat(chatId, archive);
+ return engine.archiveChat(chatId, archive, this.storedLastMessage(id, chatId));
}
/**
@@ -1185,7 +1238,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
const engine = this.requireEngine(id);
const cutoff = new Date();
- const ok = await engine.deleteChat(chatId);
+ const ok = await engine.deleteChat(chatId, this.storedLastMessage(id, chatId));
if (ok) await this.purgeStoredChat(id, chatId, cutoff);
return ok;
}