Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): key a chat's preview by the id the chat is stored under
Yudhi Armyndharis9d6b21bd1983
diff --git a/src/engine/adapters/baileys-session-store.spec.ts b/src/engine/adapters/baileys-session-store.spec.tsindex d0b1781bc..801f63ed4 100644--- a/src/engine/adapters/baileys-session-store.spec.ts+++ b/src/engine/adapters/baileys-session-store.spec.ts@@ -339,6 +339,7 @@ describe('BaileysSessionStore', () => {expect(store.lastMessage('[email protected]')).toEqual({key: { remoteJid: '[email protected]', fromMe: false, id: 'NEW' },timestamp: 200,+ jid: '[email protected]',});});@@ -601,6 +602,67 @@ describe('BaileysSessionStore', () => {});});+ describe('one preview per chat across id dialects', () => {+ const PHONE = '[email protected]';+ const LID = '484848@lid';+ const msg = (remoteJid: string, id: string, ts: number, fromMe = false) => ({+ key: { remoteJid, fromMe, id },+ message: { conversation: id },+ messageTimestamp: ts,+ });++ it('files an own send addressed as @c.us under the chat Baileys keyed by phone', () => {+ store.upsertChats([{ id: PHONE, conversationTimestamp: 5 }]);+ store.recordMessage(msg('[email protected]', 'OUT', 100, true));+ expect(store.listChats()).toEqual([+ expect.objectContaining({ id: '[email protected]', timestamp: 100, lastMessage: 'OUT' }),+ ]);+ expect(store.lastMessage('[email protected]')).toEqual(expect.objectContaining({ jid: PHONE }));+ });++ it('files a lid-addressed send under the phone-keyed chat once the mapping is known', () => {+ store.upsertChats([{ id: PHONE }]);+ store.addLidMappings([{ lid: LID, pn: PHONE }]);+ store.recordMessage(msg(LID, 'OUT', 100, true));+ expect(store.listChats()).toEqual([expect.objectContaining({ timestamp: 100, lastMessage: 'OUT' })]);+ });++ it('finds a lid-keyed chat from the @c.us id the listing publishes', () => {+ store.upsertChats([{ id: LID }]);+ store.recordKeyLidMappings({ remoteJid: LID, remoteJidAlt: PHONE });+ store.recordMessage(msg(LID, 'IN', 100));+ expect(store.listChats()[0].id).toBe('[email protected]');+ expect(store.lastMessage('[email protected]')).toEqual({+ key: { remoteJid: LID, fromMe: false, id: 'IN' },+ timestamp: 100,+ jid: LID,+ });+ store.recordMessageEdit('[email protected]', 'IN', 'edited');+ expect(store.listChats()[0].lastMessage).toBe('edited');+ });++ it('finds the lid twin through the persisted table as well', () => {+ const lidStore = {+ getCached: jest.fn(() => undefined),+ resolveLid: jest.fn(() => null),+ lidsForPhone: jest.fn((phone: string) => (phone === '628111' ? ['484848'] : [])),+ remember: jest.fn(() => Promise.resolve()),+ };+ const s = new BaileysSessionStore(lidStore, 'sess-1');+ s.upsertChats([{ id: LID }]);+ s.recordMessage(msg(LID, 'IN', 100));+ expect(s.lastMessage('[email protected]')?.jid).toBe(LID);+ });++ it('keeps one entry when a chat with no record yet is addressed in both dialects', () => {+ store.recordMessage(msg('[email protected]', 'OUT', 100, true));+ store.recordKeyLidMappings({ remoteJid: LID, remoteJidAlt: PHONE });+ store.recordMessage(msg(LID, 'IN', 200));+ expect(store.lastMessage('[email protected]')?.key.id).toBe('IN');+ expect(store.lastMessage(LID)?.key.id).toBe('IN');+ });+ });+describe('persistent lid->phone table', () => {const makeFakeLidStore = () => {const map = new Map<string, string | null>();diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.tsindex 2b9552157..904c3c1e8 100644--- a/src/engine/adapters/baileys-session-store.ts+++ b/src/engine/adapters/baileys-session-store.ts@@ -114,6 +114,11 @@ class LruMap<K, V> {values(): IterableIterator<V> {return this.map.values();}++ /** LIVE iterator with the same caveat as {@link values}. */+ entries(): IterableIterator<[K, V]> {+ return this.map.entries();+ }}/** A projected contact with the raw store key it came from, so twins can be folded deterministically. */@@ -331,13 +336,14 @@ export class BaileysSessionStore {// newest-message guard so every inbound refreshes it; the timer is cached under both the raw and// neutral JID so an outbound send addressed in either dialect (phone or @lid) finds it.this.recordEphemeralFromMessage(chatId, msg);+ const key = this.chatKey(chatId);const timestamp = this.toUnixSeconds(msg.messageTimestamp);- const existing = this.lastMessages.get(chatId);+ const existing = this.lastMessages.get(key);if (existing && existing.timestamp >= timestamp) {return; // keep the newest}const text = msg.message?.conversation ?? msg.message?.extendedTextMessage?.text ?? '';- this.lastMessages.set(chatId, { key: msg.key, timestamp, text });+ this.lastMessages.set(key, { key: msg.key, timestamp, text });}/**@@ -346,10 +352,42 @@ export class BaileysSessionStore {*/recordMessageEdit(chatId: string, messageId: string, text: string): void {if (!messageId) return;- const rawChatId = this.lastMessages.has(chatId) ? chatId : this.toEngineJid(chatId);- const existing = this.lastMessages.get(rawChatId);+ const key = this.chatKey(chatId);+ const existing = this.lastMessages.get(key);if (!existing || existing.key.id !== messageId) return;- this.lastMessages.set(rawChatId, { ...existing, text });+ this.lastMessages.set(key, { ...existing, text });+ }++ /**+ * The key a chat's preview is kept under, for an id in any dialect. One conversation reaches this+ * store as `<phone>@c.us` (the API and the listing), `<phone>@s.whatsapp.net` and `<lid>@lid`+ * (Baileys, which addresses a lid-migrated contact by its lid and sends to whatever it is given).+ * Keying each spelling separately left an API send or an inbound message on a twin the chat row+ * never reads, so the chat showed no preview and chat actions found no history. The chat record+ * decides: the twin Baileys keyed the chat under wins, then a twin that already holds a preview,+ * and a chat known under neither falls back to the engine dialect.+ */+ private chatKey(jid: string): string {+ if (this.chats.has(jid)) return jid;+ const twins = this.chatTwins(jid);+ return twins.find(k => this.chats.has(k)) ?? twins.find(k => this.lastMessages.has(k)) ?? this.toEngineJid(jid);+ }++ /** 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);+ const twins = [jid, this.toEngineJid(jid)];+ if (parsed.kind === 'lid') {+ twins.push(`${parsed.userPart}@lid`);+ const phone = this.resolvePhone(jid);+ if (phone) twins.push(`${phone}@s.whatsapp.net`);+ } else if (parsed.kind === 'user') {+ for (const [lid, pn] of this.lidToPn.entries()) {+ if (userPart(pn) === parsed.userPart) twins.push(lid);+ }+ for (const lid of this.lidStore?.lidsForPhone(parsed.userPart) ?? []) twins.push(`${lid}@lid`);+ }+ return twins;}/**@@ -474,9 +512,11 @@ export class BaileysSessionStore {return [...this.chats.values()].map(c => this.toNeutralChat(c));}- lastMessage(chatId: string): { key: WAMessageKey; timestamp: number } | null {- const m = this.lastMessages.get(chatId) ?? this.lastMessages.get(this.toEngineJid(chatId));- return m ? { key: m.key, timestamp: m.timestamp } : null;+ /** The chat's newest message, with `jid`, the id the chat itself is keyed under. */+ lastMessage(chatId: string): { key: WAMessageKey; timestamp: number; jid: string } | null {+ const jid = this.chatKey(chatId);+ const m = this.lastMessages.get(jid);+ return m ? { key: m.key, timestamp: m.timestamp, jid } : null;}/**diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 9892ae7a9..6f3a424fa 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -4528,6 +4528,46 @@ describe('BaileysAdapter store-backed ops', () => {});});+ describe('an API send addressed in another dialect than the chat is keyed by', () => {+ /** Baileys keys the sent message by exactly the jid it was handed, whatever its dialect. */+ const echoSend = () =>+ fakeSock.sendMessage.mockImplementation((jid: string, content: { text?: string }) =>+ Promise.resolve({+ key: { id: 'OUT', remoteJid: jid, fromMe: true },+ message: { extendedTextMessage: { text: content.text } },+ messageTimestamp: 1700000100,+ }),+ );+ afterEach(() => {+ fakeSock.signalRepository = undefined;+ });++ it.each([+ ['an unmapped @c.us id to a phone-keyed chat', '[email protected]', '[email protected]', null],+ ['a phone id to a phone-keyed chat whose lid is known', '[email protected]', '[email protected]', '484848@lid'],+ ['a phone id to a lid-keyed chat', '[email protected]', '484848@lid', '484848@lid'],+ ])('%s still becomes the chat preview and sort time', async (_label, sendTo, chatKey, lid) => {+ fakeSock.signalRepository = { lidMapping: { getLIDForPN: jest.fn().mockResolvedValue(lid) } };+ echoSend();+ const adapter = await ready();+ fakeSock.fire('chats.upsert', [{ id: chatKey, conversationTimestamp: 1700000000 }]);+ await adapter.sendTextMessage(sendTo, 'on its way');+ expect(await adapter.getChats()).toEqual([+ expect.objectContaining({ id: '[email protected]', timestamp: 1700000100, lastMessage: 'on its way' }),+ ]);++ fakeStore.getMessage.mockResolvedValue({+ key: { id: 'OUT', remoteJid: lid ?? sendTo, fromMe: true },+ message: { extendedTextMessage: { text: 'on its way' } },+ messageTimestamp: 1700000100,+ });+ await adapter.editMessage('[email protected]', 'OUT', 'arriving tomorrow');+ expect((await adapter.getChats())[0]?.lastMessage).toBe('arriving tomorrow');+ await adapter.deleteMessage('[email protected]', 'OUT', true);+ expect((await adapter.getChats())[0]?.lastMessage).toBe('');+ });+ });+it('clears the store on logout', async () => {const adapter = await ready();await adapter.logout();