Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): look a listed chat up under its lid or phone twin
Yudhi Armyndharise963fe611a7d
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex 8d0679643..86329cd67 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -986,8 +986,9 @@ adapter boundary — none silently stubs.message ids resolve `false`. With no usable message, clear and delete resolve `false`, and archiveand unread are sentwithout a range for a chat the session knows (a chat record, a persisted state row or a stored- message) whose jid belongs to it, and resolve `false` otherwise; unread also resolves `false` for an- archived chat, which the phone leaves unmarked without a range. `sendSeen`+ message, under its lid or its phone whichever the caller names) whose jid belongs to it, 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, inmemory 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` withdiff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex 6efcf77ab..1663b0b96 100644--- a/src/engine/adapters/baileys-contacts.ts+++ b/src/engine/adapters/baileys-contacts.ts@@ -51,6 +51,8 @@ export interface BaileysContactsHost {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;+ /** Every spelling of one chat the session can connect: the id, its engine form, and its lid or phone twin. */+ chatTwins(jid: string): string[];/*** 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`@@ -543,7 +545,7 @@ export class BaileysContacts {const row = await this.readStored(chatId, stored);const fromStore = row ? this.storedTarget(chatId, row) : null;if (fromStore && (await this.matchesChat(fromStore.key, chatId, socket))) return toRange(fromStore);- if (!rangeless() || !(last || row || this.listedChat(chatId))) return null;+ if (!rangeless() || !(last || row || this.listedChats(chatId).length)) return null;const jid = this.host.chatJid(chatId);return (await this.matchesChat({ remoteJid: jid }, chatId, socket)) ? { jid, lastMessages: [] } : null;}@@ -589,10 +591,13 @@ export class BaileysContacts {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().find(chat => chat.id === id);+ /**+ * The chat as the session lists it (a chat record or a persisted state row) under any spelling of it: a+ * row is keyed by the lid or the phone it was learned under, whichever form the caller writes it with.+ */+ private listedChats(chatId: string): ChatSummary[] {+ const ids = new Set(this.host.chatTwins(chatId).map(jid => this.host.toNeutralJid(jid)));+ return this.host.listChats().filter(chat => ids.has(chat.id));}/**@@ -603,7 +608,12 @@ export class BaileysContacts {async markUnread(chatId: string, stored?: StoredChatMessageLookup): Promise<boolean> {this.host.ensureReady();const socket = this.sock();- const range = await this.chatWriteRange(socket, chatId, stored, () => this.listedChat(chatId)?.archived !== true);+ const range = await this.chatWriteRange(+ socket,+ chatId,+ stored,+ () => !this.listedChats(chatId).some(c => c.archived),+ );if (!range) return false;await this.confirmed(this.sock(socket).chatModify({ markRead: false, lastMessages: range.lastMessages }, range.jid),diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.tsindex ca0841fec..4ad0a6de5 100644--- a/src/engine/adapters/baileys-session-store.ts+++ b/src/engine/adapters/baileys-session-store.ts@@ -518,7 +518,7 @@ export class BaileysSessionStore {}/** 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[] {+ chatTwins(jid: string): string[] {const parsed = parseWaId(jid);const twins = [jid, this.toEngineJid(jid)];if (parsed.kind === 'lid') {diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex e52b19098..1d1f56562 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -8491,6 +8491,55 @@ describe('BaileysAdapter chat writes keyed to a message (#1891)', () => {await expect(act(confirmed)).resolves.toBe(true);expect(fakeSock.chatModify).toHaveBeenCalledWith({ ...change, lastMessages: [] }, '484848@lid');});++ // A new engine holds no chat record, so a chat it has not heard from since is known by its persisted state+ // alone, filed under the lid or the phone it was learned under, whichever form the caller writes it with.+ describe('for a chat listed under its other spelling', () => {+ const stateRow = (key: string, archived: boolean) => ({+ get: jest.fn((_s: string, chatId: string) =>+ chatId === key ? { muteEndTime: null, archived, pinned: false } : undefined,+ ),+ chatIds: jest.fn(() => [key]),+ remember: jest.fn().mockResolvedValue(undefined),+ fold: jest.fn().mockResolvedValue(undefined),+ reload: jest.fn().mockResolvedValue(undefined),+ clearSession: jest.fn().mockResolvedValue(undefined),+ forget: jest.fn().mockResolvedValue(undefined),+ refreshSession: jest.fn().mockResolvedValue(undefined),+ });+ const linked = async (+ chatStateStore: ReturnType<typeof stateRow>,+ lidMappingStore: ReturnType<typeof reported>,+ ): Promise<BaileysAdapter> => {+ const adapter = new BaileysAdapter({+ sessionId: 'sess-1',+ dbSessionId: 'db-uuid-1',+ authDir: './data/baileys',+ messageStore: fakeStore,+ lidMappingStore,+ chatStateStore,+ });+ await adapter.initialize({});+ fakeSock.fire('connection.update', { connection: 'open' });+ fakeSock.fire('lid-mapping.update', { lid: '484848@lid', pn: '[email protected]' });+ return adapter;+ };++ it('archives it without a range when the caller names its lid', async () => {+ const adapter = await linked(stateRow('[email protected]', false), reported());+ await expect(adapter.archiveChat('484848@lid', true, lookup(null))).resolves.toBe(true);+ expect(fakeSock.chatModify).toHaveBeenCalledWith({ archive: true, lastMessages: [] }, '484848@lid');+ });++ it('does not mark it unread without a range when it is archived under its lid and the caller names its phone', async () => {+ const adapter = await linked(stateRow('484848@lid', true), reported());+ // Filed under a lid the engine never reported for the phone, the stored message keys no range.+ const stored = lookup({ id: 'S1', fromMe: false, timestamp: 1690000000, lid: '484848@lid' });+ await expect(adapter.markUnread('[email protected]', stored)).resolves.toBe(false);+ expect(stored).toHaveBeenCalled();+ expect(fakeSock.chatModify).not.toHaveBeenCalled();+ });+ });});describe('BaileysAdapter status posting', () => {diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex a33242383..bdf4fd7ab 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -197,6 +197,7 @@ export class BaileysAdapter implements IWhatsAppEngine {lastMessage: chatId => this.sessionStore.lastMessage(chatId),lastInboundMessage: chatId => this.sessionStore.lastInboundMessage(chatId),lidOf: jid => this.sessionStore.lidOf(jid),+ chatTwins: jid => this.sessionStore.chatTwins(jid),upsertContacts: records => this.sessionStore.upsertContacts(records),upsertChats: records => this.sessionStore.upsertChats(records),removeChats: ids => this.sessionStore.removeChats(ids),