Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): send rangeless chat writes only for known chats

Rezk Jörg Sebeningb04e9f7ca5ad
diff --git a/CHANGELOG.md b/CHANGELOG.md
index faf29a06d..9aebba6d8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -81,7 +81,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Serialize a plugin upload with an uninstall or update of the same plugin id.
- Show hours for a session active within the last day on the Sessions page, as the Dashboard does.
- 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). Thanks @rjsebening.
-- 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). Thanks @rjsebening.
+- 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 known chat with no message at all, while an unknown id still answers `false`; clear and delete still decline then (#1891). Thanks @rjsebening.
- List a whatsapp-web.js contact held under both its LID and its phone once in the contacts and blocked lists, with the phone as `number`, instead of twice with the LID's digits.
## [0.25.0] - 2026-10-15
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 985a5be11..bf2a204ac 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1028,7 +1028,7 @@ 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.
+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. The route answers `success: false` instead for an archived chat, which the phone leaves unmarked without one, and for an id the session knows no chat for.
```json
{ "chatId": "[email protected]" }
@@ -1103,7 +1103,9 @@ Archive or unarchive a chat.
> 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.
+> WhatsApp applies as well. An id the session knows no chat for (no chat record, persisted state or
+> stored message) answers `success: false`: Baileys replays its own change locally, so archiving it
+> would list a chat the account does not have.
> **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
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index e10b986fe..3dff81d45 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -243,8 +243,9 @@ curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/chats/read
-d '{ "chatId": "[email protected]", "messageIds": ["3EB0C767D26B8A3F1A2B"] }'
```
-`messageIds` is optional and holds up to 100 ids. Omit it and only the newest received message the engine
-still holds in memory is acknowledged, which on Baileys leaves the earlier messages of a burst unread.
+`messageIds` is optional and holds up to 100 ids. Omit it and only the newest received message is
+acknowledged: the one the engine holds in memory, else, on Baileys after a restart, the newest received
+message the gateway stored. On Baileys that leaves the earlier messages of a burst unread.
#### POST /api/sessions/:sessionId/chats/unread
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
index 5435afdc8..d31c61a3a 100644
--- a/docs/29-engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@ -967,12 +967,19 @@ adapter boundary — none silently stubs.
credentials and the session returning to `qr_ready`. Baileys writes only its own credentials and
showed no such effect. Link by QR when the session of that number must stay up.
- **`archiveChat` / `clearChatMessages` / `deleteChat` / `sendSeen` / `markUnread` (baileys).** The
- four `chatModify` actions (archive, clear, delete, unread) need the chat's last known message, which
- the patch carries. `sendSeen` without message ids is `readMessages([key])` for the newest _received_
- (not `fromMe`) message, since Baileys drops own keys from a receipt. A chat with no such message
- resolves `false` rather than throwing, so a chat the session has seen no message in, or one holding
- only this account's own sends, answers `POST chats/read` with `{"success": false}`, where
- whatsapp-web.js marks it read from the page-side chat object without needing any local history.
+ four `chatModify` actions (archive, clear, delete, unread) are keyed to the chat's newest message:
+ the one the session holds in memory, else the newest one the gateway stored (#1891). The patch is
+ indexed by the same jid as that message's key: a message in memory under the jid it arrived with,
+ a stored one under the chat's lid when the persisted mapping holds one, else its phone jid; an own
+ group message goes without its participant. With no message at all, clear and delete resolve
+ `false`, and archive and unread are sent without a range for a chat the session knows (a chat
+ record, a persisted state row or a stored message) and resolve `false` otherwise; unread also
+ resolves `false` for an archived chat, which the phone leaves unmarked without a range. `sendSeen`
+ without message ids is `readMessages([key])` for the newest _received_ (not `fromMe`) message, in
+ memory or stored, since Baileys drops own keys from a receipt. A chat with no such message resolves
+ `false`, so one holding only this account's own sends answers `POST chats/read` with
+ `{"success": false}`, where whatsapp-web.js marks it read from the page-side chat object without
+ needing any local history.
- **`setProfileName` / `setProfilePicture` / `deleteProfilePicture` refusals (baileys).**
whatsapp-web.js reads a page-side verdict for all three (`setDisplayName` and `setProfilePicture`
resolve `false`, `deleteProfilePicture` resolves an explicit `false`) and raises a `403`. The
diff --git a/openapi.json b/openapi.json
index a64954881..b4f8b7e44 100644
--- a/openapi.json
+++ b/openapi.json
@@ -2719,7 +2719,7 @@
},
"responses": {
"200": {
- "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.",
+ "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, for a chat the session knows; an id it knows no chat for answers `false`.",
"content": {
"application/json": {
"schema": {
diff --git a/sdk/go/types_chat.go b/sdk/go/types_chat.go
index 35801fe51..dea83424b 100644
--- a/sdk/go/types_chat.go
+++ b/sdk/go/types_chat.go
@@ -41,9 +41,9 @@ type SubscribePresenceRequest struct {
type MarkChatReadRequest struct {
ChatID string `json:"chatId"`
// MessageIDs are the messages to acknowledge (at most 100; an empty list is refused). Baileys
- // acknowledges individual messages, so without this only the newest received message the
- // engine still holds in memory gets a receipt. Ignored by whatsapp-web.js, whose own sendSeen
- // is chat-level.
+ // acknowledges individual messages, so without this only the newest received message gets a
+ // receipt: the one the engine holds in memory, else the newest received one the gateway
+ // stored. Ignored by whatsapp-web.js, whose own sendSeen is chat-level.
//
// A POINTER because the three states differ on the wire and a plain slice cannot tell two of
// them apart: nil omits the key (acknowledge the newest), &[]string{} sends [] (the server
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/MarkChatReadRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/MarkChatReadRequest.java
index f6a9ff890..cffeacdc6 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/MarkChatReadRequest.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/MarkChatReadRequest.java
@@ -20,9 +20,9 @@ public record MarkChatReadRequest(String chatId, List<String> messageIds) {
/**
* Messages to acknowledge (at most 100; an empty list is refused). Baileys acknowledges
- * individual messages, so without this only the newest received message the engine still
- * holds in memory gets a receipt. Ignored by whatsapp-web.js, whose own sendSeen is
- * chat-level.
+ * individual messages, so without this only the newest received message gets a receipt:
+ * the one the engine holds in memory, else the newest received one the gateway stored.
+ * Ignored by whatsapp-web.js, whose own sendSeen is chat-level.
*/
public Builder messageIds(List<String> v) {
this.messageIds = v;
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index d5ad3705d..90cc8f1b6 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -1152,9 +1152,8 @@ export interface SubscribePresenceRequest {
export interface MarkChatReadRequest extends MarkChatRequest {
/**
* Specific message IDs to acknowledge. Baileys acknowledges individual messages, so without this
- * only the newest received message the engine still holds in memory gets a receipt: a burst
- * leaves its earlier messages unread forever, and a restarted session has no message to
- * acknowledge at all.
+ * only the newest received message gets a receipt (the one the engine holds in memory, else the
+ * newest received one the gateway stored): a burst leaves its earlier messages unread forever.
* Callers that persist inbound message IDs should send them here. Ignored by whatsapp-web.js,
* whose own sendSeen is chat-level. At most 100 per request; an empty array is rejected.
*/
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index fc3c5a0b3..c0a28e108 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -1074,9 +1074,9 @@ class MarkChatReadRequest(TypedDict):
# Body for mark_read.
chatId: Jid
# Messages to acknowledge (at most 100; an empty list is refused). Baileys acknowledges
- # individual messages, so without this only the newest received message the engine still
- # holds in memory gets a receipt. Ignored by whatsapp-web.js, whose own sendSeen is
- # chat-level.
+ # individual messages, so without this only the newest received message gets a receipt:
+ # the one the engine holds in memory, else the newest received one the gateway stored.
+ # Ignored by whatsapp-web.js, whose own sendSeen is chat-level.
messageIds: NotRequired[list[str]]
diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.ts
index 2b5ad454b..8e57ea93e 100644
--- a/src/engine/adapters/baileys-contacts.ts
+++ b/src/engine/adapters/baileys-contacts.ts
@@ -3,6 +3,7 @@ import {
ChatSummary,
Contact,
MediaInput,
+ type StoredChatMessage,
type StoredChatMessageLookup,
} from '../interfaces/whatsapp-engine.interface';
import { assertReadableImage, resolveMediaBuffer } from './baileys-messaging';
@@ -421,8 +422,9 @@ export class BaileysContacts {
// stands in, rebuilt the way a chat write keys it.
const last = this.host.lastInboundMessage(chatId);
if (last) return [last.key];
- const target = await this.storedTarget(chatId, storedLast, { receivedOnly: true });
- return target ? [target.key] : [];
+ const row = await this.readStored(chatId, storedLast);
+ const received = row && !row.fromMe ? this.storedTarget(chatId, row) : null;
+ return received ? [received.key] : [];
}
if (messageIds.length === 0) {
return []; // an explicit empty list asks for nothing to be acknowledged, not for the newest
@@ -451,37 +453,42 @@ export class BaileysContacts {
/**
* 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 phone applies a clear or delete only when both name the chat the way it holds it. A message
+ * this session holds in memory carries that form itself: the patch is indexed by the jid the
+ * message arrived under, its lid on a lid-addressed chat and its phone jid otherwise. Indexing it by
+ * the listed phone jid instead named two different chats, which the server accepted and the phone
+ * ignored. A stored message carries no addressing, so it is keyed by the chat's lid whenever one is
+ * known (the stored row brings the one the persisted mapping holds), else by the phone jid.
*
- * 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.
+ * 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 in memory, else (none, or one that yields no usable key) the newest
+ * the gateway stored. `known` tells whether the session knows the chat at all: a message in memory or
+ * stored, or a chat record or state row the listing holds.
*/
private async chatWriteRange(
chatId: string,
stored?: StoredChatMessageLookup,
- ): Promise<{ jid: string; lastMessages: { key: WAMessageKey; messageTimestamp: number }[] } | null> {
+ ): Promise<{ range: ChatWriteRange | null; known: boolean }> {
const last = this.host.lastMessage(chatId);
- 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;
+ const inMemory = last ? this.memoryTarget(chatId, last.key, last.timestamp) : null;
+ if (inMemory) return { range: toRange(inMemory), known: true };
+ const row = await this.readStored(chatId, stored);
+ const fromStore = row ? this.storedTarget(chatId, row) : null;
+ return {
+ range: fromStore ? toRange(fromStore) : null,
+ known: Boolean(last || row) || this.listedChat(chatId) !== undefined,
+ };
}
- /** The stored newest message of the chat as a key the chat writes can use, or null. */
- private async storedTarget(
+ private async readStored(
chatId: string,
stored: StoredChatMessageLookup | undefined,
- { receivedOnly }: { receivedOnly: boolean },
- ): Promise<{ jid: string; key: WAMessageKey; timestamp: number } | null> {
+ ): Promise<StoredChatMessage | null> {
if (!stored) return null;
- let row: Awaited<ReturnType<StoredChatMessageLookup>>;
try {
- row = await stored();
+ return await stored();
} catch (err) {
this.host.logger.warn('Could not read the stored last message of a chat', {
chatId,
@@ -489,51 +496,48 @@ export class BaileysContacts {
});
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 {
+ /** A message held in memory, keyed under the jid it arrived with; null when it cannot be used. */
+ private memoryTarget(chatId: string, key: WAMessageKey, timestamp: number): WriteTarget | 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 };
+ if (group && !fromMe && !key.participant) return null;
+ const jid = group ? chatJid : this.host.toEngineJid(key.remoteJid ?? chatJid);
+ return target(jid, key.id, fromMe, group && !fromMe ? (key.participant ?? undefined) : undefined, timestamp);
}
- /** Whether the session lists the chat as archived. */
- private isArchived(chatId: string): boolean {
+ /** A stored message, keyed by the chat's lid whenever one is known; null when it cannot be used. */
+ private storedTarget(chatId: string, row: StoredChatMessage): WriteTarget | null {
+ if (!row.id || !row.timestamp) return null;
+ const chatJid = this.host.chatJid(chatId);
+ const group = parseWaId(chatJid).kind === 'group';
+ if (group && !row.fromMe && !row.author) return null;
+ const jid = group ? chatJid : (row.lid ?? this.host.lidOf(chatJid) ?? this.host.toEngineJid(chatJid));
+ const participant =
+ group && !row.fromMe && row.author
+ ? (row.authorLid ?? this.host.lidOf(row.author) ?? this.host.toEngineJid(row.author))
+ : undefined;
+ return target(jid, row.id, row.fromMe, participant, row.timestamp);
+ }
+
+ /** The chat as the session lists it (a chat record or a persisted state row), if it does. */
+ private listedChat(chatId: string): ChatSummary | undefined {
const id = this.host.toNeutralJid(this.host.chatJid(chatId));
- return this.host.listChats().some(chat => chat.id === id && chat.archived === true);
+ return this.host.listChats().find(chat => chat.id === id);
}
/**
* 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.
+ * list. It is reported as not done for an archived chat, which the phone leaves unmarked then, and
+ * for a chat the session does not know.
*/
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;
+ const { range, known } = await this.chatWriteRange(chatId, stored);
+ if (!range && (!known || this.listedChat(chatId)?.archived === true)) return false;
await this.confirmed(
this.sock().chatModify(
{ markRead: false, lastMessages: range?.lastMessages ?? [] },
@@ -546,7 +550,7 @@ export class BaileysContacts {
async clearChatMessages(chatId: string, stored?: StoredChatMessageLookup): Promise<boolean> {
this.host.ensureReady();
- const range = await this.chatWriteRange(chatId, stored);
+ 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
}
@@ -557,10 +561,15 @@ export class BaileysContacts {
return true;
}
- /** Without a known message the change goes out with no range, which WhatsApp applies as well. */
+ /**
+ * Without a known message the change goes out with no range, which WhatsApp applies as well, but
+ * only for a chat the session knows. Baileys replays its own patch locally, so archiving an id the
+ * account has no chat with would list that chat from then on.
+ */
async archiveChat(chatId: string, archive: boolean, stored?: StoredChatMessageLookup): Promise<boolean> {
this.host.ensureReady();
- const range = await this.chatWriteRange(chatId, stored);
+ const { range, known } = await this.chatWriteRange(chatId, stored);
+ if (!range && !known) return false;
await this.confirmed(
this.sock().chatModify(
{ archive, lastMessages: range?.lastMessages ?? [] },
@@ -590,7 +599,7 @@ export class BaileysContacts {
async deleteChat(chatId: string, stored?: StoredChatMessageLookup): Promise<boolean> {
this.host.ensureReady();
- const range = await this.chatWriteRange(chatId, stored);
+ 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
}
@@ -601,3 +610,20 @@ export class BaileysContacts {
return true;
}
}
+
+type WriteTarget = { jid: string; key: WAMessageKey; timestamp: number };
+type ChatWriteRange = { jid: string; lastMessages: { key: WAMessageKey; messageTimestamp: number }[] };
+
+function target(
+ jid: string,
+ id: string,
+ fromMe: boolean,
+ participant: string | undefined,
+ timestamp: number,
+): WriteTarget {
+ return { jid, key: { remoteJid: jid, fromMe, id, ...(participant ? { participant } : {}) }, timestamp };
+}
+
+function toRange(write: WriteTarget): ChatWriteRange {
+ return { jid: write.jid, lastMessages: [{ key: write.key, messageTimestamp: write.timestamp }] };
+}
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index a8bc36b3c..6d7620736 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -7073,12 +7073,16 @@ describe('BaileysAdapter sendSeen + markUnread + deleteChat', () => {
);
});
- // 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 () => {
+ // WhatsApp applies an unread mark with no range to a chat in the list (#1891), so a listed chat the
+ // session knows no message of is still marked; an id the account has no chat with is not.
+ it('markUnread marks a listed chat with no known message without a range, and declines an unknown id', 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();
+
+ fakeSock.fire('chats.upsert', [{ id: '[email protected]' }]);
expect(await adapter.markUnread('[email protected]')).toBe(true);
expect(fakeSock.chatModify).toHaveBeenCalledWith({ markRead: false, lastMessages: [] }, '[email protected]');
});
@@ -7297,11 +7301,16 @@ describe('BaileysAdapter sendSeen + markUnread + deleteChat', () => {
);
});
- // 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 () => {
+ // WhatsApp applies an archive with no range (#1891), so a listed chat with no known message is
+ // archived too. An unknown id is not: Baileys replays its own patch locally, which would list it.
+ it('archiveChat archives a listed chat with no known message without a range, and declines an unknown id', 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();
+
+ fakeSock.fire('chats.upsert', [{ id: '[email protected]' }]);
expect(await adapter.archiveChat('[email protected]', true)).toBe(true);
expect(fakeSock.chatModify).toHaveBeenCalledWith({ archive: true, lastMessages: [] }, '[email protected]');
});
@@ -7519,14 +7528,93 @@ describe('BaileysAdapter chat writes keyed to a message (#1891)', () => {
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) => {
+ ])(
+ 'with %s, clear and delete decline, and archive goes out without a range only for a listed chat',
+ 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);
+ await expect(adapter.archiveChat('[email protected]', false, make())).resolves.toBe(false);
+ await expect(adapter.markUnread('[email protected]', make())).resolves.toBe(false);
+ expect(fakeSock.chatModify).not.toHaveBeenCalled();
+
+ fakeSock.fire('chats.upsert', [{ id: '[email protected]' }]);
+ await expect(adapter.clearChatMessages('[email protected]', make())).resolves.toBe(false);
+ await expect(adapter.archiveChat('[email protected]', false, make())).resolves.toBe(true);
+ expect(fakeSock.chatModify).toHaveBeenCalledWith({ archive: false, lastMessages: [] }, '[email protected]');
+ },
+ );
+
+ it('archives a chat known only by a stored message without a range, and the store makes the chat known', async () => {
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();
+ // A stored received group message without its sender gives no usable key, but the chat exists.
+ const stored = lookup({ id: 'G1', fromMe: false, timestamp: 1690000000 });
+ await expect(adapter.archiveChat('[email protected]', true, stored)).resolves.toBe(true);
+ expect(fakeSock.chatModify).toHaveBeenCalledWith({ archive: true, lastMessages: [] }, '[email protected]');
+ });
- await expect(adapter.archiveChat('[email protected]', false, make())).resolves.toBe(true);
- expect(fakeSock.chatModify).toHaveBeenCalledWith({ archive: false, lastMessages: [] }, '[email protected]');
+ it('keys a stored message by the lid the stored row brings when the session cache holds no mapping', async () => {
+ const adapter = await ready();
+ await adapter.clearChatMessages(
+ lookup({ id: 'S1', fromMe: false, timestamp: 1690000000, lid: '484848@lid' }),
+ );
+ expect(fakeSock.chatModify).toHaveBeenLastCalledWith(
+ {
+ clear: true,
+ lastMessages: [{ key: { remoteJid: '484848@lid', fromMe: false, id: 'S1' }, messageTimestamp: 1690000000 }],
+ },
+ '484848@lid',
+ );
+
+ await adapter.clearChatMessages(
+ lookup({ id: 'G1', fromMe: false, author: '[email protected]', authorLid: '555@lid', timestamp: 1690000001 }),
+ );
+ expect(fakeSock.chatModify).toHaveBeenLastCalledWith(
+ {
+ clear: true,
+ lastMessages: [
+ {
+ key: { remoteJid: '[email protected]', fromMe: false, id: 'G1', participant: '555@lid' },
+ messageTimestamp: 1690000001,
+ },
+ ],
+ },
+ );
+ });
+
+ it('keys a message held in memory under the jid it arrived with, even when a lid is known for the chat', async () => {
+ 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: '[email protected]', fromMe: false, id: 'PN1' });
+ await adapter.clearChatMessages('[email protected]');
+ expect(fakeSock.chatModify).toHaveBeenLastCalledWith(
+ {
+ clear: true,
+ lastMessages: [
+ { key: { remoteJid: '[email protected]', fromMe: false, id: 'PN1' }, messageTimestamp: 1700000020 },
+ ],
+ },
+ );
+
+ await upsert({ remoteJid: '[email protected]', fromMe: false, id: 'GPN', participant: '[email protected]' });
+ await adapter.clearChatMessages('[email protected]');
+ expect(fakeSock.chatModify).toHaveBeenLastCalledWith(
+ {
+ clear: true,
+ lastMessages: [
+ {
+ key: { remoteJid: '[email protected]', fromMe: false, id: 'GPN', participant: '[email protected]' },
+ messageTimestamp: 1700000020,
+ },
+ ],
+ },
+ );
});
it('marks an archived chat unread only with a known message, since the phone ignores it without one', async () => {
diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.ts
index 0fcd97bb1..a84e7f493 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) 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",
+ "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 for a chat the session knows, which WhatsApp applies as well; an unknown id resolves false",
},
getBlockedContacts: {
wwjs: { status: 'supported' },
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index 1d36144e9..8e58716a2 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -1584,6 +1584,12 @@ export interface StoredChatMessage {
author?: string;
/** Epoch seconds. */
timestamp: number;
+ /**
+ * The `<lid>@lid` of a 1:1 chat, and of `author`, as the persisted lid mapping holds them. Read from
+ * the table rather than an in-memory cache, which can lack a mapping; absent when none is known.
+ */
+ lid?: string;
+ authorLid?: string;
}
/**
@@ -1615,7 +1621,7 @@ export interface ChatCapability {
/**
* 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.
+ * key the mark to; a chat that is not archived is marked without one if the session knows it.
*/
markUnread(chatId: string, stored?: StoredChatMessageLookup): Promise<boolean>;
@@ -1627,7 +1633,8 @@ export interface ChatCapability {
/**
* 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.
+ * without one when none is known, which WhatsApp applies as well, but only for a chat the session
+ * knows (a chat record, a persisted state row or a stored message); otherwise it resolves false.
*/
archiveChat(chatId: string, archive: boolean, stored?: StoredChatMessageLookup): Promise<boolean>;
diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.ts
index d819b9f50..fb3d1770f 100644
--- a/src/modules/session/session.controller.ts
+++ b/src/modules/session/session.controller.ts
@@ -812,7 +812,8 @@ export class SessionController {
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.',
+ 'without one, which WhatsApp applies as well, for a chat the session knows; an id it knows no ' +
+ 'chat for answers `false`.',
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 93c7ec41f..2728659d6 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -4,6 +4,7 @@ import { PresenceStore } from './presence-store.service';
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken, getDataSourceToken } from '@nestjs/typeorm';
import { Repository, DataSource, In, IsNull, LessThanOrEqual, Not, QueryFailedError } from 'typeorm';
+import type { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
import {
NotFoundException,
ConflictException,
@@ -8496,10 +8497,12 @@ describe('SessionService', () => {
timestamp: 1690000000,
});
+ // The chat's lid comes from the table-backed lookup, which the engine's cache can lack.
await expect(lookupOf('markUnread', () => service.markUnread('sess-uuid-1', '[email protected]'))).resolves.toEqual({
id: 'S1',
fromMe: true,
timestamp: 1690000000,
+ lid: '999@lid',
});
const base = {
sessionId: 'sess-uuid-1',
@@ -8513,7 +8516,10 @@ describe('SessionService', () => {
);
});
- it('in a group, takes an own message or a received one with its sender', async () => {
+ it('in a group, takes an own message or a received one with its sender, and its lid from the table', async () => {
+ (lidMappingStore.findLidsForPhone as jest.Mock).mockImplementation((phone: string) =>
+ Promise.resolve(phone === '628222' ? ['555'] : []),
+ );
(messageRepository.findOne as jest.Mock).mockResolvedValueOnce({
waMessageId: 'G1',
direction: MessageDirection.INCOMING,
@@ -8523,7 +8529,14 @@ describe('SessionService', () => {
await expect(
lookupOf('clearChatMessages', () => service.clearChatMessages('sess-uuid-1', '[email protected]')),
- ).resolves.toEqual({ id: 'G1', fromMe: false, author: '[email protected]', timestamp: 1690000001 });
+ ).resolves.toEqual({
+ id: 'G1',
+ fromMe: false,
+ author: '[email protected]',
+ authorLid: '555@lid',
+ timestamp: 1690000001,
+ });
+ expect(lidMappingStore.findLidsForPhone).toHaveBeenCalledWith('628222');
const base = {
sessionId: 'sess-uuid-1',
chatId: In(['[email protected]']),
@@ -8541,6 +8554,66 @@ describe('SessionService', () => {
expect(whereOf()).toEqual([expect.objectContaining({ direction: MessageDirection.INCOMING })]);
});
+ // The query itself, on a real database: the id-form `In`, the group sender rule and the ordering.
+ describe('against a real database', () => {
+ let db: DataSource;
+ let messages: Repository<Message>;
+
+ beforeAll(async () => {
+ db = new DataSource({ type: 'better-sqlite3', database: ':memory:', entities: [Message], synchronize: true });
+ await db.initialize();
+ messages = db.getRepository(Message);
+ const row = (
+ chatId: string,
+ waMessageId: string | null,
+ direction: MessageDirection,
+ timestamp: number,
+ author?: string,
+ ) => ({ sessionId: 'sess-uuid-1', chatId, waMessageId, direction, timestamp, author, from: 'a', to: 'b' });
+ await messages.insert([
+ row('[email protected]', 'OUT', MessageDirection.OUTGOING, 100),
+ row('999@lid', 'IN', MessageDirection.INCOMING, 200),
+ row('[email protected]', null, MessageDirection.INCOMING, 300),
+ row('[email protected]', 'OTHER', MessageDirection.INCOMING, 400),
+ row('[email protected]', 'G-ANON', MessageDirection.INCOMING, 500),
+ row('[email protected]', 'G-OWN', MessageDirection.OUTGOING, 300),
+ row('[email protected]', 'G-IN', MessageDirection.INCOMING, 250, '[email protected]'),
+ ] as QueryDeepPartialEntity<Message>[]);
+ });
+
+ afterAll(async () => {
+ await db.destroy();
+ });
+
+ beforeEach(() => {
+ Object.assign(service as unknown as Record<string, unknown>, { messageRepository: messages });
+ (lidMappingStore.findLidsForPhone as jest.Mock).mockImplementation((phone: string) =>
+ Promise.resolve(phone === '123' ? ['999'] : []),
+ );
+ });
+
+ it("finds a 1:1 chat's newest message under its lid twin and skips rows without an id", async () => {
+ await expect(lookupOf('markUnread', () => service.markUnread('sess-uuid-1', '[email protected]'))).resolves.toEqual({
+ id: 'IN',
+ fromMe: false,
+ timestamp: 200,
+ lid: '999@lid',
+ });
+ });
+
+ it('in a group, skips a received message without its sender, and a receipt takes only a received one', async () => {
+ await expect(
+ lookupOf('clearChatMessages', () => service.clearChatMessages('sess-uuid-1', '[email protected]')),
+ ).resolves.toMatchObject({ id: 'G-OWN', fromMe: true, timestamp: 300 });
+ await expect(lookupOf('sendSeen', () => service.sendSeen('sess-uuid-1', '[email protected]'))).resolves.toMatchObject({
+ id: 'G-IN',
+ fromMe: false,
+ author: '[email protected]',
+ timestamp: 250,
+ });
+ });
+ });
+
it('is not read until the engine asks for it', async () => {
mockEngine.deleteChat.mockResolvedValueOnce(false);
await service.deleteChat('sess-uuid-1', '[email protected]');
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 5e2edd6e5..b3cbe757e 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -1181,15 +1181,30 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
select: { id: true, waMessageId: true, direction: true, author: true, timestamp: true },
});
if (!row) return null;
+ // The lids the engine keys a lid-migrated chat by, read from the persisted mapping: the engine's
+ // own cache can lack them (#1901).
+ const lid = expanded.find(candidate => parseWaId(candidate).kind === 'lid');
+ const authorLid = row.author ? await this.persistedLidOf(row.author) : undefined;
return {
id: row.waMessageId,
fromMe: row.direction === MessageDirection.OUTGOING,
...(row.author ? { author: row.author } : {}),
timestamp: row.timestamp,
+ ...(lid ? { lid } : {}),
+ ...(authorLid ? { authorLid } : {}),
};
};
}
+ /** The `<lid>@lid` the persisted mapping holds for a person, or undefined. */
+ private async persistedLidOf(jid: string): Promise<string | undefined> {
+ const parsed = parseWaId(jid);
+ if (parsed.kind === 'lid') return `${parsed.userPart}@lid`;
+ if (parsed.kind !== 'user') return undefined;
+ const [lid] = await this.lidMappingStore.findLidsForPhone(parsed.userPart);
+ return lid ? `${lid}@lid` : undefined;
+ }
+
/**
* 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 message in memory or stored to key the
@@ -1208,7 +1223,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
/**
* 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.
+ * without one for a chat the session knows, which WhatsApp applies too.
*/
async archiveChat(id: string, chatId: string, archive: boolean): Promise<boolean> {
await this.findOne(id); // Verify session exists